paintComponent method run inside of the JPanel constructor

64 views Asked by At

I'm new to the forum. This is actually my first post, and I'm still figuring things out. I recently started working on learning Java, and I have been working on the paintComponent method. I was looking up a way to paint to a panel that I constructed in the main method. I have done it the way that I have seen where you create a second class that extends JPanel, but I was curious if it can be done without extending JPanel, and completed entirely from the main class. I came across this post by SantaXL about 7 years ago, and it works beautifully, but I can't figure out why it works. I'm not even sure what to call the process to look it up. I would love to know why it's okay to run a method inside the main method if I do it inside the JPanel constructor in this way.

I appreciate any help you can give.

Old Post

I just want to know why this works, and what this style is called.

1

There are 1 answers

0
Blue Dev On

So essentially what's going on here is you are creating a new version of the JPanel class, without having to create a new class, extend the JPanel, and give it a name. I've added a bunch of notes to your code snippet below to hopefully walk you through what's happening.

//This first line creates a new instance, and with the boolean
//parameter, sets the BufferStrategy to double-buffered (important later,
//but for now just think of this as a good default).
JPanel panel = new JPanel(true) {
    //Here you're overriding a built-in method (paintComponent)in the JPanel class. 
    //Overriding it allows you to alter its default behavior. 
    //NOTE that this requires you to use the exact name of the built-in method.
    @Override
    public void paintComponent(Graphics g){
        //supering the paintComponent method with the Graphics object allows
        //the class to function as though you hadn't overridden this mathod,
        //which allows the background to be redrawn as it is supposed to, 
        //every frame. Removing this will cause issues when you try to animate
        //anything or change what is being painted to the panel. 
        super.paintComponent(g);
        //all your paint code would go here. 
    }
}

Typically this is called an anonymous inner class or a nested class. You can read more about them here.