Answer the question
In order to leave comments, you need to log in
What if no Swing components are visible inside the class?
There is a class that adds a Button and a TextField to the panel. But when I try to write actions in ColorAction when the button is clicked, the compiler does not see panel, Button, Textfield. Where is the mistake?
class BPanel extends JPanel
{
public BPanel()
{
JButton Button = new JButton("Button_");
JTextField Text = new JTextField(15);
add(Button);
add(Text);
ActionListener actionListener = new ColorAction();
Button.addActionListener(actionListener);
}
protected class ColorAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(panel, "ppppp"); //ошибка, не видит panel
}
}
}
Answer the question
In order to leave comments, you need to log in
The scope of your variables is the method inside which they are defined (constructor).
Make them variables of the BPanel class.
In this case, it's better to implement the listener as an anonymous class or lambda:
Button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Обработка здесь.
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question