2013-04-06 3 views
0

나는 프로그램을 작성 중이며 문제가 발생했습니다. ...JButton Array ActionListener 문제

1 개의 JLabel 배열과 1 개의 JButton 배열을 만듭니다. JLabel 배열에는 문자열 인 클럽 이름이 들어 있습니다. JButton 배열에는 "편집"이라고하는 문자열이 들어 있습니다.

For 루프는 클럽 배열의 길이에 따라 각 배열을 채우고 각 단추에 대한 동작 수신기를 추가합니다.

사용자가 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); 
     } 
    }); 
} 
+1

현재 코드에 어떤 문제가 있습니까? –

+0

actionListener 안에 i를 사용할 수 없습니다. –

답변

1

나는 버튼 및 JLabels의지도를 작성하고의 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); 
     } 
    }); 
} 

버튼과 라벨은 별도의 데이터 구조를 통해 서로 연결되어이 방법 각각의 배열에있는 색인에 의해서가 아니라.

+0

Valek, NullPointerException을 던졌습니다 ... 또한 labelMap final을 만들어야했습니다. 어느 쪽이든 작동하지 않지만 .. –

+0

문제가 해결되었으므로 Valek의 아이디어를 사용했습니다 ... 그러나 "this"를 사용하지 않고 e.getSource()를 사용했습니다. –

+0

@RickyRodrigues가 수정되었습니다. 죄송합니다. 익명 클래스 선언 내에서 여러 수준의 'this'에 대해 혼란스러워합니다. 그것이 당신의 문제를 해결한다면 받아 들여라. – ApproachingDarknessFish