This exhaustive example illustrates JPasswordField in swing. This covers all core methods of javax.swing.JPasswordField class.
import javax.swing.*;
import java.awt.*;
import java.io.*;
class JPasswordFieldDemo extends JFrame
{
JPasswordField p1,p2,p3,p4;
public JPasswordFieldDemo()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("JPasswordField Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
p1=new JPasswordField();
p2=new JPasswordField(20);
p3=new JPasswordField("Password");
p4=new JPasswordField("Password 4",20);
// Set text
p1.setText("Password 1");
p2.setText("Password 2");
// Set echo char
p1.setEchoChar('*');
// Get echo char
System.out.println("Echo char for p1 "+p1.getEchoChar());
// Is echo char set
System.out.println("Is echo char set for p1 "+p1.echoCharIsSet());
// Get password
char[] pass=p2.getPassword();
for(int i=0;i<pass.length;i++)
{
System.out.print(pass[i]);
}
// Set cols
p1.setColumns(22);
// Get columns
System.out.println("Cols in p1 is "+p1.getColumns());
// Set horizontal alignment
// default is LEFT
p1.setHorizontalAlignment(JTextField.CENTER);
p2.setHorizontalAlignment(JTextField.RIGHT);
// Set font
p3.setFont(new Font("Tahoma",Font.PLAIN,18));
// Set caret color
p4.setCaretColor(Color.RED);
// Select some text
p1.select(0,5);
p2.select(0,6);
// Alternative ways for selecting
// p1.setCaretPosition(0);
// p1.moveCaretPosition(6);
// p1.setSelectionStart(0);
// p1.setSelectionEnd(4);
// Get selected password
System.out.println("Selected password in p1 "+p1.getSelectedText());
// Set selection background color
p1.setSelectionColor(Color.DARK_GRAY);
// Set selected text color
p1.setSelectedTextColor(Color.WHITE);
// Set inner margin
p4.setMargin(new Insets(5,5,5,5));
// Replace selected password
p2.replaceSelection("Two");
// Get password
pass=p2.getPassword();
for(int i=0;i<pass.length;i++)
{
System.out.print(pass[i]);
}
// Write password in p1 to file
try{
p1.write(new FileWriter("p1.txt"));
}catch(IOException e){}
// Read from file and put in p4
try{
p4.read(new FileReader("p1.txt"),null);
}catch(IOException e){}
// Make p3 non editable
p3.setEditable(false);
// Disable p4
p4.setEnabled(false);
// Set disabled foreground
p4.setDisabledTextColor(Color.BLUE);
// Set focus accelerator
// Alt+1 gives focus to p1
p1.setFocusAccelerator('1');
p2.setFocusAccelerator('2');
add(p1);
add(p2);
add(p3);
add(p4);
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
new JPasswordFieldDemo();
}
}