I am a beginner java programmer, trying to implement ActionListener
through an Inner class. Following is the simple code where I want to change label text on button click but instead of using getSource
for more than one components I want to use Inner Class. Here is my code :
public class InnerClasses extends JPanel {
static JFrame frame ;
static JButton button ;
static JLabel label ;
public static void main(String[] args) {
InnerClasses i= new InnerClasses();
frame= new JFrame("Inner class");
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(i);
label = new JLabel(BorderLayout.NORTH);
label.setText("I m label");
i.add(label);
button = new JButton(BorderLayout.SOUTH);
button.setText("Click me ");
button.addActionListener(new innerclass() );
i.add(button);
frame.setVisible(true);
}
class innerclass implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
label.setText("i have been changed");
}
}
now when i try to register listener to button it gives error
No enclosing instance of type InnerClasses is accessible. Must qualify the allocation with an enclosing instance of type InnerClasses (e.g. x.new A() where x is an instance of InnerClasses).
Please help me with it if i am doing something agaisnt the syntax or whats wrong here