codechaser
V2EX  ›  Java

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

  •  
  •   codechaser · Jul 20, 2018 · 1908 views
    This topic created in 2863 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   ·   3093 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 10:48 · PVG 18:48 · LAX 03:48 · JFK 06:48
    ♥ Do have faith in what you're doing.