Reputation: 311
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).
Upvotes: 4
Views: 6934
Reputation: 3921
This is an old question, but I had the same problem and solved it by overriding paintChildren(Graphics g)
instead of paintComponent
.
As the Oracle documentation states, the order of execution for the three paint
methods is:
protected void paintComponent(Graphics g)
protected void paintBorder(Graphics g)
protected void paintChildren(Graphics g)
So, paintChildren(g)
is run last, which means whatever we draw inside it is drawn on top of all previously drawn components.
Upvotes: 0
Reputation: 36423
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:
Upvotes: 4