2014-02-26 1 views
0

모두, 저는 Java에 초보자이며 Java 12 교과서에서 Java로 시작합니다. Ed.5).액션 리스너의 getSource() 메소드는 내가 참조하는 버튼을 인식하지 못합니다.

생성자에 대한 코드를 작성한 후 패널을 작성하고 라디오 버튼을 추가하는 메소드를 작성했습니다. RadioButtonListener라는 액션 리스너에이 라디오 버튼을 등록했습니다. 그런 다음 RadioButtonListener에 대한 내부 클래스를 작성했습니다.

여기에 문제가 있습니다. 버튼을 클릭했는지 확인하기 위해 getSource() 메서드를 사용 했으므로 컴파일러가 지정한 버튼을 인식하지 못합니다.

private void buildBottomPanel() 
{ 
    bottomPanel = new JPanel(); 

    JRadioButton greenButton = new JRadioButton("Green"); 

    JRadioButton blueButton = new JRadioButton("Blue"); 

    JRadioButton cyanButton = new JRadioButton("Cyan"); 

    ButtonGroup bottomButtonGroup = new ButtonGroup(); 
    bottomButtonGroup.add(greenButton); 
    bottomButtonGroup.add(blueButton); 
    bottomButtonGroup.add(cyanButton); 

    greenButton.addActionListener(new RadioButtonListener()); 
    blueButton.addActionListener(new RadioButtonListener()); 
    cyanButton.addActionListener(new RadioButtonListener()); 

    bottomPanel.add(greenButton); 
    bottomPanel.add(blueButton); 
    bottomPanel.add(cyanButton); 
} 

private class RadioButtonListener implements ActionListener 
{ 
    public void actionPerformed(ActionEvent f) 
    { 
     if (f.getSource() == greenButton) 
     { 
      messageLabel.setForeground(Color.GREEN); 
     } 
     else if (f.getSource() == blueButton) 
     { 
      messageLabel.setForeground(Color.BLUE); 
     } 
     else if (f.getSource() == cyanButton) 
     { 
      messageLabel.setForeground(Color.CYAN); 
     } 
    } 
} 
+1

로컬 변수'JRadioButton greenButton'에 액세스하려고하기 때문에 – vels4j

+0

buildBottomPanel()은 메소드 로컬 변수를 초기화하는 반면, 리스너는 액션 소스를 객체 필드와 비교합니다. 실제 코드를 검토해야하며 예제와 정확히 일치하면 buildBottomPanel() 메서드를 변경하여 greenButton, blueButton 및 cyanButton 변수에서 JRadioButton 유형 선언을 제거하여 객체 필드를 초기화해야합니다. –

+0

맞습니다. buildBottomPanel() 메서드에서 버튼 변수를 초기화했습니다. buildBottomPanel() 메서드 외부에서 단추 변수를 선언해야한다는 의미입니까? 내 컴퓨터에있을 때 외부 클래스에서 변수를 선언하려고합니다. 정말 고맙습니다! – Daguva

답변

-2

시도가 getActionCommand() 대신 다음과 같이 getSource()의를 사용하기 : 여기

내 코드입니다 -

if (f.getActionCommand().equals("green")) 
     { 
      messageLabel.setForeground(Color.GREEN); 
     } 

또는 당신은 다음과 익명의 내부 클래스를 사용할 수 있습니다 : -

greenButton.addActionListener(new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent e) 
      { 

       messageLabel.setForeground(Color.GREEN); 

      } 
     }); 
+0

의견을 보내 주셔서 대단히 감사합니다. 다른 액션 리스너 내부 클래스에 getActionCommand()를 사용했는데 제대로 작동합니다. 그러나이 내부 클래스의 경우 실험실 명령을 사용하려면 getSource() 메서드를 사용해야하고 텍스트 북의 샘플과 비슷한 코딩을 입력해야합니다. 현재 내부 클래스의 getSource() 메서드가 내부 클래스 외부의 메서드에 로컬 인 변수를 추적 할 수 없는지 궁금합니다. – Daguva

+0

로컬 변수가 final로 선언되면 내부 클래스에서만 해당 변수를 사용할 수 있습니다. –

관련 문제