I am developing a small test where I press a button in java swing and start doing a background task, while the background task is running I want to keep interacting with the window. However, when developing it, I realized that if I press the button, the window remains frozen until the process is finished. I leave the code here so you can advise me on what I should do.
The background class:
public class Descarga extends Thread{
@Override
public void run() {
System.out.println("Decargando en segundo plano");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Window:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JCheckBox;
public class Ventana extends JFrame {
private JPanel contentPane;
public Ventana() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 370, 156);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Empezar descarga");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Descarga h2 = new Descarga();
h2.run();
}
});
btnNewButton.setBounds(81, 72, 199, 25);
contentPane.add(btnNewButton);
JCheckBox chckbxOtraCosa = new JCheckBox("Seguir haciendo cosas");
chckbxOtraCosa.setBounds(81, 8, 193, 23);
contentPane.add(chckbxOtraCosa);
}
}
The class to run the program:
public class Run {
public static void main(String[] args) {
Ventana ventana = new Ventana();
ventana.setVisible(true);
}
}
What you are getting is that you are calling the method
run()
, but doing this is just going to execute the code of that method (without creating a new thread). This is incorrect considering that what you want to do is that the code defined in that methodrun()
is executed in a different thread than the thread where the graphical interface runs.For a new thread to be created you always have to use the method
start()
and once said thread is started then it will be the one that executes the code that you defined in the methodrun()
.