nsc010
nsc010

Reputation: 385

Drawing a shape with an undefined size

I have been looking at the Java2D tutorials and was wondering how to draw a shape using the mouse to define its size(i.e the size of the shape is not fixed). I haven't come across a tutorial specifically for this and was wondering how I could implement this for a rectangle for example.

Upvotes: 0

Views: 97

Answers (3)

shuangwhywhy
shuangwhywhy

Reputation: 5625

Basically, the size is FIXED at every moment. When you add a MouseMotionListener, before the next event is captured, you can paint the shape on the screen with the size depending on current MouseEvent.getPoint() which tells you the coordinates of your mouse location.

Override the paintComponent(Graphics g) method of the component. and call repaint() method after each update of the mouse location and the size of the shape:

class YourPanel extends JPanel extends MouseMotionListener, MouseListener {

    private Rectangle rect = new Rectangle();

    public YourPanel () {
        addMouseListener(this);
        addMouseMotionListener(this);
    }

    @Override
    public void paintComponent (Graphics g) {
        super.paintComponent(g);
        g.draw(rect);
    }

    @Override
    public void mouseDragged (MouseEvent me) {
        rect.setSize(me.getX() - rect.x, me.getY() - rect.y);
        repaint();
    }

    @Override
    public void mousePressed (MouseEvent me) {
        rect.setLocation(me.getX(), me.getY());
        repaint();
    }

    // Other methods...

}

Upvotes: 1

corvid
corvid

Reputation: 11187

You should have your class implement a mouse listener, then save the variables of the mouse listener with getX and getY to draw the shape.

Upvotes: 0

AlexWien
AlexWien

Reputation: 28727

Shapes is a word and java class that represents differnet geometric figures like rectangles, ellipses, poly lines, etc.

So first the user would have to decide which shape, e.g a poly line.
You then would catch mouse left click events, and for each click read the mouse coordinates and add that coordinate pair (e.g java.awt.geom.Point2D()) to an ArrayList<Point2D>. The size of such an list is (practically) unbounded.
On each click you will create a current shaped object that will be drawn. Once the user clicks right mouse, the shape is ready und you store it in list of shapes.

Upvotes: 0

Related Questions