尝试
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(); }}


