Jac*_*aub 0 java swing multithreading
我是否应该假设以下程序是错误的,因为 x 和 y 行(在 main 方法的最后)没有在 EDT 上执行?
public class Temp
{
private static JButton button;
private static JTextField text;
private static void showGUI()
{
JFrame frame = new JFrame();
JPanel contentPane = new JPanel();
button = new JButton( "Push Me" );
text = new JTextField( "I am the walrus" );
contentPane.add( button );
contentPane.add( text );
frame.setContentPane( contentPane );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
throws InterruptedException, InvocationTargetException
{
SwingUtilities.invokeAndWait( () -> showGUI() );
/* x */ System.out.println( text.getText() );
/* y */ button.addActionListener( System.out::println );
}
}
Run Code Online (Sandbox Code Playgroud)
是的你应该。
x 行和 y 行确实不在 EDT 上执行,这可能会导致 Swing 应用程序出现潜在问题。
在 Swing 中,在 EDT 上执行所有与 GUI 相关的操作非常重要,以确保正确的同步并防止潜在的线程问题。
SwingUtilities.invokeAndWait()您在方法中使用的方法用于main在showGUI()EDT 上执行该方法,这是正确的。但是,后续行 x 和 y 在主线程上执行,这可能会导致同步问题和意外行为。
为了确保 x 行和 y 行在 EDT 上执行,您SwingUtilities.invokeLater()也应该将它们包装在调用中。
这边走:
public static void main(String[] args)
throws InterruptedException, InvocationTargetException
{
SwingUtilities.invokeAndWait( () -> showGUI() );
SwingUtilities.invokeLater( () -> {
/* x */ System.out.println( text.getText() );
/* y */ button.addActionListener( System.out::println );
});
}
Run Code Online (Sandbox Code Playgroud)