Java & Netbeans: Overriding paint to customize GUI components
I found that it’s somewhat tricky to override GUI components methods with Netbeans, because the IDE automatically generates the code needed for the component, and that code cannot be edited (it’s grayed out).
But there is a property, in the “Code” tab of the component properties called “Custom Creation Code”, that let us insert the creation code we need for that component.
For example. Create a new desktop application project and, using the design view, drop a new JPanel inside the main panel. If you inspect the source code that Netbeans has generated, you can see the declaration:
private javax.swing.JPanel jPanel1;
And the initialization for that JPanel:
jPanel1 = new javax.swing.JPanel();
Note that the code after the “=” is called “Creation Code”.
Now, open the properties menu of the JPanel you have just dropped before and click on the “code” tab. Click on the “Custom Creation Code” property.

This property allow us to insert whatever code we need for the creation of the component.
Today we just want to override paint() so we insert this code:
new javax.swing.JPanel()
{
public void paint(Graphics g)
{
super.paint(g);
ourCustomPaintingMethod(g);
}
};
If you check the generated code again you can see that Netbeans has changed the creation code:
jPanel1 = new javax.swing.JPanel()
{
public void paint(Graphics g)
{
super.paint(g);
ourCustomPaintingMethod(g);
}
};
This way we can override any GUI component method we want
February 25th, 2009 at 9:21 am
Wow, neat
Thanks for the tip; this was just what I needed!
April 13th, 2009 at 10:09 pm
Hi, I really need some help guys,
I installed Netbeans lately, and I have to design some shapes, in java, using graphics/paint sth, Im not sure what are these methods.
I write there:
public void paint(Graphics g)
{
//method to draw text on screen
// String first, then x and y coordinate.
g.drawString(“Hey hey hey”,20,20);
g.drawString(“Hellooow World”,20,40);
}
And I get the error that there is no package called Graphics, what should I do?
Should I Import some kind of package,, I would appreciate a lot if you help me.
Stefi
April 13th, 2009 at 10:45 pm
You should import java.awt.Graphics.
Netbeans can do it for you, just click with the right button on the editor and “Fix Imports”
July 8th, 2009 at 11:49 am
This is great. I knew there had to be an easy way to do this! It should be in the basic Netbeans tutorials.