Java swing 应用程序不工作

Java swing application not working

这是我的申请图片:

当按下新按钮时,将显示问题并启动计时器。

但是按下'New'按钮后,定时器既不运行也不显示文本,默认的关闭操作不起作用。当我注释掉 checkTimer() 时,它工作正常。

代码如下:

if(buttonEvent.getActionCommand().equals("New")){
                String store = buttonEvent.getActionCommand();
                startGame();
                checkTimer();

            panelOne.remove(buttonNew);
            panelOne.revalidate();
            panelOne.repaint();
        }

public void startGame(){
    // TODO Auto-generated method stub
    String line = null;
    try{
        BufferedReader reader = new BufferedReader(new FileReader("C:\Users\myPc\Documents\myFile.txt"));
        while((line = reader.readLine()) != null){
            System.out.println(line);
            queue.add(line);
        }
        reader.close();
    }
    catch(IOException exception){
        exception.printStackTrace();
    }
       // flag = true;
        String display = queue.remove();
        textArea.setText(display);
        //checkTimer();
} 


    public void checkTimer() {
    // TODO Auto-generated method stub

    int sec = 59;
    int min = Integer.parseInt(timerField1.getText());

    while(min >= 0){
        min--;
        if(min >= 0){
            for(int i = 0; i < 60; i++){
                try{
                    Thread.sleep(1000);
                }
                catch(InterruptedException ie){
                    Thread.currentThread().interrupt();
                }

                timerField1.setText(Integer.toString(min));
                timerField2.setText(Integer.toString(sec));
                if(sec > 0){
                    sec--;
                }
                else{
                    break;
                }
            }
        }
        //textArea1.setText(Integer.toString(num));
        sec = 59;
    }

}

请指导我为什么它不起作用。

您通过调用 sleep() 在 checkTimer() 中阻止 EventDispatcherThread。事实上,它会阻止重新绘制 UI 和处理所有事件。

而是启动一个新的单独线程并调用 UI 更改,例如

            timerField1.setText(Integer.toString(min));
            timerField2.setText(Integer.toString(sec));

在 SwingUtilities.invokeAndWait() 块内(也可以尝试 invokeLater())

你的问题是你 checkTimer() 它不是一个线程,然后如果你按下新建按钮再次调用 checkTimer() 但是,另一个实例是 运行。您需要为您的时钟使用 Swing Timer,然后当您按下 New 按钮时,您可以停止它。

Thread.sleep(1000);

Event Dispatch Thread (EDT) 上执行代码时不要使用 Thead.sleep。这将导致 GUI 冻结并阻止 GUI 响应事件。

When the new button is pressed the question will be displayed and timer starts.

那么你应该使用 Swing Timer。您可以将计时器设置为每秒触发一次,以便更新时间。然后在 if 触发 300 次后你将停止计时器并且游戏将结束。

阅读有关 How to Use Swing Timers 的 Swing 教程部分,了解更多信息和工作示例。