Java swing UI线程和事件按钮事件 [英] Java swing UI Threads and event button events
问题描述
据我了解,所有摆动组件都只能从EDT中创建,修改和查询.
因此,如果我碰巧按下JButton
提交",那么它将打包来自文本框的所有信息,将该数据发送到控制器,然后控制器会将其发送到其他控制器,最终将这些东西发送到服务器.该按钮的操作正在哪个线程上运行?如果它在EDT上运行,如何退出它以将数据从主线程发送到控制器?我是否应该甚至使用主线程将数据从控制器发送到服务器?
So as far as I understood, all the swing components should be created, modified and queried only from the EDT.
So if I happen to press a JButton
"submit" let's say, that will pack up all the information from the text boxes, send that data to controller and then controller will send it to other controllers which will eventually send stuff to the server. What thread is the action for that button is running on? If it is running on EDT, how do I exit it to send the data to controller from the main thread? Should I even use main thread to send data to server from the controller?
所以我的意思是这个
java.awt.EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
JButton button = new JButton("Submit");
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// WHAT THREAD DO ACTIONS HERE RUN ON?
// AND HOW DO I MAKE THEM RUN ON MAIN THREAD?
// AND WHAT THREAD SHOULD I RUN THING ON HERE?
}
});
}
});
推荐答案
从Swing触发的任何操作都将在EDT上运行.因此,actionPerformed
方法中的代码将已经在EDT上执行,而无需您进行任何特殊处理.
Any action triggered from Swing will run on the EDT. So the code in your actionPerformed
method will already be executed on the EDT, without any special handling by you.
To start a long-running task, like sending data to a server, use a SwingWorker
or a Callable
and an ExecutorService
.
我更喜欢在实现Swing UI时使用SwingWorker
,因为它是发布更新并在EDT上自动完成任务时进行回调的有用API.
I prefer using a SwingWorker
when implementing a Swing UI, as has it a useful API for publishing updates and makes the callbacks when the task is done automatically happen on the EDT.
这篇关于Java swing UI线程和事件按钮事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!