Java swing UI Threads and event button events

旧城冷巷雨未停 提交于 2019-12-25 02:45:09

问题


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?

So what I am saying is this

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?
            }
        });
    }
});

回答1:


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.

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.



来源:https://stackoverflow.com/questions/22560235/java-swing-ui-threads-and-event-button-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!