用Java写一个涂鸦板控制鼠标移动结合画图功能实现。鼠标拖拽才开始绘制,松开鼠标则停止绘制。
时间: 2024-02-13 08:00:59 浏览: 169
好的,以下是一个简单的Java涂鸦板程序的示例代码,希望能帮到您:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawingBoard extends JFrame implements MouseListener, MouseMotionListener {
private int lastX, lastY;
private boolean isDragging;
private Graphics g;
public DrawingBoard() {
super("Java涂鸦板");
setSize(600, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mousePressed(MouseEvent e) {
lastX = e.getX();
lastY = e.getY();
isDragging = true;
}
public void mouseReleased(MouseEvent e) {
isDragging = false;
}
public void mouseDragged(MouseEvent e) {
if (isDragging) {
int x = e.getX();
int y = e.getY();
g.drawLine(lastX, lastY, x, y);
lastX = x;
lastY = y;
}
}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void paint(Graphics g) {
super.paint(g);
this.g = g;
g.setColor(Color.BLUE);
}
public static void main(String[] args) {
new DrawingBoard();
}
}
```
该程序使用了Java的Swing库来创建图形用户界面,实现了MouseListener和MouseMotionListener接口来监听鼠标事件,以及Graphics类来进行画图操作。当鼠标拖动时,使用drawLine()方法绘制线条,松开鼠标则停止绘制。希望对您有所帮助。
阅读全文