代码:
public class TestSwing extends JFrame implements ActionListener {
private staticfinal long serialVersionUID = 1L;
private JLabellblUsername; // 标签-用户名
private JLabellblPassword; // 标签-密码
private JTextFieldtfUsername; // 文本框-用户名
privateJPasswordField tfPassword; // 密码框-用户名
private JButtonbtnOK; // 按钮-确认
private JButtonbtnExit; // 按钮-退出
public TestSwing(){
// 容器1-用户名
JPanel p1 = newJPanel();
p1.setLayout(newBorderLayout());
lblUsername = newJLabel("用户名:");
tfUsername = newJTextField(12);
p1.add(lblUsername, BorderLayout.WEST);
p1.add(tfUsername,BorderLayout.EAST);
// 容器2-密码
JPanel p2 = newJPanel();
p2.setLayout(newBorderLayout());
lblPassword = newJLabel("密码:");
tfPassword = newJPasswordField(12);
p2.add(lblPassword, BorderLayout.WEST);
p2.add(tfPassword,BorderLayout.EAST);
// 容器3-按钮
JPanel p3 = newJPanel();
btnOK = newJButton("登录");
btnOK.addActionListener(this);
btnExit = newJButton("取消");
btnExit.addActionListener(this);
p3.add(btnOK);
p3.add(btnExit);
this.add(p1,BorderLayout.NORTH);
this.add(p2,BorderLayout.CENTER);
this.add(p3,BorderLayout.SOUTH);
this.setLocation(400, 300);
this.setSize(300,110);
this.setTitle("密码验证");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true); // 默认可见
}
@SuppressWarnings("deprecation")
public voidactionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("登录")) {
JOptionPane.showMessageDialog(this,"用户名为:" +tfUsername.getText()
+ "\n" + "密码为:" + String.valueOf(tfPassword.getText()));
} else if(e.getActionCommand().equals("取消")) {
System.exit(0);
}
}
public static voidmain(String[] args) {
new TestSwing();
}
}
窗口: