Java Netbeans override paint() method in a JPanel

java, netbeans, swing

Solution

The usual way to do this is to create your own `JPanel` subclass (e.g. `MyJPanel`) and implement the `paint()` method there.

After you implemented that class, switch to your form, select the panel and then use "Custom creation code" in the the "Code" tab of the panel's properties to create an instance of `MyJPanel` instead of `JPanel`

This has the slight disadvantage that you will need to cast the instance variable to `MyJPanel` each time you want to access methods that are defined in `MyJPanel` but not in `JPanel`. If you never need to do that, this is the quickest method.

If you want to access additional methods in your panel class (without casting the instance variable each time), it's easier to remove the existing JPanel and add a "Bean" using the new class.

This is done by clicking on the "Choose Bean" button in the palette:

Once you click OK you can place the panel on your form and NetBeans will create an instance variable of the type `MyJPanel` (instead of JPane) and you can access all methods defined in that class. Note that the class must be compiled before you can add it that way!

Problem

Hi I'm a newbie programmer I want to develop a Java program's GUI using Netbeans IDE Using Netbeans GUI Builder, First, I create a new JFrame Form Then, I add a JPanel from the toolbar/palette Question is, How can I override the `paint()` function of the newly created `JPanel` ? I want to draw a background and some spheres inside the `JPanel`, I tried using `getGraphics()` function to paint and draw, it does the job, but it won't draw anymore when I call `repaint()` Should I create a new class implementing `JPanel` or `JComponent`, with my custom `paint()` function, instead ? (If it so, how can I do it with Netbeans GUI Builder?) Similar Question : how to use jpanel with paint (or repaint) (but it doesn't use Netbeans GUI Builder)

Original source

Related problems