Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java swing draw objects over other components

I am trying to make a small paint program. I am drawing objects over a JPanel which is on top of JFrame (I am using Netbeans 6.9). I have some basic functionality like font, line and fillRectangle. I am using the standard method to draw which is to override paintComponent().

class .... extends JPanel
{
@Override
void paintComponents(Graphics g)
{
.......
}
}

The problem is that when I draw a text,line over a region then it is drawn behind it rather than on top of it. Basically I want to draw objects on top of all other objects that have previously been drawn on the JPanel. I really do not want to switch to other types of layered pane. One very naive method will be to undo every object and paint them in reverse order (last one first).

like image 336
Dipendra Kumar Mishra Avatar asked Oct 19 '25 15:10

Dipendra Kumar Mishra


1 Answers

You will need to override paintComponent(Graphics g) and do not forget to call super.paintComponent(Graphics g);

class .... extends JPanel
{
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);//honor paintComponent an call super to draw other components that were added to the JPanel
        .......
    }
}

You may also need to override getPreferredSize(..) of JPanel and return an appropriate size so the JPanel will be visible:

class .... extends JPanel
{
    @Override
    public Dimension getPreferredSize()
    {
        return new Dimension(300,300);
    }
}

EDIT:

Depending on what you are doing you may also want to have a look at the GlassPane which will allow you to set a transparent pane over the entire JFrame window and can be painted too, which will cause the graphics to be drawn above all others like so:

enter image description here

like image 159
David Kroukamp Avatar answered Oct 21 '25 04:10

David Kroukamp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!