简体   繁体   English

处理并发事件Java Swing事件处理程序

[英]Handle concurrent events Java Swing event handler

I have the following Java Code which adds a JRadioButton to a JPanel and handles its mouse click event 我有以下Java代码,它将JRadioButton添加到JPanel并处理其鼠标单击事件

    JRadioButton offline  = new JRadioButton();
    offline.setText("Offline Mode");

    modePanel.add(offline);

    modePanel.setLayout(new GridLayout(2,1));
    offline.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    offlineClicked(evt);
                }
            });

The function offlineClicked takes roughly around 1 min to be executed completely. 该功能offlineClicked大约需要1分钟左右才能完全执行。 And until its execution is completed no other actions performed are handled. 并且在执行完成之前,不会执行任何其他操作。

All actions performed thereafter seem to go to a Eventqueue and handled FIFO when the offlineClicked has completed execution. offlineClicked完成执行后,此后执行的所有操作似乎都进入事件队列并处理了FIFO。

Due to this the UI seems to have gone into a hung state. 因此,UI 似乎已进入挂起状态。

What can be done to make swing handle events concurrently and not wait till the last is executed completely. 可以做哪些操作使并发事件同时发生,而不必等到最后一个执行完毕。

When the mouselistener event is fired it runs on the event dispatch Thread (the swing gui thead that redraws the screen). 当激发mouselistener事件时,它将在事件分发线程(重新绘制屏幕的sui gui thead)上运行。 If you put logic code in the gui thread then your gui would freeze until the logic completes and returns the gui thread back to swing. 如果将逻辑代码放在gui线程中,则gui将冻结,直到逻辑完成并返回gui线程回荡。 You can use swingworker or another option is to simply start a new thread and let the gui thread return so it can let other gui events process. 您可以使用swingworker或另一个选择是简单地启动一个新线程并让gui线程返回,以便它可以让其他gui事件处理。 In the new thread do your time consuming logic, it's running off of the event loop so swing won't freeze as it's running async. 在新线程中执行耗时的逻辑,因为它不在事件循环中运行,所以摆动不会因为其异步运行而冻结。 You MUST run all swing code on the dispatch thread so when the logic is done since you are no longer on the dispatch thread you have to add it to the event queue. 您必须在分派线程上运行所有摆动代码,因此在逻辑完成后,由于您不再在分派线程上,因此必须将其添加到事件队列中。

java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        // you can now safely use swing components
        new frame.setVisible(true);
    }
} );

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

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