Could you please help me with simple program which is executing windows cmd command. By clicking jbutton3 i want to execute code with PING command with parameters set in textboxes but problem is that during the execution whole window freeze. I tried to run new Thread after button click but windows still freeze, could you point me what I am doing wrong?
public class GUI extends javax.swing.JFrame implements ActionListener{
public GUI() {
initComponents();
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
Thread worker = new Thread()
{
public void run()
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try
{
Runtime rt2 = Runtime.getRuntime();
String IP2, COUNT;
IP2 = jTextField4.getText();
COUNT = jTextField3.getText();
Process pr = rt2.exec("cmd /c ping -n " + COUNT + " " + IP2);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
jTextArea1.append(line + "\n");
jTextArea1.repaint();
jTextArea1.update(jTextArea1.getGraphics());
System.out.println(line);
}
jTextArea1.append("\nCOMPLETED!\n");
jTextArea1.repaint();
jTextArea1.update(jTextArea1.getGraphics());
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
}
catch(Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
});
}
};
worker.start();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
}
}
Yes, you've got a background thread, which immediately creates another Runnable that calls your long-running process is run on the Swing event thread -- the exact place where it shouldn't be run (by passing the Runnable into the SwingUtilities.invokeLater method).
The solution: run long stuff in a background thread that is not run in the Swing event thread, and only run Swing code within the event thread.
Read: Concurrency in Swing