【问题标题】:Java GUI is frozen but program still running in the terminalJava GUI 被冻结但程序仍在终端中运行
【发布时间】:2021-06-03 11:47:28
【问题描述】:

我正在尝试制作一个简单的 Java GUI 计时器,但每当我按下开始按钮时,GUI 就会冻结并且不允许我点击停止按钮,但程序会继续在终端上完美运行。

这是我的开始按钮的代码:

startButton = new JButton();
startButton.setText("START");
startButton.setFont(new Font("RuneScape UF", Font.PLAIN, 16));
startButton.setFocusable(false);
startButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == startButton) {
            System.out.println("Start button pressed!");
            isRunning = true;
            System.out.println(isRunning);

            long startTime = System.currentTimeMillis();
            while (isRunning) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }

                long elapsedTime = System.currentTimeMillis() - startTime;
                long elapsedSeconds = elapsedTime / 1000;
                if (elapsedSeconds == 60) {
                    elapsedSeconds = 0;
                    startTime = System.currentTimeMillis();
                }
                if ((elapsedSeconds % 60) == 0) {
                    minutesDisplay++;
                }
                if ((minutesDisplay % 60) == 0 && stupidFix > 0) {
                    stupidFix++;
                    hoursDisplay++;
                }
                //System.out.println(elapsedSeconds);
                String h = String.format("%02d", hoursDisplay);
                String m = String.format("%02d", minutesDisplay);
                String s = String.format("%02d", elapsedSeconds);

                timePassed.setText(h + ":" + m + ":" + s);
                System.out.println(h + ":" + m + ":" + s);
            }
        }
    }
});

【问题讨论】:

标签: java swing user-interface


【解决方案1】:

您在按钮操作侦听器中使用while loop。 在按钮动作侦听器中使用 while 循环被认为是一项繁重的任务。为此,您必须使用 SwingWorker

你可以在这里看到它的教程:

https://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html

【讨论】:

  • " 在按钮操作侦听器中使用 while 循环被认为是一项繁重的任务。" 只有 Thread.sleep(..) 会阻塞 EDT,因此不一定是“重”任务。事实上,这最好通过建立一个 SwingTimer 来更新时间。 Anastasia 提供的链接涵盖了这两种情况。
猜你喜欢
  • 2012-08-03
  • 2023-02-08
  • 2011-07-11
  • 2014-10-07
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
相关资源
最近更新 更多