我一直试图为循环
做这个 for ( int i = 0; i < Main.ipList.length; i++){
JButton btn = new JButton();
btn.setText(Main.ipList[i]);
panel.add(btn);
btn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
Main.refreshSpecificIp(i);
System.out.println("Bu");
}
});
}
Main.refreshSpecificIp(i)
正在给我一个错误说'我&#39;必须是最终的或有效的决赛。这是refreshSpecificIp函数:
public static void refreshSpecificIp(Integer d){
try
{
InetAddress inet = InetAddress.getByName(ipList[d]);
System.out.println("Sending Ping Request to " + ipList[d]);
boolean status = inet.isReachable(500000); //Timeout = 5000 milli seconds
if (status)
{
System.out.println("Status : " + ipList[d]+ " Host is reachable");
}
else
{
System.out.println("Status " + ipList[d]+ " Host is not reachable");
}
}
catch (UnknownHostException e)
{
System.err.println(ipList[d] + " Host does not exists");
}
catch (IOException e)
{
System.err.println(ipList[d] + " Error in reaching the Host");
}
}
static String[] ipList = {"127.0.0.1", "173.57.51.111", "69.696.69.69"};
如果你能帮助我,我可以继续我的项目。
感谢。
答案 0 :(得分:2)
您可以定义另一个局部变量,将其声明为final,并为其指定i
的值:
for ( int i = 0; i < Main.ipList.length; i++){
JButton btn = new JButton();
btn.setText(Main.ipList[i]);
panel.add(btn);
final int j = i;
btn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
Main.refreshSpecificIp(j);
System.out.println("Bu");
}
});
}
答案 1 :(得分:1)
i
必须为final
,因为匿名内部类不能使用外部变量,除非它是final
。
唯一可以在没有final
的情况下使用它的情况是它是否直接传递给由匿名类子类化的类的构造函数。