Java swingworker thread to upgrade core Gui

hi id likes to know that the best way to add text to jtextarea from swingworkerthread is to create another class that jbutton calls Threadsclass (). execute (); and the thread runs in parallel with this code

public class Threadsclass extends SwingWorker<Object, Object> { @Override protected Object doInBackground() throws Exception { for(int x = 0; x< 10;x++) try { System.out.println("sleep number :"+ x); Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(eftcespbillpaymentsThreads.class.getName()).log(Level.SEVERE, null, ex); } throw new UnsupportedOperationException("Not supported yet."); } } 

now what id like to do is add the x value to the text area on the main gui, any ideas that were highly appreciated.

+4
source share
2 answers

There is a great example from JavaDocs

 class PrimeNumbersTask extends SwingWorker<List<Integer>, Integer> { PrimeNumbersTask(JTextArea textArea, int numbersToFind) { //initialize } @Override public List<Integer> doInBackground() { List<Integer> numbers = new ArrayList<Integer>(25); while (!enough && !isCancelled()) { number = nextPrimeNumber(); numbers.add(number); publish(number); setProgress(100 * numbers.size() / numbersToFind); } return numbers; } @Override protected void process(List<Integer> chunks) { for (int number : chunks) { textArea.append(number + "\n"); } } } JTextArea textArea = new JTextArea(); final JProgressBar progressBar = new JProgressBar(0, 100); PrimeNumbersTask task = new PrimeNumbersTask(textArea, N); task.addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("progress".equals(evt.getPropertyName())) { progressBar.setValue((Integer)evt.getNewValue()); } } }); task.execute(); System.out.println(task.get()); //prints all prime numbers we have got 

Take a look at publish and process

The main goal is that you only need to update the interface from the Dispatching Event stream, passing the data you want to update to the user interface using the publish method, SwingWorker will call the process for you in the EDT context

+7
source

Source: https://habr.com/ru/post/1484617/


All Articles