Java For 循环作为参数

Java For Loop as an argument

我一直在尝试做这个 for 循环

    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");
        }   
    });
}

i 必须是 final 因为匿名内部 class 不能使用外部变量,除非它是 final.

唯一可以在没有 final 的情况下使用它的情况是它直接传递给被匿名 class 子class 的 class 的构造函数.