更改 java 中不同 class 的标签文本

Change Label text from different class in java

我有一个主图形用户界面 class,它是在 NetBeans 图形用户界面生成器中创建的。我正在创建一个 JLabel 计时器停止运行的迷你游戏。 JLabel 位于主 gui 中,计时器位于单独的 classes 中,例如称为 timer。当定时器的循环正在循环时,我希望位于主 gui 中的 JLabel 发生变化(Timer=10,Timer=9,...等)。

查看下面的示例代码以便更好地理解。

这是定时器所在的class:

public class ShapeGame {

Timer timer;
int counter = 10;

ShapeGame() {

    ActionListener a = new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            System.out.println("Counter = " + counter);
            labTimer.setText("Timer: " + counter);
            if (--counter < 0) {
                timer.stop();
                System.exit(0);
            }
        }
    };

    timer = new Timer(1000, a);
    timer.start();
    }
}

这是 JLabel 所在位置的修改代码:

(注意:并未为 JLabel 和 JFrame 添加所有代码只是为了阅读目的)

public class mainGui extends JFrame {

labTimer = new javax.swing.JLabel();

    private void gameStartStopActionPerformed(java.awt.event.ActionEvent evt) {                                              
        ShapeGame sg = new ShapeGame();
    }
}

我知道这不是从其他 class labTimer.setText("Timer: " + counter); 调用标签的正确方法。希望我提供了足够的信息来帮助解决这个问题。

一个可能的简单(但不干净)解决方案是将 JLabel 传递到 ShapeGame class 以便它可以直接改变其状态。

例如,

public class ShapeGame {
    Timer timer;
    int counter = 10;

    // note change to constructor parameter
    public ShapeGame(final JLabel label) {
        ActionListener a = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Counter = " + counter);

                // note changes
                // labTimer.setText("Timer: " + counter);
                label.setText("Timer: " + counter);

                if (--counter < 0) {
                    timer.stop();
                    System.exit(0);
                }
            }
        };

        timer = new Timer(1000, a);
        timer.start();
    }
}

然后在创建 ShapeGame 时 class,将 JLabel 传递到其构造函数调用中。更清洁的方法是按照 MVC 的方式构建您的程序。