我想在我的应用程序中添加一个功能,允许用户通过在起始位置单击鼠标并在结束位置释放它来绘制直线.当鼠标移动直到最终释放时,线应该移动;类似于使用Microsoft Paint应用程序绘制线条的方式.
如何实现这一点,以便线条在移动时重新绘制,而不重新绘制可能已在该矩形区域中绘制的其他内容?
解决方法:
试试这个……当鼠标移动(拖动)时,在屏幕上画一条红线.
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);
}