Java SwingWorkder USES instances

  • 2020-04-01 03:16:24
  • OfStack

The first thing to consider is Swing's internal SwingWorkder object, but the online ready-made examples are not easy to find, mainly referring to the information on the Internet, their own arrangement of a.

Note: SwingWorkder objects can only be executed once, not repeatedly! For example, if you click start, when it's over, you can't start again.


import java.awt.BorderLayout;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
import javax.swing.SwingWorker;

public class SwingWorkerSample {

    public static void main(String[] args) {

        //Appearance of definition
        try {
            UIManager
                    .setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception ex) {
        }

        //The form
        JFrame f = new JFrame("SwingWorker Sample");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Said area
        final JTextArea taOutput = new JTextArea(15, 30);
        JScrollPane sp = new JScrollPane(taOutput);
        f.add(sp);

        //Bottom progress bar
        final JProgressBar progressBar = new JProgressBar();
        f.add(BorderLayout.SOUTH, progressBar);

        //Start button
        JButton b = new JButton(" start ");
        f.add(BorderLayout.NORTH, b);

        //The end of the button
        JButton b2 = new JButton(" The end of the ");
        f.add(BorderLayout.AFTER_LINE_ENDS, b2);

        //SwingWorker class
        final SwingWorker<Integer, int[]> sw = new SwingWorker<Integer, int[]>() {

            
            @Override
            protected Integer doInBackground() throws Exception {

                int sum = 0;

                if (!this.isCancelled()) {

                    for (int i = 1; i <= 10; ++i) {
                        sum += i;
                        publish(new int[] { i, sum });//The call represents the intermediate result
                        setProgress(i * 10);//The progress bar
                        Thread.sleep(1000);
                    }

                }
                return sum;
            }

            
            @Override
            protected void process(List<int[]> chunks) {
                StringBuilder sb = new StringBuilder();
                for (int[] values : chunks) {
                    sb.append(String.format(" cumulative %d Is equal to the %d%n", values[0], values[1]));
                }
                taOutput.append(sb.toString());
            }

            
            @Override
            protected void done() {

                if (this != null && !this.isDone()) {
                    try {
                        int result = get();
                        taOutput.append(" Finished.   A combined " + result + "n");
                    } catch (InterruptedException ex) {
                    } catch (ExecutionException ex) {
                    }
                }
            }

        };

        //The progress bar said 
        sw.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if ("progress".equals(evt.getPropertyName())) {
                    progressBar.setValue((Integer) evt.getNewValue());
                }
            }
        });

        //Start button The event 
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                sw.execute();//Call SwingWorkder asynchronously
            }
        });

        //The end of the button
        b2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (sw != null && !sw.isDone()) {
                    // Cancel
                    sw.cancel(true);
                }

                JOptionPane.showMessageDialog(null, " The end! ");
            }
        });

        //The form said 
        f.pack();
        f.setVisible(true);
    }
}


Related articles: