我想用简单 Ping 生成的每个新字符串动态更改 JLabel,但不知道如何用 Ping 执行时传入的每个新字符串替换 JLabel 上的现有字符串。以下是我到目前为止所拥有的。到目前为止,它替换了 JLabel 的文本,但仅在 Ping 执行完成后才替换。
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());
}
}
最佳答案
在事件调度线程上调用setText。为此,请使用 SwingUtils.invokeLater。不要从 EDT 执行长时间持续的操作。正如您所经历的那样,这将导致您的应用程序卡住。
关于java - 使用 Ping 结果动态更改 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14089363/