问题
How can I use a image as background in a JPanel if the paint () method is already used for other purposes? (I'm tried to draw over a image in a panel).
Here is my code to draw as a pencil, but I don´t know how to add the image as background ?
@Override
public void paint(Graphics g) {
if (x >= 0 && y >= 0) {
g.setColor(Color.BLACK);
g.fillRect(x, y, 4, 4);
}
}
Thanks Diego
回答1:
Suggestions:
- Don't draw in the JPanel's
paint(...)
method but rather use it'spaintComponent(...)
method. There are several reasons for this, one being that if you use thepaint(...)
method, then you are also responsible for drawing the JPanel's borders and child components and at risk of messing up the rendering of these guys. Also you lose Swing's automatic double buffering. - First call the parent class's super method before calling any other code in the method. This will allow the JPanel to refresh its background and do any graphics housekeeping that may need to be done.
- Next draw your background image using
g.drawImage(...)
, - Then do your pencil drawing.
回答2:
Hovercraft Full Of Eels gave good advice on one direction to take. Here is another.
- Display the image in a (
ImageIcon
in a)JLabel
. - When it comes time to paint:
- Call
createGraphics()
on theBufferedImage
to gain aGraphics2D
object. - paint the lines or other visual elements to the graphics instance.
- dispose of the graphics instance.
- Call
repaint()
on the label.
- Call
E.G. as seen in this answer.

来源:https://stackoverflow.com/questions/12102076/panel-with-image-background-and-mouse-draw