各位前辈,请教一个问题:想在另外一个线程中,定期检测某ip是否在线,如果在线,就在界面上使某个组件显红色,如果不在线,就显灰色。该怎么写?
import java.net.*;
import java.io.IOException;
import javax.swing.*;
import java.awt.Color;
public class IP
{
JFrame f=new JFrame( "测试界面组件在另一个线程中的更新 ") ;
public static void main(String[] args)
{
IP ip=new IP();
ip.init() ;
TestIp tt=new TestIp() ;
tt.start() ;
}
public void init()
{
f.setSize(350,250);
f.setVisible(true);
jLabelip.setForeground(Color.lightGray);
jLabelip.setHorizontalAlignment(SwingConstants.CENTER);
jLabelip.setText( "192.168.0.1 ");
f.getContentPane().add(jLabelip);
f.setVisible(true);
}
JLabel jLabelip = new JLabel();
}
class TestIp extends Thread //implements Readable
{
public void run()
{
byte[] clint1 =
{
(byte) 192, (byte) 168, (byte) 0, (byte) 1};
InetAddress addr = null;
while (true)
{
try {
Thread.sleep(5000);
}
catch (InterruptedException ex2) {
}
try
{
addr = InetAddress.getByAddress(clint1);
}
catch (UnknownHostException ex)
{
}
try
{
if (addr.isReachable(5000))
{
//如果192.168.0.1在线,更新jLabelip为红色
}
else
{
//如果192.168.0.1不在线,则使jLabelip成为灰色
}
}