2. 涂鸦板是一个具有趣味性的小程序,它的实现原理是通过鼠标事件,控制鼠标移动结合画图功能实现。鼠标拖拽才开始绘制,松开鼠标则停止绘制。 请用Java图形界面的知识,编写以上软件。
时间: 2023-12-31 07:06:02 浏览: 76
以下是使用Java Swing库创建一个简单的涂鸦板的示例代码:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
public class DoodleBoard extends JFrame {
private int lastX, lastY;
private Color currentColor = Color.BLACK;
private JPanel canvas;
public DoodleBoard() {
setTitle("Doodle Board");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
};
canvas.setBackground(Color.WHITE);
canvas.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
lastX = e.getX();
lastY = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
lastX = -1;
lastY = -1;
}
});
canvas.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if (lastX != -1 && lastY != -1) {
Graphics g = canvas.getGraphics();
g.setColor(currentColor);
g.drawLine(lastX, lastY, e.getX(), e.getY());
lastX = e.getX();
lastY = e.getY();
}
}
});
JButton blackButton = new JButton("Black");
blackButton.addActionListener(e -> currentColor = Color.BLACK);
JButton redButton = new JButton("Red");
redButton.addActionListener(e -> currentColor = Color.RED);
JButton greenButton = new JButton("Green");
greenButton.addActionListener(e -> currentColor = Color.GREEN);
JButton blueButton = new JButton("Blue");
blueButton.addActionListener(e -> currentColor = Color.BLUE);
JPanel buttonPanel = new JPanel(new GridLayout(1, 4));
buttonPanel.add(blackButton);
buttonPanel.add(redButton);
buttonPanel.add(greenButton);
buttonPanel.add(blueButton);
add(canvas, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public static void main(String[] args) {
new DoodleBoard();
}
}
```
这个程序创建了一个简单的涂鸦板窗口,可以通过鼠标拖拽来绘制线条,并且可以通过按钮来改变绘制的颜色。运行程序后,你将看到一个具有绘画功能的窗口,可以在上面进行涂鸦。
阅读全文