我想在我的应用程序中添加一个功能,允许用户通过在起始位置单击鼠标并在结束位置释放它来绘制直线。当鼠标移动直到最终释放时,线应该移动;类似于使用Microsoft Paint应用程序绘制线条的方式。
如何实现这一点,以便线条在移动时重新绘制,而不重新绘制可能已在该矩形区域中绘制的其他内容?
答案 0 :(得分:14)
试试这个...当鼠标移动(拖动)时,在屏幕上画一条红线。
public static void main(String args[]) throws Exception {
JFrame f = new JFrame("Draw a Red Line");
f.setSize(300, 300);
f.setLocation(300, 300);
f.setResizable(false);
JPanel p = new JPanel() {
Point pointStart = null;
Point pointEnd = null;
{
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
pointStart = e.getPoint();
}
public void mouseReleased(MouseEvent e) {
pointStart = null;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
pointEnd = e.getPoint();
}
public void mouseDragged(MouseEvent e) {
pointEnd = e.getPoint();
repaint();
}
});
}
public void paint(Graphics g) {
super.paint(g);
if (pointStart != null) {
g.setColor(Color.RED);
g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
}
}
};
f.add(p);
f.setVisible(true);
}
答案 1 :(得分:2)
MouseListener界面是您的朋友。您可以只实现mousePressed和mouseReleased函数。 MouseListener接口具有以下可以使用的方法:
public void mouseEntered(MouseEvent mouse){ }
public void mouseExited(MouseEvent mouse){ }
public void mousePressed(MouseEvent mouse){ }
public void mouseReleased(MouseEvent mouse){ }
答案 2 :(得分:1)
JFrame frame = new JFrame("Lines");
frame.add(new JComponent() {
private Shape line = null;
{
line = new Line2D.Double(100, 100, 200, 200);
prevPoint = new Point();
newPoint = new Point();
MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
prevPoint = e.getPoint();
System.out.println("Prev Point=" + prevPoint.toString());
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
int dx = 0;
int dy = 0;
dx = (int) (prevPoint.x - e.getPoint().getX());
dy = (int) (prevPoint.y - e.getPoint().getY());
Line2D shape = (Line2D) line;
int x1 = (int) (shape.getX1() - dx);
int y1 = (int) (shape.getY1() - dy);
int x2 = (int) (shape.getX2() - dx);
int y2 = (int) (shape.getY2() - dy);
Point startPoint = new Point(x1, y1);
Point endPoint = new Point(x2, y2);
if (shape != null) {
shape.setLine(startPoint, endPoint);
prevPoint = e.getPoint();
repaint();
}
}
@Override
public void mouseReleased(MouseEvent e) {
repaint();
}
};
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.BLUE);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (line != null) {
g2d.draw(line);
}
}
});
frame.setSize(650, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
这会在鼠标移动时移动线条。 希望这会有所帮助..