j2se使用ActionListener实现界面上按钮点击的事件监听操作

来源:互联网 发布:美发店收银软件下载 编辑:程序博客网 时间:2024/05/22 20:49
public class my_eventListener extends JFrame implements ActionListener {//实现接口,要实现所有接口里的方法。//定义一个panelJPanel mp = null;//两个按钮,作为按钮类监听的事件源,而my_eventListener来监听事件,实现一个监听接口JButton jb1 = new JButton("按钮1");JButton jb2 = new JButton("按钮2");public static void main(String[] args) {my_eventListener my = new my_eventListener();}//构造函数public my_eventListener(){mp = new JPanel();this.add(jb1,BorderLayout.NORTH);mp.setBackground(Color.black);this.add(mp);this.add(jb2,BorderLayout.SOUTH);//注册监听,给按钮jb1注册一个在JFrame上的监听。也可以注册其他的class。jb1.addActionListener(this);//指定action命令,当点击jb1时,传递命令blackjb1.setActionCommand("black");jb2.addActionListener(this);jb2.setActionCommand("red");this.setSize(200,150);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}//对事件处理的方法或操作@Overridepublic void actionPerformed(ActionEvent e) {//判断哪个按钮被点击if(e.getActionCommand().equals("black")){System.out.println("点击了black");}if(e.getActionCommand().equals("red")){System.out.println("点击了red");}}}

0 0
原创粉丝点击