java 按钮 事件_JAVA中按钮的事件监听的三种方式

JAVA中的Swing组件,按钮的重点是进行事件的监听,可以通过调用JButton的addActionListener()方法。这个方法接受一个实现ActionListener接口的对象作为参数,ActionListener接口中只包含一个actionPerformed()方法,所以如果想把事件处理的代码与JButton进行关联,就需要如下的三种做法:

第一种:

public class Button extends MyFrame {

private JButton

b1 = new JButton("Button1"),

b2 = new JButton("Button2");

private JTextField txt = new JTextField(10);

class ButtonListener implements ActionListener{// 定义内部类实现事件监听

public void actionPerformed(ActionEvent e) {

txt.setText(((JButton)e.getSource()).getText()) ;

/*

* String name = ((JButton)e.getSource()).getText();

* txt.setText(name);

*/

}

}

private ButtonListener b = new ButtonListener();

public Button(){

b1.addActionListener(b);

b2.addActionListener(b);

this.setLayout(new FlowLayout());

this.add(b1);

this.add(b2);

this.add(txt);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

new Button();

}

});

}

}

第二种:

//直接创建ActionListener的类的对象b,使用的是匿名内部类

private ActionListener b= new ActionListener(){// 定义内部类实现事件监听

public void actionPerformed(ActionEvent e) {

txt.setText(((JButton)e.getSource()).getText()) ;

/*

* String name = ((JButton)e.getSource()).getText();

* txt.setText(name);

*/

}

};

第三种:

//在程序中直接创建按钮的监听,不需要再引入监听器

b1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {

txt.setText(((JButton)e.getSource()).getText());

}

});

b2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {

txt.setText(" ");

}

});

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值