简易涂鸦板Java代码
时间: 2023-07-03 07:28:16 浏览: 100
简易涂鸦板
以下是一个简易涂鸦板的 Java 代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DoodleBoard extends JFrame implements MouseListener, MouseMotionListener {
private int lastX;
private int lastY;
private Color currentColor;
private JPanel canvas;
public DoodleBoard() {
super("Doodle Board");
setLayout(new BorderLayout());
currentColor = Color.BLACK;
canvas = new JPanel();
canvas.setBackground(Color.WHITE);
canvas.addMouseListener(this);
canvas.addMouseMotionListener(this);
add(canvas, BorderLayout.CENTER);
JPanel colorPanel = new JPanel();
colorPanel.setLayout(new GridLayout(1, 0));
add(colorPanel, BorderLayout.SOUTH);
JButton blackButton = new JButton("Black");
blackButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentColor = Color.BLACK;
}
});
colorPanel.add(blackButton);
JButton redButton = new JButton("Red");
redButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentColor = Color.RED;
}
});
colorPanel.add(redButton);
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void mousePressed(MouseEvent e) {
lastX = e.getX();
lastY = e.getY();
}
public void mouseDragged(MouseEvent e) {
Graphics g = canvas.getGraphics();
g.setColor(currentColor);
g.drawLine(lastX, lastY, e.getX(), e.getY());
lastX = e.getX();
lastY = e.getY();
}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
new DoodleBoard();
}
}
```
此代码创建了一个带有涂鸦板功能的窗口,用户可以在窗口中使用鼠标进行绘画。用户可以通过点击底部的按钮来选择颜色。涂鸦板使用 `JPanel` 组件作为画布,并在组件上使用 `MouseListener` 和 `MouseMotionListener` 来处理鼠标事件。在鼠标拖动期间,程序使用 `Graphics` 对象的 `drawLine` 方法来绘制线条。
阅读全文