Hello, I've got this problem with an intro to Java class. To lay some background down, the professor teaches the 'theory' behind java, and nothing of actual code, so my knowledge is very limited here.

The reason I'm here is I can't discern for the life of me how to clear a java Canvas. I've created shapes on it (rectangles, lines etc). But the goal I seek here is to create a clear button (which will clear the canvas, and let the use create more of the same shapes with the same color) and a reset button(which does the same as clear, but resets to normal). With the reset button, I got everything to reset, but it does not erase.

ex code of that

case OVAL :
            	diameter = Math.max(width, height);
                if(filledColor == null)
                    g.drawOval(x, y, width, height);
                else
                    g.fillOval(x, y, width, height);
                break;

I have no real idea how to erase it. My professor vaguely hinted at clearRect, but I'm at a loss as to how to implement this. Here are the things I've tried from sources all over the internet:

case CLEAR : 
            	//repaint();
            	//g.clearRect(x, y, width, height);
                g.setColor(getBackground());
                g.clearRect(0, 0, width, height);
            	break;

When I do use it, My current shape selection disappears. And when used with reset, the shape stays, but reverts to the standard shape when the program starts. Is there another way, that would just erase the canvas?

Thanks in advance.

My current shape selection disappears

How would clearRect change a selection?
You have not posted enough code to tell what the program is doing.

DrawCanvas.Java

import java.awt.*;
import java.awt.event.*;

public class DrawCanvas extends Canvas implements MouseListener,
                                                  MouseMotionListener {

    // Constants for shapes
    public static final int CIRCLE = 1;
    public static final int ROUNDED_RECTANGLE = 2;
    public static final int RECTANGLE_3D = 3;
    public static final int LINE = 4;
    public static final int OVAL = 5;
    public static final int SQUARE = 6;
    public static final int CLEAR = 7;

    // Coordinates of points to draw
    private int x1, y1, x2, y2;

    // shape to draw
    private int shape = CIRCLE;
    /**
     * Method to set the shape
     */
    public void setShape(int shape) {
        this.shape = shape;
    }

    // filled color
    private Color filledColor = null;
    /**
     * Method to set filled color
     */
    public void setFilledColor(Color color) {
        filledColor = color;
    }

    /**
     * Constructor
     */
	public DrawCanvas() {
	    addMouseListener(this);
	    addMouseMotionListener(this);
	} // end of constructor

    /**
     * painting the component
     */
    public void paint(Graphics g) {

        // the drawing area
        int x, y, width, height;

        // determine the upper-left corner of bounding rectangle
        x = Math.min(x1, x2);
        y = Math.min(y1, y2);

        // determine the width and height of bounding rectangle
        width = Math.abs(x1 - x2);
        height = Math.abs(y1 - y2);

        if(filledColor != null)
            g.setColor(filledColor);
        switch (shape) {
            case ROUNDED_RECTANGLE :
                if(filledColor == null)
                    g.drawRoundRect(x, y, width, height, width/4, height/4);
                else
                    g.fillRoundRect(x, y, width, height, width/4, height/4);
                break;
            case CIRCLE :
                int diameter = Math.max(width, height);
                if(filledColor == null)
                    g.drawOval(x, y, diameter, diameter);
                else
                    g.fillOval(x, y, diameter, diameter);
                break;
            case RECTANGLE_3D :
                if(filledColor == null)
                    g.draw3DRect(x, y, width, height, true);
                else
                    g.fill3DRect(x, y, width, height, true);
                break;
            case LINE :
                if(filledColor == null)
                    g.drawLine(x1, y1, x2, y2);
                else
                	g.drawLine(x1, y1, x2, y2);
                break;
            case OVAL :
            	diameter = Math.max(width, height);
                if(filledColor == null)
                    g.drawOval(x, y, width, height);
                else
                    g.fillOval(x, y, width, height);
                break;
            case SQUARE :
                if(filledColor == null)
                    g.drawRect(x, y, width, width);
                else
                    g.fillRect(x, y, width, width);
                break;
            case CLEAR : 
            	//repaint();
            	//g.clearRect(x, y, width, height);
                g.setColor(getBackground());
                g.clearRect(0, 0, width, height);
            	break;
        }
    }

    /**
     * Implementing MouseListener
     */
    public void mousePressed(MouseEvent event) {
        x1 = event.getX();
        y1 = event.getY();
    }

    public void mouseReleased(MouseEvent event) {
        x2 = event.getX();
        y2 = event.getY();
        repaint();
    }

    public void mouseClicked(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}

    /**
     * Implementing MouseMotionListener
     */
    public void mouseDragged(MouseEvent event) {
        x2 = event.getX();
        y2 = event.getY();
        repaint();
    }

    public void mouseMoved(MouseEvent e) {}
}

Draw.java

import java.awt.*;
import java.awt.event.*;

public class Draw extends Frame implements ActionListener, ItemListener {

	// Initial Frame size
	static final int WIDTH = 400;                // frame width
	static final int HEIGHT = 300;               // frame height

    // Color choices
    static final String COLOR_NAMES[] = {"None", "Red", "Blue", "Green"};
    static final Color COLORS[] = {null, Color.red, Color.blue, Color.green};

    // Button control
    Button circle;
    Button roundRec;
    Button threeDRec;
    Button line;
    Button oval;
    Button square;
    Button reset;
    Button clear;

    // Color choice box
    Choice colorChoice;

    // the canvas
    DrawCanvas canvas;

    /**
     * Constructor
     */
	public Draw() {
	    super("Java Draw");
        setLayout(new BorderLayout());

        // create panel for controls
        Panel topPanel = new Panel(new GridLayout(3, 2));
        add(topPanel, BorderLayout.NORTH);

        // create button control
        Panel buttonPanel = new Panel(new FlowLayout(FlowLayout.LEFT));
        topPanel.add(buttonPanel);

        circle = new Button("Circle");
        buttonPanel.add(circle);
        roundRec = new Button("Rounded Rectangle");
        buttonPanel.add(roundRec);
        threeDRec = new Button("3D Rectangle");
        buttonPanel.add(threeDRec);
        
        buttonPanel = new Panel(new FlowLayout(FlowLayout.LEFT));
        topPanel.add(buttonPanel);
        
        line = new Button("Line");
        buttonPanel.add(line);
        oval = new Button("Oval");
        buttonPanel.add(oval);
        square = new Button("Square");
        buttonPanel.add(square);

        // add button listener
        circle.addActionListener(this);
        roundRec.addActionListener(this);
        threeDRec.addActionListener(this);
        line.addActionListener(this);
        oval.addActionListener(this);
        square.addActionListener(this);

        // create panel for color choices
        Panel colorPanel = new Panel(new FlowLayout(FlowLayout.LEFT));
        topPanel.add(colorPanel);
        Label label = new Label("Filled Color:");
        colorPanel.add(label);
        colorChoice = new Choice();
        for(int i=0; i<COLOR_NAMES.length; i++) {
            colorChoice.add(COLOR_NAMES[i]);
        }
        colorPanel.add(colorChoice);
        clear = new Button("Clear");
        colorPanel.add(clear);
        reset = new Button("Reset");
        colorPanel.add(reset);
        reset.addActionListener(this);
        clear.addActionListener(this);
        colorChoice.addItemListener(this);

        // create the canvas
        canvas = new DrawCanvas();
        add(canvas, BorderLayout.CENTER);
	} // end of constructor


    /**
     *  Implementing ActionListener
     */
    public void actionPerformed(ActionEvent event) {
        if(event.getSource() == circle) {  // circle button
            canvas.setShape(DrawCanvas.CIRCLE);
        }
        else if(event.getSource() == roundRec) {  // rounded rectangle button
            canvas.setShape(DrawCanvas.ROUNDED_RECTANGLE);
        }
        else if(event.getSource() == threeDRec) { // 3D rectangle button
            canvas.setShape(DrawCanvas.RECTANGLE_3D);
        }
        else if(event.getSource() == line) { // line button
            canvas.setShape(DrawCanvas.LINE);
         }
         else if(event.getSource() == oval) { // oval button
             canvas.setShape(DrawCanvas.OVAL);
         }
         else if(event.getSource() == square) { // square button
             canvas.setShape(DrawCanvas.SQUARE);
         }
         else if(event.getSource() == clear) { // square button
        	 canvas.setShape(DrawCanvas.CLEAR);
             canvas.repaint();     
         }
         else if(event.getSource() == reset) { // square button
        	 canvas.setShape(DrawCanvas.CLEAR);
             canvas.repaint();     
             canvas.setShape(DrawCanvas.CIRCLE);
             canvas.repaint();    
             canvas.setFilledColor(null);
             colorChoice.select(0);
         }
    }

    /**
     * Implementing ItemListener
     */
    public void itemStateChanged(ItemEvent event) {
        Color color = COLORS[colorChoice.getSelectedIndex()];
        canvas.setFilledColor(color);
    }

    /**
     * the main method
     */
    public static void main(String[] argv) {
        // Create a frame
        Draw frame = new Draw();
        frame.setSize(WIDTH, HEIGHT);
        frame.setLocation(150, 100);

        // add window closing listener
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent event) {
                System.exit(0);
            }
        });

        // Show the frame
        frame.setVisible(true);
    }
}

What is supposed to happen when you execute this?
I get a window with some buttons. Nothing happens when I click on the buttons.

What do you do to see the problem?
Please explain the sequence of events(clicks, drags, button presses,etc) and what you see.
Then say what is wrong with how it works and what you want it to do differently.

Edited 4 Years Ago by NormR1: n/a

So, when you draw a shape, and hit the clear button, it de selects any current shape and redraws the background as a clear rectangle. I would like it to keep that shape. Also, the reset button should be the same, save to set the shape to circle.

. I would like it to keep that shape

I don't understand this. How can you clear it and keep it? Where do you want to keep it when it is cleared?

You have not explained the sequence of events and how you want to change them
Here is a sample sequence of events:
I click on button
button shows its selected
I click on drawing area
I drag the mouse and a shape is drawn
Then ???

What happens next?
What do you want to change about what happens

Alright, so what I want to happen, is basically you click the clear button, and it wipes the canvas. After wiping it the previously drawn shape's button should still be enabled.

What actually happens is you click clear, and it selects the clearRect shape, so you would have to go and again select the shape you want to draw.

previously drawn shape's button should still be enabled.

Where do you disable any buttons? They are all enabled.

Why not have the listener save the currently selected shape in a class variable so it will know that last selected button without the user having to click it again.

This article has been dead for over six months. Start a new discussion instead.