Java & Netbeans: Overriding paint to customize GUI components

26 08 2008

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 ;)



Actions

Informations

4 responses to “Java & Netbeans: Overriding paint to customize GUI components”

25 02 2009
Dustin (09:21:56) :

Wow, neat :) Thanks for the tip; this was just what I needed! :D

13 04 2009
Stefi (22:09:32) :

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

13 04 2009
Ignacio Sánchez (22:45:06) :

You should import java.awt.Graphics.

Netbeans can do it for you, just click with the right button on the editor and “Fix Imports” ;-)

8 07 2009
Kimberly (11:49:35) :

This is great. I knew there had to be an easy way to do this! It should be in the basic Netbeans tutorials. :)

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image