Sometimes it is necessary to display progress and result updates in workthreads on the interface.
Principle: Do not update controls directly in workthreads
Reason: The method of interface control is generally thread insecure, and the operation of interface in worker thread is generally insecure.
Solution: Create an event by yourself and insert it into the event loop
SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MyFrame.textField.setText(progress); } });
In the event loop, an event is fetched and found to be a custom event handler, so the Runnable callback method for the custom event is executed.
code
package my; import javax.swing.SwingUtilities; public class ButtonThread extends Thread { @Override public void run() { try { updateUI("I"); Thread.sleep(1000*2); updateUI("love"); Thread.sleep(1000*2); updateUI("you"); Thread.sleep(1000*2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Thread Scheduling private void updateUI(String progress) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MyFrame.textField.setText(progress); } }); } }
package my; import java.awt.FlowLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class MyFrame extends JFrame { public static JTextField textField=new JTextField(10); public static JButton button=new JButton("Determine"); public MyFrame(String title) { super(title); //panel JPanel root=new JPanel(); this.setContentPane(root); root.setLayout(new FlowLayout()); root.add(textField); root.add(button); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { onButton(); } }); } private void onButton() { ButtonThread th=new ButtonThread(); th.start(); } }
package my; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class MyDemo { private static void createGUI() { // JFrame refers to a window whose parameters are the title of the window. JFrame frame = new MyFrame("Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set other parameters of the window, such as window size frame.setSize(500, 300); // Display window frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createGUI(); } }); } }