java swingworker thread to update main Gui

前端 未结 2 1861
青春惊慌失措
青春惊慌失措 2020-11-27 08:23

hi id like to know whats the best way to add text to a jtextarea from a swingworkerthread, ive created another class which a jbutton calls by Threadsclass().execute(); and t

相关标签:
2条回答
  • 2020-11-27 08:39

    Within doInBackground(), use publish(V... chunks) to send data to process(List<V> chunks).

    • See How SwingWorker works.
    0 讨论(0)
  • 2020-11-27 08:57

    There is an excellent example from the 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 underlying intention is that you need to update the UI from only within the Event Dispatching Thread, by passing the data you want to updated to the UI via the publish method, SwingWorker will call process for you within the context of the EDT

    0 讨论(0)
提交回复
热议问题