我一直在與Java搞鬼,我試圖做一個程序,開始ping一個地址,並打印出「ms」。Java JButton actionPerformed freeze
我有一個JButton:
JButton start = new JButton("START");
start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
doCommand();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
而且doCommand()方法是這樣的:
public static void doCommand() throws IOException{
String s = null;
ProcessBuilder pb = new ProcessBuilder(commands); //definiramo procesBuilder
Process proces = pb.start(); //zaženemo proces (vrne Process)
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proces.getInputStream())); //Branje outputa procesa
BufferedReader stdError = new BufferedReader(new InputStreamReader(proces.getErrorStream())); //Branje error outputa
while((s = stdInput.readLine()) != null){ //dokler output obstaja (ni error)
int dvop = s.indexOf(":") + 16;
if(s.startsWith("Reply")){
s=s.substring(dvop);
int pres = s.indexOf(" ");
s=s.substring(0,pres-2);
//System.out.println(s);
label.setText(s);
}
}
while((s = stdError.readLine()) != null){ //dokler error obstaja
System.out.println(s);
}
}
會發生什麼情況是,每次我按下按鈕的程序只是凍結,並沒有任何反應,我甚至不能關閉它的「正常」的方式... 我想我做錯了什麼...
一個例子你應該使用'SwingWorker'來處理繁重的事情,那麼擁有標籤的類就是swingWorker的觀察者,swingWorker會通知作品結束,並且你在'EDT'中更新你的標籤。 – nachokk