Christian Daley
Christian Daley

Reputation: 789

fillRect not showing up

I have a problem with drawing a rect on screen. I have the paintComponent method in my jpanel class and I want to draw a rect in it. It looks like this:

public void paintComponent( Graphics g ) {

    super.paintComponent( g );

    g.setColor( Color.yellow );
    g.fillRect( 0, 140, 100, 100 );

}

The problem is that I have a couple of panels added to the one that I'm drawing in. The subpanels always show up on top and the rect is drawn beneath them. How can I make it so that the rect is drawn in front?

Upvotes: 1

Views: 1520

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347214

No offense, but I feel this is a bad idea...

public void paint( Graphics g ) {

    super.paint( g );

    g.setColor( Color.yellow );
    g.fillRect( 0, 140, 100, 100 );

}

As Hovercraft has pointed out, a better approach would be to use a GlassPane (How to use RootPanes) or a JLayeredPane or JLayer (AKA JXLayer if you're not using Java 7)

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

If the drawn JPanel is in the container, then there's no way that it can be in "front". You can make the child components non-opaque by calling setOpaque(false) on them, but still the container will always be behind its children.

If you absolutely want a component above another, consider using a JLayeredPane or consider drawing on the top level window's glass pane.

Upvotes: 4

Related Questions