Diego Arena
Diego Arena

Reputation: 136

panel background image take screenshot

I'm trying to draw over an image (with the mouse) in a JPanel, this is working, but when I try to take an screenshot of the panel and generate an image of this, I only can see the image background without drawn with the mouse.

This is my code to generate the background Panel.java

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(this.createImage("/imagenes/cuerpoHumano.png").getImage(), 0, 0, null);
}

This is my code to draw as a pencil over the image: Panel.java

private void formMouseDragged(java.awt.event.MouseEvent evt) {
    x = evt.getX();
    y = evt.getY();

    this.getGraphics().setColor(Color.RED);
    this.getGraphics().fillOval(x, y, 4, 4);
}                                 

This is the code to generate an screenshot

Dimension size = panel.getSize();
BufferedImage image = (BufferedImage) panel.createImage(size.width, size.height);
Graphics g = image.getGraphics();
panel.paint(g);
g.dispose();
try {
    String fileName = UUID.randomUUID().toString().substring(0, 18);
    ImageIO.write(image, "jpg", new File(path, fileName + ".jpg"));

} catch (IOException e) {
    e.printStackTrace();
}

Upvotes: 3

Views: 572

Answers (2)

Diego Arena
Diego Arena

Reputation: 136

I think this is code that works .

public class PanelImagenCuerpoHumano extends JPanel {

    private int x = -1;
    private int y = -1;
    private Image image = null;
    private ArrayList<Point> puntos = new ArrayList<Point>();

    public PanelImagenCuerpoHumano() {

        image = new ImageIcon(getClass()
            .getResource("/imagenes/cuerpoHumano.png")).getImage();

        this.addMouseMotionListener(new MouseMotionListener() {

            @Override
            public void mouseDragged(MouseEvent e) {
                x = e.getX();
                y = e.getY();
                puntos.add(new Point(x, y));
                repaint();
            }

            @Override
            public void mouseMoved(MouseEvent e) {
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {

        g.drawImage(image, 0, 0, null);
        for (Point p : puntos) {
            g.setColor(Color.red);
            g.fillOval(p.x, p.y, 3, 3);
        }
    }
}

Upvotes: 0

Dan D.
Dan D.

Reputation: 32391

When you are taking the screenshot, the paintComponent() method is called. This means it will only paint you the image. You have to store the mouse move inside some model and paint the contents of the model in the paintComponent() method. This method is triggered by calling repaint() on the panel during the mouse move.

Upvotes: 3

Related Questions