Hi All,
I am learning Multithreading in Java and came across this code using SwingWorker for GUI multithreading.
Here is the modified code done by me.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
public class MainFrame extends JFrame {
private JLabel countLabel1 = new JLabel("0");
private JLabel statusLabel = new JLabel("Task not completed.");
private JButton startButton = new JButton("Start");
public MainFrame(String title) {
super(title);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.NONE;
gc.gridx = 0;
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 1;
add(countLabel1, gc);
gc.gridx = 0;
gc.gridy = 1;
gc.weightx = 1;
gc.weighty = 1;
add(statusLabel, gc);
gc.gridx = 0;
gc.gridy = 2;
gc.weightx = 1;
gc.weighty = 1;
add(startButton, gc);
Thread t4 = new Thread(new Runnable(){
public void run(){
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
start();
}
});
}});
t4.start();
setSize(200, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void start() {
SwingWorker<Boolean, Integer> worker = new SwingWorker<Boolean, Integer>() {
@Override
protected Boolean doInBackground() {
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
for(int i=0; i<30; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("Interrupted");
e.printStackTrace();
}
System.out.println("Hello: " + i);
publish(i);
}
}
});
t1.start();
return false;
}
@Override
protected void process(final List<Integer> chunks) {
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
Integer value = chunks.get(chunks.size() - 1);
countLabel1.setText("Current value: " + value);
}
});
t2.start();
}
@Override
protected void done() {
try {
Boolean status = get();
statusLabel.setText("Completed with status: " + status);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
worker.execute();
}
}
And this is the class containing main method
import javax.swing.SwingUtilities;
public class App{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
new MainFrame("SwingWorker Demo");
}
});
}
}
What i am unable to understand is even though i am running the processes in different threads(t1,t2 and t4) when i close the JFrame window, the console window will also stop printing "Hello". Why is this happening since threads are meant for parallel processing and i am running them in seperate threads...If i want to continue printing "Hello" in console even after JFrame is closed,how do i do it using threads?
Thanks in advance.