java绘制鼠标拖动线
时间: 2023-10-14 07:12:28 浏览: 107
以下是一个简单的Java程序,用于绘制鼠标拖动线:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DrawingPanel extends JPanel implements MouseMotionListener {
private int x1, y1, x2, y2;
public DrawingPanel() {
addMouseMotionListener(this);
}
@Override
public void mouseDragged(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(x1, y1, x2, y2);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Drawing Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.getContentPane().add(new DrawingPanel());
frame.setVisible(true);
}
}
```
这个程序创建了一个JPanel,监听鼠标的拖动事件,并在拖动时更新线的终点坐标。在绘制组件时,程序使用Graphics对象绘制直线,起点为(x1, y1),终点为(x2, y2)。当鼠标拖动时,程序调用repaint()方法重新绘制组件,从而实现鼠标拖动线的效果。您可以将此代码复制并执行,查看效果。
阅读全文