I made a simple counter GUI for practice. The user presses a button to start the counter. The button click executes a SwingWorker
task that updates a JLabel with the count. The update occurs in the doInBackground
method.
Is this a bad idea? Even for something as simple as this, I should still update the component from a method that runs on the event dispatch thread, such as process
?
If so, why would it be a bad practice for something as simple as this?
Main.java:
package counter;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CounterView view = new CounterView();
view.activate();
}
});
}
}
ProgressBar.java:
package counter;
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
import javax.swing.SwingConstants;
import java.awt.event.*;
public class CounterView {
private JFrame frame;
private JPanel gui;
private JButton button;
private JLabel count;
public CounterView() {
customizeFrame();
createMainPanel();
createCountText();
createButton();
addComponentsToFrame();
}
private void customizeFrame() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void createMainPanel() {
gui = new JPanel();
gui.setLayout(new BorderLayout());
}
private void createCountText() {
count = new JLabel("0");
count.setHorizontalAlignment(SwingConstants.CENTER);
}
private void createButton() {
button = new JButton("Start counter");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Create the worker
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
for (int i = 0; i <= 50; i++) {
Thread.sleep(100);
System.out.println(i);
text.setText(Integer.toString(i));
}
return null;
}
};
// Start the worker
worker.execute();
}
});
}
private void addComponentsToFrame() {
gui.add(count, BorderLayout.CENTER);
gui.add(button, BorderLayout.SOUTH);
frame.add(gui);
frame.pack();
}
public void activate() {
frame.setVisible(true);
}
}
text.setText(Integer.toString(i));
wheretext
is defined? \$\endgroup\$text
is(JLabel) count
. \$\endgroup\$