Java Swing - 如何使用SwingWorker來(lái)處理冗長(zhǎng)的任務(wù)...
我們想知道如何使用SwingWorker來(lái)處理冗長(zhǎng)的任務(wù)。...
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
public class Main {
static int index = 0;
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.setLayout(new BorderLayout());
frame.add(new JScrollPane(ta));
frame.add(pb, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
Timer timer = new Timer(250, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
index++;
if (index >= 100) {
((Timer) (e.getSource())).stop();
}
ta.append("Line " + index + "\n");
pb.setValue(index);
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
}