모두, 저는 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);
}
}
}
로컬 변수'JRadioButton greenButton'에 액세스하려고하기 때문에 – vels4j
buildBottomPanel()은 메소드 로컬 변수를 초기화하는 반면, 리스너는 액션 소스를 객체 필드와 비교합니다. 실제 코드를 검토해야하며 예제와 정확히 일치하면 buildBottomPanel() 메서드를 변경하여 greenButton, blueButton 및 cyanButton 변수에서 JRadioButton 유형 선언을 제거하여 객체 필드를 초기화해야합니다. –
맞습니다. buildBottomPanel() 메서드에서 버튼 변수를 초기화했습니다. buildBottomPanel() 메서드 외부에서 단추 변수를 선언해야한다는 의미입니까? 내 컴퓨터에있을 때 외부 클래스에서 변수를 선언하려고합니다. 정말 고맙습니다! – Daguva