java画图_Java实现的简单画图板示例
时间: 2024-03-07 22:48:55 浏览: 75
以下是一个简单的Java画图板示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimplePaint extends JFrame implements MouseListener, MouseMotionListener {
private int x1, y1, x2, y2;
private Graphics g;
private JPanel panel;
public SimplePaint() {
super("Simple Paint");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
panel.addMouseListener(this);
panel.addMouseMotionListener(this);
getContentPane().add(panel);
setSize(300, 300);
setVisible(true);
g = panel.getGraphics();
}
public void mousePressed(MouseEvent e) {
x1 = e.getX();
y1 = e.getY();
}
public void mouseDragged(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
}
public void mouseMoved(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public static void main(String[] args) {
new SimplePaint();
}
}
```
这个示例使用了Java的Swing库来创建一个画图板。用户可以在画板上拖动鼠标来画线条。在这个示例中,我们使用了JPanel类来创建画板,并添加了鼠标事件监听器来处理用户的输入。我们还使用了Graphics类来绘制线条。
阅读全文