Search code examples
javaswingbufferedimagegraphics2d

draw buffered image ontop of another buffered image


my goal is to draw some bufferedimage onto another. then all this stuff draw onto some other bufferedimage and so on. And finally draw this on top of a panel. For now i'm trying to draw bufferedimage onto panel and nothing works. My bufferedimage looks completely white:

public class Main2 {
    public static void main(String[] args) {
        JFrame frame = new JFrame("asdf");
        final JPanel panel = (JPanel) frame.getContentPane();
        frame.setSize(500,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                somepaint(panel);
            }
        });
    }

    private static void somepaint(JPanel panel) {
        BufferedImage image = new BufferedImage(200,200,BufferedImage.TYPE_INT_ARGB);
        image.getGraphics().setColor(Color.red);
        image.getGraphics().fillRect(0, 0, 200, 200);

        Graphics2D graphics = (Graphics2D) panel.getGraphics();
        graphics.setColor(Color.magenta);
        graphics.fillRect(0, 0, 500, 500);
        graphics.drawImage(image, null, 0, 0); // draws white square instead of red one
    }
}

thanks


Solution

  • Re:

    private static void somepaint(JPanel panel) {
        BufferedImage image = new BufferedImage(200,200,BufferedImage.TYPE_INT_ARGB);
        image.getGraphics().setColor(Color.red);
        image.getGraphics().fillRect(0, 0, 200, 200);
    
        Graphics2D graphics = (Graphics2D) panel.getGraphics();
    

    This is not how you draw inside of a JPanel or JComponent.

    Don't call getGraphics() on a component as the Graphics object returned will be short-lived, and anything drawn with it will not persist. Instead do your JPanel's drawing inside of its paintComponent(Graphics G) method override. You will need to create a class that extends JPanel in order to override paintComponent(...).

    Most importantly, to see how to do Swing graphics correctly, don't guess. You'll want to read the Swing Graphics Tutorials first as it will require you to toss out some incorrect assumptions (I know that this is what I had to do to get it right).