问题描述
我想根据mousedrag事件绘制矩形。如果用户拖动鼠标,然后在小程序中的矩形应该增加或减少立足当前鼠标的坐标。
我有以下code。
I want to draw rectangle based on mousedrag event. if user dragging the mouse, then the rectangle on the applet should increase or decrease basing on current mouse coordinates.i have the following code.
在以下code我使用延伸上对此我进行绘图操作的画布SelectionArea类。我正在使用本类双缓冲图像变量减少闪烁并保存applet的previous状态(即绘图小程序的内容)
in the following code i am using SelectionArea class which extends a canvas on which i am performing drawing operation. i am using image variable in this class for double buffering to reduce flickering and to save the applet's previous state(i.e drawing content of applet)
但是,如果我画一个矩形的code是工作的罚款。如果我开始绘制第二个矩形的previously绘制的矩形正在消失。我想previously绘制的矩形要在屏幕上
but the code is working fine if i draw first rectangle. if i start to draw second rectangle the previously drawn rectangle is disappearing. i want the previously drawn rectangle to be on the screen
PLZ告诉我怎么解决这个问题。
plz tell me how to solve this.
推荐答案
您需要做的,是的保存previously绘制的矩形在某些类型的数据结构上,这样你就可以画再次更新版本。
What you need to do, is save the previously drawn rectangle in some sort of data structure, so you can draw it again later.
这code(约长不好意思,会做类似于你所描述的东西。
要使用它,只是巴掌的JPanel
内部的的JFrame
。
This code (sorry about the length, will do something similar to what you are describing.
To use it, just slap the JPanel
inside of a 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);
}
}
这篇关于在Java中的JFrame中拖动矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!