panel with image background and mouse draw

2019-07-08 08:07发布

问题:

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's paintComponent(...) method. There are several reasons for this, one being that if you use the paint(...) 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 the BufferedImage to gain a Graphics2D object.
    • paint the lines or other visual elements to the graphics instance.
    • dispose of the graphics instance.
    • Call repaint() on the label.

E.G. as seen in this answer.