Question

I am creating an applet that lets the user draw different shapes using the rubber band effect, letting the user see the shape while it is being drawn. What I want is for the program to draw shapes that stay on the screen. The problem is that the program draws a shape wherever the mouse is.

Take the program below, for example. Say the user clicks the applet at point (50,50) and drags the mouse to draw a rectangle with the bottom-right corner at (70,70). The program will draw several rectangles inside the final rectangle (i.e. rectangles with the bottom-right corner at (54,56), (63,61), etc.). I only want the final rectangle to be shown, but also while using the rubber band effect. If the user were to draw a second rectangle, the first one would remain on the screen while the user draws the second one.

How can I alter the code to make this work?

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

public class Test extends java.applet.Applet implements MouseListener, MouseMotionListener {
    int downX, downY, dragX, dragY;

    public void init() {
        downX = downY = dragX = dragY = 0;

        addMouseListener(this);
        addMouseMotionListener(this);
    }

    public void paint(Graphics g) {
        g.drawRect(downX,downY,dragX-downX,dragY-downY);
    }

    public void update(Graphics g) {
        paint(g);
    }

    public void mouseClicked(MouseEvent e) {
        downX = e.getX();
        downY = e.getY();
    }

    public void mouseDragged(MouseEvent e) {
        dragX = e.getX();
        dragY = e.getY();
        repaint();
    }

    public void /*Other MouseEvent methods*/ {}
}
Was it helpful?

Solution

  1. You've broken the paint chain. Failing to call super.paint is preventing the applet from preparing the Graphics context for painting, by removing anything that might have been painted to it before. There's no need to override update, as you're not doing anything with it.
  2. Typically, you should avoid overriding paint of top level containers, as they aren't double buffered and will flicker as they are repainted
  3. You should avoid using Applet and instead use a combination of JApplet a (for example) JPanel as your drawing surface . In fact, if you're just learning. It would be better to use JFrame as applets have a lot of additional management
  4. Painting by its very nature is destructive. You need to maintain a list of things that you want to draw. In this, I would recommend a List of Points, which can be used to paint lines, where the last point is the current drag point

Also take a look at Painting in AWT and Swing for details about how painting works

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top