【发布时间】:2016-06-03 11:51:11
【问题描述】:
你能帮我用一个简单的程序来执行windows cmd命令吗?通过单击 jbutton3,我想使用 PING 命令执行代码,并在文本框中设置参数,但问题是在执行期间整个窗口冻结。单击按钮后我尝试运行新线程但窗口仍然冻结,你能指出我做错了什么吗?
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);
}
});
}
}
【问题讨论】:
标签: java multithreading swing swingworker