I am newly learning Java Event handling. I wrote a code but it shows an error while I try to call a Constructor of class MyGUI from the main method. Please have a look and explain the following error to me.
Error:
No enclosing instance of type MyGUI is accessible. Must qualify the allocation
with an enclosing instance of type MyGUI (e.g. x.new A() where x is an instance
of MyGUI).
My code:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MyGUI extends JPanel {
JButton button;
JTextField textField;
JRadioButton radioButton;
MyGUI(){
add(new JButton("Button"));
add(new JTextField(10));
add(new JRadioButton("RadioButton"));
}
class MyHandler implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button)
{
JOptionPane.showMessageDialog(null, "Button has been clicked");
}
else if(e.getSource()==textField)
{
JOptionPane.showMessageDialog(null, "TextField has been clicked");
}
else if(e.getSource()==radioButton)
{
JOptionPane.showMessageDialog(null, "RadioButton has been clicked");
}
}
}
public static void main(String[]args)
{
MyGUI gui=new MyGUI();
MyHandler handler=new MyHandler(); //Error Shows on this statement
gui.button.addActionListener(handler);
JFrame frame=new JFrame("Its a frame");
frame.add(gui);
frame.setVisible(true);
frame.setSize(500,500);
frame.setLayout(new FlowLayout(FlowLayout.LEFT,10,10));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}