Replace swing components until one component completes its work

I created a simple JAVA Swing program that has JTextArea, three JTextFields and one JButton. What this application does when the user clicks the button, it updates the JTextArea with a text string, the text string inserted in the JTextArea is prepared in a for loop, and the number of repetitions is indicated in the JTextField.

My problem is that when I press the JButton launch button, all application components are frozen, I can’t even close the window until the for loop completes its work. How can I separate this job of updating JTextField from other tasks in the form?

+4
source share
1 answer

You are probably working on a Dispatch Event stream (the same stream as the GUI rendering). Use SwingWorker , it will do the work in another thread.


Example

The code below creates this screenshot:

screenshot

Worker example:

 static class MyWorker extends SwingWorker<String, String> { private final JTextArea area; MyWorker(JTextArea area) { this.area = area; } @Override public String doInBackground() { for (int i = 0; i < 100; i++) { try { Thread.sleep(10); } catch (InterruptedException e) {} publish("Processing... " + i); } return "Done"; } @Override protected void process(List<String> chunks) { for (String c : chunks) area.insert(c + "\n", 0); } @Override protected void done() { try { area.insert(get() + "\n", 0); } catch (Exception e) { e.printStackTrace(); } } } 

main example:

 public static void main(String[] args) throws Exception { final JTextArea area = new JTextArea(); JFrame frame = new JFrame("Test"); frame.add(new JButton(new AbstractAction("Execute") { @Override public void actionPerformed(ActionEvent e) { new MyWorker(area).execute(); } }), BorderLayout.NORTH); frame.add(area, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); frame.setVisible(true); } 
+9
source

All Articles