java画图_Java实现的简单画图板示例
时间: 2024-03-23 09:40:12 浏览: 66
好的,以下是一个简单的Java画图板示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleDraw extends JFrame implements ActionListener {
private JButton clearBtn;
private DrawArea drawArea;
public SimpleDraw() {
// 设置窗口标题
super("Simple Draw");
// 创建清除按钮
clearBtn = new JButton("Clear");
clearBtn.addActionListener(this);
// 创建绘制区域
drawArea = new DrawArea();
// 将按钮和绘制区域添加到窗口中
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.add(clearBtn, BorderLayout.NORTH);
c.add(drawArea, BorderLayout.CENTER);
// 设置窗口大小
setSize(600, 400);
// 显示窗口
setVisible(true);
}
// 处理清除按钮的点击事件
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clearBtn) {
drawArea.clear();
}
}
// 绘制区域类
class DrawArea extends JComponent {
private Image image;
private Graphics2D g2;
public DrawArea() {
// 添加鼠标事件监听器
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
// 记录鼠标按下时的坐标
int x = e.getX();
int y = e.getY();
// 创建新的图像对象
image = createImage(getSize().width, getSize().height);
g2 = (Graphics2D) image.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
g2.setPaint(Color.black);
drawLine(x, y);
}
});
// 添加鼠标事件监听器
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
// 绘制线条
drawLine(e.getX(), e.getY());
}
});
}
// 绘制线条
private void drawLine(int x, int y) {
g2.drawLine(x, y, x, y);
repaint();
}
// 清除图像
public void clear() {
g2.setPaint(Color.white);
g2.fillRect(0, 0, getSize().width, getSize().height);
g2.setPaint(Color.black);
repaint();
}
// 绘制图像
protected void paintComponent(Graphics g) {
if (image == null) {
image = createImage(getSize().width, getSize().height);
g2 = (Graphics2D) image.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g.drawImage(image, 0, 0, null);
}
}
public static void main(String[] args) {
new SimpleDraw();
}
}
```
这个示例实现了一个简单的画图板,可以使用鼠标在绘制区域中绘制线条,并且可以使用清除按钮清除绘制区域中的内容。
阅读全文