栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

我的JButton的ActionListener如何访问另一个类中的变量?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

我的JButton的ActionListener如何访问另一个类中的变量?

尝试

extends GGCGuiLotto
做不会按照您的预期去做,这使您可以访问 相同的 实例变量。所以摆脱它。相反,您可以 通过引用
将当前实例
GGCGuiLotto
传递给侦听器。并具有一些getter和setter方法来从
GGCGuiLotto
类中访问所需的变量。我的意思可能是这样的事情(不确定您要完成的工作,因此仅是示例)。

public class GenPLCListener implements ActionListener {    private GGCGuiLotto lotto;    public GenPLCListener(GGCGuiLotto lotto) {        this.lotto = lotto;    }    @Override    public void actionPerfomred(ActionEvent e) {        List<ImageIcon> slotList = lotto.getSlotList();        Collections.shuffle(slotList);  // shuffle the list        // do something else if need be.    }}

创建侦听器时,将

this
其传递给它。
this
作为…的实例
GGCGuiLotto


很少注意事项

  • Swing程序与控制台程序不同。您不想在

    main
    方法中做任何事情。首先,
    main
    可以将方法中的代码放入构造函数中。然后
    GGCGuiLotto
    main
    方法中创建一个实例。

  • Swing应用程序应在事件调度线程上运行。请参阅初始线程


编辑

对于您的问题,也许更合适的解决方案是

interface
使用
pullSlot
可以在
GGCGuiLotto
类中重写的方法,然后将方法传递
interface
给侦听器并在
pullSlot
您的方法中调用该方法
actionPerformed
。像这样

public interface PullInterface {    public void pullSlot();}public class GGCGuiLotto implements PullInterface {    ArrayList<ImageIcon> slotList = new ArrayList<>();  // global scope.    JLabel aReel1lbl = new JLabel();    JLabel bReel2lbl = new JLabel();    JLabel cReel3lbl = new JLabel();    Random rand = new Random();    public GGCGuiLotto() {        GenPLCListener listener = new GenPLCListener(this);    }    @Override    public void pullSlot() {        // do what you need to do here to implement a pulling of the lever        int r1 = rand.nextInt(slotList.size());        int r2 = rand.nextInt(slotList.size());        int r3 = rand.nextInt(slotList.size());        reel1lbl.setIcon(slotList.get(r1));    }}public class GenPLCListener implement ActionListener {    private PullInterface pull;    public GenPLCListener(PullInterface pull) {        this.pull = pull;    }    @Override    public void actionPerformed(ActionEvent e) {        pull.pullSlot();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/507370.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号