我想根据 mousedrag 事件绘制矩形。如果用户拖动鼠标,则小程序上的矩形应根据当前鼠标坐标增加或减少。我有以下代码。
在下面的代码中,我使用的是 SelectionArea 类,它扩展了我正在执行绘图操作的画布。我在这个类中使用图像变量进行双缓冲以减少闪烁并保存小程序的先前状态(即小程序的绘制内容)
但是如果我绘制第一个矩形,代码工作正常。如果我开始绘制第二个矩形,则先前绘制的矩形正在消失。我希望之前绘制的矩形出现在屏幕上
请告诉我如何解决这个问题。
您需要做的是将先前绘制的矩形保存在某种数据结构中,以便稍后再次绘制。
这段代码(对不起长度,会做类似于你所描述的事情。要
使用它,只需拍打JPanel
.JFrame
public class DrawPane extends JPanel {
private List<DrawnShape> drawings;
private DrawnShape curShape;
public DrawPane() {
drawings = new ArrayList<DrawnShape>();
setBackground(Color.WHITE);
setPreferredSize(new Dimension(300, 300));
addMouseListener(clickListener);
addMouseMotionListener(moveListener);
}
@Override
protected void paintComponent(Graphics g2) {
super.paintComponent(g2);
Graphics2D g = (Graphics2D) g2;
for (DrawnShape s : drawings) {
s.draw(g);
}
g.setColor(Color.BLACK);
g.setStroke(new BasicStroke(2));
if (curShape == null)
return;
curShape.draw(g);
}
private MouseListener clickListener = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
curShape = new DrawnShape(e.getPoint(), e.getPoint());
}
@Override
public void mouseReleased(MouseEvent e) {
drawings.add(new DrawnShape(curShape.getClickP(), e.getPoint()));
curShape = null;
}
};
private MouseMotionListener moveListener = new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
curShape = new DrawnShape(curShape.getClickP(), e.getPoint());
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
}
};
}
class DrawnShape {
private Point p1, p2;
public DrawnShape(Point p1, Point p2) {
this.p1 = p1;
this.p2 = p2;
}
public Point getClickP() {
return p1;
}
public void draw(Graphics2D g) {
g.drawLine(p1.x, p1.y, p2.x, p1.y);
g.drawLine(p1.x, p1.y, p1.x, p2.y);
g.drawLine(p2.x, p2.y, p2.x, p1.y);
g.drawLine(p2.x, p2.y, p1.x, p2.y);
}
}
自定义绘画方法展示了两种技术。