java 调用listener_Java:使用actionlistener在该类的对象上调用另一个类中的函数

本文介绍了在Java中如何在ActionListener中调用或修改类内的成员变量。通过使用匿名类和final关键字,或直接访问封闭类的成员,可以在按钮点击事件中实现对对象状态的改变。
摘要由CSDN通过智能技术生成

在匿名类中引用内容的一种方法是使用final关键字:

public static void main(String[] args) {

final Object thingIWantToUse = "Hello";

JButton button = new JButton("Click");

button.addActionListener(new ActionListener() {

@Override public void actionPerformed(ActionEvent e) {

System.out.println(thingIWantToUse);

}

});

JFrame frame = new JFrame();

frame.setLayout(new FlowLayout());

frame.add(button);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();

frame.setVisible(true);

}

或者,您可以访问封闭类型的成员(变量或方法):

public class ActionListenerDemo2 {

private final JFrame frame = new JFrame();

private Object thingIWantToUse = "Hello";

public ActionListenerDemo2() {

JButton button = new JButton("Click");

button.addActionListener(new ActionListener() {

@Override public void actionPerformed(ActionEvent e) {

thingIWantToUse = "Goodbye";

System.out.println(thingIWantToUse);

}

});

frame.setLayout(new FlowLayout());

frame.add(button);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();

frame.setVisible(true);

}

public static void main(String[] args) {

new ActionListenerDemo2().frame.setVisible(true);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值