我想用一个简单的Ping生成的每个新字符串动态更改JLabel,但无法弄清楚如何用每个新字符串替换JLabel上的现有字符串,因为Ping是执行。以下是我到目前为止。到目前为止,它只替换了Ping完成执行后的JLabel文本。用Ping结果动态更改JLabel
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
public class Ping extends JFrame implements ActionListener{
private JButton runButton = new JButton("Run");
private JLabel pingResult = new JLabel("Result");
private String results;
public Ping(){
runButton.addActionListener(this);
add(pingResult, BorderLayout.CENTER);
add(runButton, BorderLayout.NORTH);
}
//Action Listener
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand();
if (buttonString.equals("Run"))
{
//Execute Ping
try {
String line;
Process p = Runtime.getRuntime().exec("/sbin/ping -c 4 www.google.com");
BufferedReader input = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
results += line + "\n";
pingResult.setText(results);
//System.out.println(line);
}
input.close();
}catch (Exception err){
err.printStackTrace();
}
}else{
System.exit(0);
}
}
public static void main(String[] args) {
Ping sp = new Ping();
sp.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
sp.setSize(400, 400);
sp.setVisible(true);
sp.setLayout(new BorderLayout());
}
}
另外,作为一个侧面说明,其建议至少改变鼠标指针“忙”对于可能持续更长的时间超过2秒的操作,而一个进度条将是很好的,甚至更长的操作。 –