Search code examples
javaswingjpanelpaintgraphics2d

Paint JPanel Program using Graphics2D Disappears when Resizing Window


I'm trying to create a JPanel to make a simple paint program that paints whenever the user drags their mouse. However, upon resizing the window, the graphics that I've already drawn disappear. Here is the PaintPanel class:

public class PaintPanel extends JPanel {    

private static final long serialVersionUID = 4267027584083413157L;

private class MouseMotionHandler implements MouseMotionListener {

    public void mouseDragged(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();

        Graphics2D g2 = (Graphics2D)getGraphics();

        g2.setPaint(color);         
        g2.fillOval(x, y, size, size);
    }


    public void mouseMoved(MouseEvent e) {

    }

}

class JSliderHandler implements ChangeListener {
    @Override
    public void stateChanged(ChangeEvent e) {
        JSlider colorChange = (JSlider)e.getSource();
        if (!colorChange.getValueIsAdjusting()) {
            colVal = (int)colorChange.getValue();
            color = new Color(colVal, colVal, colVal);
            System.out.print(colVal);
        }
    }
}

class JSpinnerHandler implements ChangeListener {
    @Override
    public void stateChanged(ChangeEvent e) {
        JSpinner thickChange = (JSpinner)e.getSource();
        size = (int)thickChange.getValue();
    }
}


private Color color;
private int colVal = 0;
private int   size;


public PaintPanel() {     

    color = new Color(colVal, colVal, colVal);
    size  = 8;

    addMouseMotionListener(new MouseMotionHandler());        
}
}

Solution

  • a simple paint program that paints whenever the user drags their mouse.

    See Custom Painting Approaches. It demonstrates two common ways to do custom painting:

    1. Store objects to paint in an ArrayList and then iterate through the ArrayList in the paintComponent(...) method to paint each Object

    2. Paint directly to a BufferedImage and then just paint the BufferedImage.