我一直在努力使这个循环

    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)给我一个错误,说“ i”必须是最终的或有效地是最终的。这是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"};


如果可以的话请帮助我,以便我继续进行我的项目。

谢谢。

最佳答案

您可以定义另一个局部变量,将其声明为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");
        }
    });
}

07-24 14:09