简体   繁体   English

有关JAVA中异常处理的错误

[英]An error regarding Exception Handling in JAVA

I am newly learning Java Event handling. 我正在学习Java事件处理。 I wrote a code but it shows an error while I try to call a Constructor of class MyGUI from the main method. 我编写了代码,但是在尝试从main方法调用类MyGUI的Constructor时显示错误。 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);



}
}

The main method isn't the one to be setting up action listeners for MyGUI . main方法不是为MyGUI设置动作侦听器的MyGUI Move the code that sets up the action listeners into the MyGUI constructor. 将设置动作侦听器的代码移到MyGUI构造函数中。

You'll also need to assign the new components you're creating to your instance variables. 您还需要将要创建的新组件分配给实例变量。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM