用mousemotionlistener画出曲线
时间: 2023-08-30 22:12:35 浏览: 79
好的,下面是一个使用`MouseMotionListener`绘制曲线的例子:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawPanel extends JPanel implements MouseMotionListener {
private int x, y;
private Graphics2D g2d;
private boolean isDrawing = false;
public DrawPanel() {
addMouseMotionListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (g2d == null) {
g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(2));
}
}
public void mouseDragged(MouseEvent e) {
if (!isDrawing) {
x = e.getX();
y = e.getY();
isDrawing = true;
} else {
int x2 = e.getX();
int y2 = e.getY();
g2d.drawLine(x, y, x2, y2);
x = x2;
y = y2;
}
}
public void mouseMoved(MouseEvent e) {
isDrawing = false;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Panel");
DrawPanel panel = new DrawPanel();
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
```
这个例子创建了一个`DrawPanel`类,它继承了`JPanel`并实现了`MouseMotionListener`接口。`DrawPanel`类在构造函数中注册了自身作为`MouseMotionListener`,并重写了`paintComponent`方法来设置`Graphics2D`对象的线条宽度。当鼠标被拖动时,`mouseDragged`方法会被调用,它绘制了一条线段来连接之前的鼠标位置和当前鼠标位置。当鼠标移动时,`mouseMoved`方法会被调用,它将`isDrawing`标记为`false`,以便在下一次鼠标拖动时开始绘制新的曲线。
当你运行这个例子时,你可以按住鼠标并拖动来绘制曲线。
阅读全文