Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;

public class Main {

    public static void main(String[] args) {
        JProgressBar pb = new JProgressBar();
        JTextArea ta = new JTextArea(10, 20);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(ta));
        frame.add(pb, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);

        new BackgroundWorker(ta, pb).execute();
    }
}

class BackgroundWorker extends SwingWorker<Void, String> {
    private JProgressBar pb;
    private JTextArea ta;

    public BackgroundWorker(JTextArea ta, JProgressBar pb) {
        this.pb = pb;
        this.ta = ta;
        addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
                    BackgroundWorker.this.pb.setValue(getProgress());
                }
            }

        });
    }

    @Override
    protected void done() {
    }

    @Override
    protected void process(List<String> chunks) {
        for (String text : chunks) {
            ta.append(text);
            ta.append("\n");
        }
    }

    @Override
    protected Void doInBackground() throws Exception {
        for (int index = 0; index < 100; index++) {
            publish("Line " + index);
            setProgress(index);
            Thread.sleep(125);
        }
        return null;
    }
}