0

私はプログラムを書いていて、問題に遭遇しました...

1 つの JLabel 配列と 1 つの JButton 配列を作成します。JLabel 配列は文字列、クラブ名を保持します。JButton 配列は、「編集」という文字列を保持します。

For ループは、clubs 配列の長さに基づいて各配列を埋め、各ボタンのアクション リスナーを追加します。

ユーザーが JLabel に対応する JButton をクリックすると、イベントが開始されます。このイベントでは、JButton に一致する JLabel に格納されている値を見つける必要があります。

イベントリスナーはループ内にあることを認識していないため、使用できません。

望む目標を達成するにはどうすればよいですか?

以下のコードを参照してください。

JLabel clubs[]      = new JLabel[99];
JButton editAClub[] = new JButton[99];

for(int i=0; i <= (allClubs.length - 1);i++)
{
    clubs[i]        =   new JLabel("Club " + i);
    editAClub[i]    =   new JButton("Edit");
    editAClub[i].addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            selectedClub = clubs[i].getText().toString();
            System.out.println(selectedClub);
        }
    });
}   
4

1 に答える 1

1

ボタンと JLabel のマップを作成し、アクションのソースを actionListener に渡します。

JLabel clubs[]      = new JLabel[99];
JButton editAClub[] = new JButton[99];

//create a map to store the values
final HashMap<JButton,JLabel> labelMap = new HashMap<>(); //in JDK 1.7

for(int i=0; i <= (allClubs.length - 1); i++)
{
    clubs[i]        =   new JLabel("Club " + i);
    editAClub[i]    =   new JButton("Edit");

    //add the pair to the map
    labelMap.put(editAClub[i],clubs[i]);

    editAClub[i].addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            //get the label associated with this button from the map
            selectedClub = labelMap.get(e.getSource()).getText(); // the toString() is redundant
            System.out.println(selectedClub);
        }
    });
}   

このようにして、ボタンとラベルは、それぞれの配列のインデックスだけではなく、個別のデータ構造を介して互いに関連付けられます。

于 2013-04-06T18:25:13.500 に答える