在我们学习java图形化用户页面的时候我们就会使用各种监听器
ActionListener就是一个,当我们想实现例如点击 登录 就去判断账号和密码是否正确来判断下一步时我们就会用可以使用这个监听器来监听你是否点击了登录来判断下一步
是否来判断点击登录后密码和账号是否正确
@Override
public void actionPerformed(ActionEvent e) {
// String s=new String(this.jPPass.getPassword());
if("admin".equals(this.jUser.getText())&&"12345".equals(new String(this.jPPass.getPassword()))){
this.jframe.dispose();
}else{
this.jUser.setText((String)null);
this.jPPass.setText((String)null);
this.jUser.requestFocus();
}
}
}
监听器的外部定义
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class manager implements ActionListener{
private JFrame jframe;
private JTextField jUser;
private JPasswordField jPPass;
// private JButton jb1;
private manager a;
public manager(){}
public manager(JTextField jTfUser, JPasswordField jPfPass, JFrame jFrame){
this.jframe=jFrame;
this.jUser=jTfUser;
this.jPPass=jPfPass;
}
@Override
public void actionPerformed(ActionEvent e) {
// String s=new String(this.jPPass.getPassword());
if("admin".equals(this.jUser.getText())&&"12345".equals(new String(this.jPPass.getPassword()))){
this.jframe.dispose();
}else{
this.jUser.setText((String)null);
this.jPPass.setText((String)null);
this.jUser.requestFocus();
}
}
}
当我们想让他监听某个按钮时
JButton jbtLogin;
manager b;
this.b=new manager(this.jTfUser,this.jPfPass,this.jFrame); this.jbtLogin.addActionListener(b);
import java.awt.*;
import javax.swing.*;
public class app{
Icon[] faces;
JFrame jFrame;
JLabel jlbUser;
JLabel jlbPass;
JTextField jTfUser;
JPasswordField jPfPass;
JButton jbtLogin;
JButton jbtCancel;
JPanel jp1;
JPanel jp2;
JPanel jp3;
JPanel jp4;
Container c;
manager b;
public app(){
faces=new Icon[]{
new ImageIcon("src/img/登录1.png"),
new ImageIcon("src/img/取消1.png"),
};
this.jFrame=new JFrame();
this.jlbUser=new JLabel();
this.jFrame.setBounds(200,200,300,200);
this.jFrame.setBackground(Color.blue);
this.jlbUser=new JLabel("用户");
this.jlbPass=new JLabel("密码");
this.jTfUser=new JTextField(14);
this.jPfPass=new JPasswordField(14);
this.jbtLogin=new JButton("登录");
this.jbtLogin.setIcon(faces[0]);
this.jbtCancel=new JButton("取消");
this.jbtCancel.setIcon(faces[1]);
this.jp1=new JPanel();
this.jp1.setOpaque(false);
this.jp2=new JPanel();
this.jp2.setOpaque(false);
this.jp3=new JPanel();
this.jp3.setOpaque(false);
this.jp4=new JPanel();
this.jp4.setOpaque(false);
this.jp1.add(this.jlbUser);
this.jp1.add(this.jTfUser);
this.jp2.add(this.jlbPass);
this.jp2.add(this.jPfPass);
this.jp3.add(jbtLogin);
this.jp3.add(this.jbtCancel);
this.jp4.add(this.jp1);
this.jp4.add(this.jp2);
this.jp4.add(this.jp3);
this.jFrame.add(this.jp4);
this.jFrame.setBackground(Color.blue);
this.jFrame.setVisible(true);
this.c=jFrame.getContentPane();
this.c.setBackground(Color.cyan);
this.b=new manager(this.jTfUser,this.jPfPass,this.jFrame);
this.jbtLogin.addActionListener(b);
}
}