简体   繁体   English

Java Swing UI 线程和事件按钮事件

[英]Java swing UI Threads and event button events

So as far as I understood, all the swing components should be created, modified and queried only from the EDT.所以据我所知,所有的摆动组件都应该只从 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.因此,如果我碰巧按下JButton “提交”,比方说,它将打包文本框中的所有信息,将该数据发送到控制器,然后控制器将其发送到其他控制器,这些控制器最终会将内容发送到服务器。 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?如果它在 EDT 上运行,我如何退出它以将数据从主线程发送到控制器? 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?
            }
        });
    }
});

Any action triggered from Swing will run on the EDT.从 Swing 触发的任何操作都将在 EDT 上运行。 So the code in your actionPerformed method will already be executed on the EDT, without any special handling by you.因此,您的actionPerformed方法中的代码将已经在 EDT 上执行,而无需您进行任何特殊处理。

To start a long-running task, like sending data to a server, use a SwingWorker or a Callable and an ExecutorService .要开始一个长时间运行的任务,比如向服务器发送数据,请使用SwingWorkerCallableExecutorService

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.我更喜欢在实现 Swing UI 时使用SwingWorker ,因为它是一个有用的 API,用于发布更新并在 EDT 上自动完成任务完成时进行回调。

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

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