//program to demonstrate the use of JTextField JPasswordField using Listener Interface.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginForm extends JFrame implements ActionListener {
private Container container;
private JLabel userLabel, passwordLabel;
private JTextField userTextField;
private JPasswordField passwordField;
private JButton loginButton;
public LoginForm() {
setTitle("Login Form");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = getContentPane();
container.setLayout(null);
userLabel = new JLabel("Username:");
userLabel.setBounds(50, 30, 100, 30);
container.add(userLabel);
userTextField = new JTextField();
userTextField.setBounds(150, 30, 150, 30);
container.add(userTextField);
passwordLabel = new JLabel("Password:");
passwordLabel.setBounds(50, 70, 100, 30);
container.add(passwordLabel);
passwordField = new JPasswordField();
passwordField.setBounds(150, 70, 150, 30);
container.add(passwordField);
loginButton = new JButton("Login");
loginButton.setBounds(150, 110, 150, 30);
container.add(loginButton);
loginButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String username = userTextField.getText();
String password = new String(passwordField.getPassword());
System.out.println("Username: " + username);
System.out.println("Password: " + password);
}
public static void main(String[] args) {
LoginForm form = new LoginForm();
form.setVisible(true);
}
}
//Program Code
import javax.swing.*;
import java.awt.*;
public class PasswordFieldExample extends JFrame {
private JPasswordField passwordField;
public PasswordFieldExample() {
setTitle("Password Field Example");
setSize(400,250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
passwordField = new JPasswordField(25);
passwordField.setEchoChar('#');
add(passwordField);
setVisible(true);
}
public static void main(String[] args) {
new PasswordFieldExample();
}
}