简体   繁体   English

无法似乎在事件处理程序中设置文本

[英]Cant seem to set text in Event Handler

I am fairly new to Java so I am probably missing something fundamental here but here goes. 我对Java还是很陌生,所以这里可能遗漏了一些基本的知识,但是这里就去了。

I have a GUI with a button and I want to click on it, change the text in a window to something then perform a task 我有一个带有按钮的GUI,我想单击它,将窗口中的文本更改为某些内容,然后执行任务

        connectButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    databaseConnectWindow.setText("Connecting...");
                    connectToDatabase();
                 }
        });

But with the code above the text in databaseConnectWindow does not change until after conectToDatabse has finished. 但是使用上面的代码,直到conectToDatabse完成后,databaseConnectWindow中的文本才会更改。 Any ideas? 有任何想法吗?

Use a SwingWorker for a background thread so you don't lock the GUI thread otherwise known as the event dispatch thread or EDT. 对后台线程使用SwingWorker,这样就不必锁定GUI线程(否则称为事件分发线程或EDT)。 For more on this, please check out Lesson: Concurrency in Swing 有关更多信息,请查看课程:Swing中的并发

You're calling connectToDatabase() in the UI thread. 您正在UI线程中调用connectToDatabase()
The UI isn't able to update until the UI thread is free. 在UI线程空闲之前,UI无法更新。

You should connect to the database on a background thread. 您应该在后台线程上连接到数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM