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.
I just want to know why this works, and what this style is called.
So essentially what's going on here is you are creating a new version of the
JPanelclass, 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.Typically this is called an anonymous inner class or a nested class. You can read more about them here.