我正在学习Java事件处理。我编写了一个代码但是当我尝试从main方法调用类MyGUI的构造函数时它显示错误。请看一下并向我解释以下错误。
错误:
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).
我的代码:
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);
}
}
答案 0 :(得分:2)
main
方法不是为MyGUI
设置动作侦听器的方法。将设置动作侦听器的代码移动到MyGUI
构造函数中。
您还需要将正在创建的新组件分配给实例变量。
MyGUI(){
button = new JButton("Button");
textField = new JTextField(10);
radioButton = new JRadioButton("RadioButton");
add(button);
add(textField);
add(radioButton);
MyHandler handler = new MyHandler();
button.addActionListener(handler);
}