无封闭实例错误 [英] No Enclosing instance error

查看:51
本文介绍了无封闭实例错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在研究一本Java书籍,并且已经开始使用此程序.但是,当我在Eclipse中使用它时,它会为我提供.... error类型的无封闭实例.

So I'm working through a Java book and I've come to this program. However when I'm working with it in Eclipse it gives me a No Enclosing Instance of type .... error

对于为什么会弹出此错误,我感到非常困惑.这是我的代码:

I'm pretty baffled by this as to why this error pops up. Here is my code:

我已注释掉出现错误的行

I've commented the line that gives the error

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloJava2 
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Hello, Java2!");
        /*
        HelloComponent2 newObject = new HelloComponent2("Hello, Java!");
        */
        frame.add(newObject);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setVisible(true);

    }

    class HelloComponent2 extends JComponent implements MouseMotionListener
    {
        String theMessage;
        int messageX = 125, messageY = 95;

        public HelloComponent2(String message)
        {
            theMessage = message;
            addMouseMotionListener(this);
        }

        public void paintComponent( Graphics g )
        {
            g.drawString( theMessage, messageX, messageY);
        }

        public void mouseDragged(MouseEvent e)
        {
            messageX = e.getX();
            messageY = e.getY();

            repaint();
        }

        public void mouseMoved(MouseEvent e) 
        {

        }
    }
}

如果有人能解释为什么我会收到此错误以及以后如何解决/避免它,将不胜感激.预先感谢!

If anyone could explain why I'm getting this error and how to fix/avoid it in the future I would be greatly appreciated. Thanks in advance!

推荐答案

这是因为您试图从静态方法实例化非静态内部类.

This is because you are trying to instantiate a non-static inner class from a static method.

Java有两种可以在类级别嵌套的内部类-静态和非静态.非静态类引用了其外部"类的 instance ,在内部对其进行了实例化.这允许非静态内部类访问其外部类的实例变量.静态类(例如您的 HelloComponent2 )不访问其外部类的实例变量.这样,您就可以从静态函数实例化此类.

Java has two kinds of inner classes that can be nested at the class level - static and non-static. Non-static classes have a reference to an instance of their "outer" class, inside of which they were instantiated. This allows non-static inner classes access instance variables of their outer class. Static classes, such as your HelloComponent2, do not access instance variables of their outer class. This lets you instantiate such classes from static functions.

使类为 static 应该可以解决此问题:

Making the class static should fix the problem:

static class HelloComponent2 extends JComponent implements MouseMotionListener

这篇关于无封闭实例错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆