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 😉

6 thoughts to “Java & Netbeans: Overriding paint to customize GUI components”

  1. 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

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

  3. This article should appear on top when googling for drawing custom lines using Netbeans..

    Thank you so much!

Comments are closed.