首页 > 解决方案 > 为什么当按下 Jbutton 并在 java 中执行其定义的功能时,我无法在我的应用程序中执行任何操作?

问题描述

这就是我试图做到这一点的方式:

btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Hello there");
                Thread.sleep(1000);
                panel.updateUI();
            }
});             

我将 Enter 按钮设置为默认按钮,所以当我继续按下它时,按钮可能按下 100 次或更多,但因为我使用Thread.sleep(1000)它需要一些时间,所以我有时间输入我的 JtextField 甚至关闭窗口但不能做任何事情。

另外,我尝试放入btnNewButton.addActionListener()线程的运行方法,但没有区别。

Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                btnNewButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                         System.out.println("Hello there");
                        Thread.sleep(1000);
                        panel.updateUI();
                    }
                });
            }
        });
thread.start();
// I used try catch block in real code

谁能帮我解决这个问题?

**我正在使用 windowsBuilder 在 Eclipse 中创建此应用程序。

标签: javamultithreadingswingjframe

解决方案


不完全确定你的代码应该做什么,但如果你想按下按钮,然后 1000 毫秒后它会检查你的字段,你应该这样做:

Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("before 1000ms");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("after 1000ms");
                System.out.println("Reading the text field ...");
            }
        });
        thread.start();
        System.out.println("after the thread");

输出:

after the thread
before 1000ms
after 1000ms
Reading the text field ...

推荐阅读