This demo gives examples of using the SwingWorker
class. The purpose of SwingWorker
is to implement a background thread that you can use to perform time-consuming operations without affecting the performance of your program’s GUI.
package org.kodejava.swing;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
import java.awt.Dimension;
import java.awt.FlowLayout;
public class SwingWorkerDemo extends JFrame {
public SwingWorkerDemo() {
initialize();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new SwingWorkerDemo().setVisible(true));
}
private void initialize() {
this.setLayout(new FlowLayout());
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton processButton = new JButton("Start");
JButton helloButton = new JButton("Hello");
processButton.addActionListener(event -> {
LongRunProcess process = new LongRunProcess();
try {
process.execute();
} catch (Exception e) {
e.printStackTrace();
}
});
helloButton.addActionListener(e ->
JOptionPane.showMessageDialog(null, "Hello There"));
this.getContentPane().add(processButton);
this.getContentPane().add(helloButton);
this.pack();
this.setSize(new Dimension(500, 500));
}
static class LongRunProcess extends SwingWorker<Integer, Integer> {
protected Integer doInBackground() {
int result = 0;
for (int i = 0; i < 10; i++) {
try {
result += i * 10;
System.out.println("Result = " + result);
// Sleep for a while to simulate a long process
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
@Override
protected void done() {
System.out.println("LongRunProcess.done");
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024