V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
codechaser
V2EX  ›  Java

Java swing 组件更新必须在事件派遣线程吗?

  •  
  •   codechaser · Jul 20, 2018 · 1881 views
    This topic created in 2850 days ago, the information mentioned may be changed or developed.
    package volume2.chapter3;
    
    import javax.swing.*;
    import java.awt.*;
    
    public class JFrameDispatchEventTest extends JFrame {
    
        public JFrameDispatchEventTest(){
            JPanel panel = new JPanel(new BorderLayout());
            JButton test = new JButton("Test");
            JTextArea textArea = new JTextArea();
    
            panel.add(test,BorderLayout.NORTH);
            panel.add(new JScrollPane(textArea),BorderLayout.SOUTH);
    
            System.out.println(Thread.currentThread());
            test.addActionListener((e) -> {
                textArea.append(Thread.currentThread().toString()+"\n");
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        textArea.append("Another thread runs in thread: "+Thread.currentThread()+"\n");
                    }
                });
                t.start();
            });
    
            add(panel);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(JFrameDispatchEventTest::new);
        }
    }
    

    这里我新开了一个线程更新textArea也没有什么问题啊。

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2909 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 12:43 · PVG 20:43 · LAX 05:43 · JFK 08:43
    ♥ Do have faith in what you're doing.