R
R
roman38472014-03-16 12:25:07
Java
roman3847, 2014-03-16 12:25:07

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

2 answer(s)
R
Rodgenk, 2014-03-17
@Rodgenk

The scope of your variables is the method inside which they are defined (constructor).
Make them variables of the BPanel class.

A
Andrey Vershinin, 2014-03-18
@WolfdalE

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) {
        //Обработка здесь.
    }
});

In this case, the panel variable will be visible. Or, as Rodgenk wrote, but this approach has two drawbacks:
1) Redundancy if a given listener is used once.
2) The need to create static fields, and this is also a kind of redundancy.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question