2015-06-08 2 views
1

Я пытаюсь изменить цвет фона при щелчке переключателя, но второй переключатель «bt2» не найден компилятором.Переменная JButton не найдена

Я получаю сообщение об ошибке:

"cannot find symbol bt1" in the e.getSource()==bt1 

Вот мой код:

public class ColorChooser extends JFrame implements ActionListener { 

    public static void main(String[] args) { 
     new ColorChooser(); 
    } 

    public ColorChooser() { 
     super("ColorChooser"); 
     Container content = getContentPane(); 
     content.setBackground(Color.white); 
     content.setLayout(new FlowLayout()); 
     JRadioButton bt1 = new JRadioButton("Red"); 
     JRadioButton bt2 = new JRadioButton("Yellow"); 

     bt1.addActionListener(this); 
     bt2.addActionListener(this); 
     content.add(bt1); 
     content.add(bt2); 
     setSize(300, 100); 
     setVisible(true); 
    } 

    public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == bt1) 
      getContentPane().setBackground(Color.RED); 
     else 
      getContentPane().setBackground(Color.YELLOW); 
    } 
} 

ответ

1

объявить bt1 вне конструктора

JRadioButton bt1; 

затем инициализировать в конструкторе

bt1 = new JRadioButton("Red"); 

проблема в вашем коде bt1 не видна вне конструктора.it объявлена ​​как блочная переменная. Вы должны объявить как переменную экземпляра [в области класса]. Пример

public class ColorChooser extends JFrame implements ActionListener { 

    JRadioButton bt1;//declare 

    public static void main(String[] args) { 
     new ColorChooser(); 
    } 

    public ColorChooser() { 
     super("ColorChooser"); 
     Container content = getContentPane(); 
     content.setBackground(Color.white); 
     content.setLayout(new FlowLayout()); 
     bt1 = new JRadioButton("Red");//initializing 
     JRadioButton bt2 = new JRadioButton("Yellow"); 

     bt1.addActionListener(this); 
     bt2.addActionListener(this); 
     content.add(bt1); 
     content.add(bt2); 
     setSize(300, 100); 
     setVisible(true); 
    } 

    public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == bt1) { 
      getContentPane().setBackground(Color.RED); 
     } else { 
      getContentPane().setBackground(Color.YELLOW); 
     } 

    } 

} 
+1

спасибо большое, он работал. Не могли бы вы сообщить мне, почему это было необходимо ...? –

+0

@AkshatMalviya, когда вы объявляете JRadioButton bt1; внутри конструктора вы можете получить к нему доступ только из конструктора. Когда вы будете обращаться к нему откуда-то [actionPerformed method], а не конструктор, вы получите компиляцию error.but, когда вы объявляете переменную экземпляра, вы можете получить к ней доступ из любого места в классе –

+1

. Я получаю это сейчас. –

2

Вы должны объявлять BT1, как, например переменная Как что

public class ColorChooser extends JFrame implements ActionListener 
{ 
    private JRadioButton bt1; 
... 
} 
Смежные вопросы