可能重复:
How to draw a rectangle on a java applet using mouse drag event and make it stay
您好。 我想知道如何使用mousedragged事件绘制矩形。我知道我必须使用Point类记录鼠标位置。我需要在paint方法中实现绘制函数,在mousedragged中调用它或者我的绘图代码应该在mousedragged事件中实现?
此时我将我的代码放在鼠标拖动事件中。这是代码:
@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);
}
});