2017-05-10 1 views
0

요소의 이름에 ActionListener를 어떻게 추가 할 수 있습니까?Java - JRadioButton 이름의 동작 수신기

나를 위해 테이블을 만드는 루프가 있습니다. 이 루프

enter image description here

나 라디오 버튼을 만들 :

ZFbutton = new JRadioButton(); 
ZFbutton.setName(""+key);  

..where key 루프에서이다.

은 현재 내가 통해 JRadioButtons에 액세스하려고 :

ZFbutton.addActionListener (new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     try { 
     if(ZFbutton.isSelected() == true){ 

하지만 이것은 단지 나 논리의 관점에서 의미가 마지막으로 생성 된 JRadioButton의를 액세스 할 수 있습니다. 그래서 모든 RadioButton에 고유 한 이름을 부여했습니다 : ZFbutton.setName(""+key);하지만 어떻게 요소의 이름으로 ActionListener를 만들 수 있습니까?

+0

사용자가 시도 할 수있는 몇 가지 방법이 있습니다. 첫 번째는 어떤 요소가'e.getSource()'로 액션 이벤트를 일으키는 지 확인하고 아마'.getName()'이 소스에서 작동하는지 확인하는 것입니다. 다른 방법은 라디오 버튼을 배열에 저장하고 배열을 통해 액세스하는 것입니다. – XtremeBaumer

+0

대신에'JTable'을 사용하는 것이 좋습니다 – MadProgrammer

+0

@XtremeBaumer 제 문제를 해결 한 배열을 만들어 주셔서 감사합니다. 당신은 내가 그것을 받아 들일 수 있도록 대답으로 쓸 수 있습니다 :) – MansNotHot

답변

1

모든 버튼을 배열에 추가하고 배열을 통해 각 버튼에 액세스하십시오. 쉬운 방법이지만 @StimpsonCat이 언급 한 것도 잘 작동합니다.

JRadioButoon[] buttons=new JRadioButton[x]; 
buttons[0]=new JRadioButton(); 
... 
2

각 단추에 actionListener를 추가 할 수 있습니다. Button의 이름을 설정하는 대신 ActionCommand를 설정할 수 있습니다.

button.setActionCommand("Alpha"); 

그럼 당신은 이런 식으로 눌러 진 버튼 distiguish 수 있습니다

public void actionPerformed(ActionEvent ae) { 
String ac = ae.getActionCommand(); 

if (ac.equals("Alpha")) { 
    if (jbtnB.isEnabled()) { 
    System.out.println("Alpha pressed. Beta is disabled."); 
    jbtnB.setEnabled(false); 
    } else { 
    System.out.println("Alpha pressed. Beta is enabled."); 
    jbtnB.setEnabled(true); 
    } 
} else if (ac.equals("Beta")) 
    System.out.println("Beta pressed."); 
} 

당신은 ActionEvent의의는 actionCommand를 얻을.