【问题标题】:Java GUI/Swing, stopping the thread, passing integers between classesJava GUI/Swing,停止线程,在类之间传递整数
【发布时间】:2014-08-12 17:57:18
【问题描述】:

我正在尝试使用 GUI/Swing 模拟轮盘游戏,以应对即将到来的考试。我有两个类,一个称为 GUI,实际上是用于组件的代码,例如 JFrame、JOptionPane、JButtons 等。另一个扩展了 Thread,应该在一个小的 JLabel 上显示随机数,运行方法是像这样:

public void run() {
    int k = 0;
    for (int i = 0; i < 50; i++) {
        k = (new Random().nextInt(37));
        label.setText(k + " ");
        label.setFont(new Font("Tahoma", Font.BOLD, 56));
        label.setForeground(Color.yellow);
        try {
            sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }       
}

在 GUI 类中,我只想从上述循环的最后一次迭代中获取数字,然后将它传递给一个新的 int,稍后我将在 GUI 类中使用它。 有什么想法吗?

【问题讨论】:

  • 按照@Braj 的建议使用摇摆计时器(他的答案为 1+)。另外顺便说一句,您几乎从不想扩展 Thread 类。如果您需要使用基本线程并且绝对不能使用 Swing Timer 或 SwingWorker,那么您希望您的类实现 Runnable,而不是扩展 Thread。

标签: java swing user-interface


【解决方案1】:

使用 Swing Timer 而不是 Thread.sleep 有时会挂起整个 Swing 应用程序。

请看How to Use Swing Timers

Timer timer = new Timer(50, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {            
        //next call from here
    }
});
timer.setRepeats(false);
timer.start();

我只想从上述循环的最后一次迭代中获取数字,然后将其传递给一个新的 int,稍后我将在 GUI 类中使用它。

只需在另一个接受 int 的类中创建一个方法(setter)并从该类中调用它以进行最后一次调用。


示例代码:

private int counter = 0;
private Timer timer;
...

final JLabel label = new JLabel();
label.setFont(new Font("Tahoma", Font.BOLD, 56));
label.setForeground(Color.yellow);
Thread thread = new Thread(new Runnable() {
    public void run() {

        timer = new Timer(50, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (counter++ < 50) {
                    int k = (new Random().nextInt(37));
                    label.setText(k + " ");
                } else {
                    timer.stop();
                    label.setText("next call");
                }

            }
        });
        timer.setRepeats(true);
        timer.start();
    }
});

thread.start();

快照:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多