2

Possible Duplicate:
How to draw a rectangle on a java applet using mouse drag event and make it stay

Hello. I would like to know how I can draw rectangle using mousedragged event. I know that I must record mouse location using class Point. I need to implement paint function in paint method and in mousedragged call it or my paint code should implement in mousedragged event?

At this time I put my code in mouse dragged event. This is code:

@Override
    public void mousePressed(MouseEvent e)
    {
        super.mousePressed(e);
        System.out.println("f.getGlassPane() mousePressed");
        if(e.getButton() == MouseEvent.BUTTON1)


        frame.getGlassPane().setVisible(true);

        startPoint=e.getPoint();

        Graphics2D g = null;
            Graphics2D g2 = (Graphics2D) g;
        Rectangle2D prostokat = new Rectangle2D.Double();
        prostokat.setFrameFromDiagonal(e.getPoint().x, e.getPoint().y,startPoint.x, startPoint.y);
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5F));
        g2.setColor(Color.BLUE);
        g2.fill(prostokat);
        g2.draw(prostokat);

    }

    });
Community
  • 1
  • 1
edi233
  • 3,511
  • 13
  • 56
  • 97
  • 3
    There are a lot of comparable questions on SO - this one could have an answer for your problem: http://stackoverflow.com/questions/1115359/how-to-draw-a-rectangle-on-a-java-applet-using-mouse-drag-event-and-make-it-stay – Andreas Dolk May 16 '11 at 13:07
  • use mousePressed and store the location and store the location of the mouseReleased. With those values you can calculate your rect. – monty May 16 '11 at 13:13
  • I have a question. When I will be painting my rectangle using mousedragged, he will be blinking? In example from Andreas_D post when I draw rectangle he blinking. I don't want to see this effect – edi233 May 16 '11 at 13:19
  • `JPanel` is double buffered by default; this is usually satisfactory. +1 for using `AlphaComposite`. – trashgod May 16 '11 at 14:49

1 Answers1

2

You'll also need to handle mouseReleased and mouseDragged, as shown here and here.

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