No Enclosing instance error

237 views Asked by At

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!

1

There are 1 answers

2
Sergey Kalinichenko On BEST ANSWER

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

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.

Making the class static should fix the problem:

static class HelloComponent2 extends JComponent implements MouseMotionListener