5

これらのコード行があります。非最終変数を内部クラスに渡すことはできないことは知っていますがi、seatingIDとして使用するには、変数を匿名の内部クラスに渡す必要があります。それを行う方法を提案できますか?

JButton [] seats = new JButton [40]; //creating a pointer to the buttonsArray
for (int i = 0; i < 40; i++)
{
    seats[i] = new JButton();//creating the buttons
    seats[i].setPreferredSize(new Dimension(50,25));//button width
    panel4seating.add(seats[i]);//adding the buttons to the panels

    seats[i].addActionListener(new ActionListener()
    {  //anonymous inner class
        public void actionPerformed(ActionEvent evt)
        {  
            String firstName = (String)JOptionPane.showInputDialog("Enter First Name");
            String lastName = (String)JOptionPane.showInputDialog("Enter Last Name");

            sw101.AddPassenger(firstName, lastName, seatingID);
        }
    });
}
4

2 に答える 2

8

簡単な方法は、ローカルの最終変数を作成し、ループ変数の値で初期化することです。例えば

    JButton [] seats = new JButton [40]; //creating a pointer to the buttonsArray
    for (int i = 0; i < 40; i++)
    {
        seats[i] = new JButton();//creating the buttons
        seats[i].setPreferredSize(new Dimension(50,25));//button width
        panel4seating.add(seats[i]);//adding the buttons to the panels
        final int ii = i;  // Create a local final variable ...
        seats[i].addActionListener(new ActionListener()
         {  //anonymous inner class
            public void actionPerformed(ActionEvent evt)
            {  
                String firstName = (String)JOptionPane.showInputDialog("Enter First Name");
                String lastName = (String)JOptionPane.showInputDialog("Enter Last Name");

                sw101.AddPassenger(firstName, lastName, ii);
            }
         });
    }
于 2011-06-12T03:05:07.120 に答える
2

直接行うことはできませんが、コンストラクターでseatingIDを受け取るActionListenerの(静的プライベート)サブクラスを作成することはできます。

次にではなく

seats[i].addActionListener(new ActionListener() { ... });

あなたが持っているだろう

seats[i].addActionListener(new MySpecialActionListener(i));

[編集]実際、コードには他にも多くの問題があるため、このアドバイスが適切かどうかはわかりません。コンパイルするコードを提示するのはどうですか。

于 2011-06-12T02:58:55.367 に答える