2

I have a program which lets the user paint. But when the user clicks the clear button which calls clearRect() and repaint() the user can no longer keep painting on the same panel. Another issue I am having is that when the user clicks the save or open button (which open up a file explorer window), if the user presses cancel, the panel paints the file window onto the panel. How would I go about fixing these issues?

public void paintComponent(Graphics g){
    super.paintComponents(g);
    g.fillOval(myX - radius, myY - radius, 2 * radius, 2 * radius);
    if(img != null)
        g.drawImage(img, 0, 0, null);
} 

Below portion is inside of an actionPerformed method

if(source == clear){
    g.setBackground(Color.WHITE);
    g.clearRect(0, 0, getWidth(), getHeight());
    repaint();
}

BufferedImage and Graphics

BufferedImage img = new BufferedImage(1000, 1000, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();

1 Answers1

2

I suspect that the Graphics context, g, is invalid in your ActionListener, perhaps due to using getGraphics() inappropriately. Instead, let your ActionListener update fields in your view class and modify the Graphics context in paintComponent() using the updated values.

In this complete example, the various implementations of actionPerformed() in the buttonPanel update attributes in the DrawingArea. The implementation of paintComponent() in DrawingArea then knows what to draw each time it is called.

image

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045