使用java写出绘图板代码
时间: 2024-03-07 07:50:21 浏览: 25
好的,以下是一个简单的Java绘图板代码,它可以绘制基本图形、修改颜色等功能。你可以参考它进行修改和扩展:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawingBoard extends JFrame implements ActionListener, MouseListener, MouseMotionListener {
private JMenuBar mb;
private JMenu m;
private JMenuItem mi1, mi2, mi3, mi4, mi5;
private JPanel p;
private Graphics g;
private int x1, y1, x2, y2;
public DrawingBoard() {
setTitle("Drawing Board");
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mb = new JMenuBar();
m = new JMenu("Options");
mi1 = new JMenuItem("Line");
mi2 = new JMenuItem("Rectangle");
mi3 = new JMenuItem("Oval");
mi4 = new JMenuItem("Clear");
mi5 = new JMenuItem("Color");
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
mi4.addActionListener(this);
mi5.addActionListener(this);
m.add(mi1);
m.add(mi2);
m.add(mi3);
m.add(mi4);
m.add(mi5);
mb.add(m);
setJMenuBar(mb);
p = new JPanel();
add(p);
p.addMouseListener(this);
p.addMouseMotionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == mi1) {
g.setColor(Color.BLACK);
} else if (e.getSource() == mi2) {
g.setColor(Color.RED);
} else if (e.getSource() == mi3) {
g.setColor(Color.BLUE);
} else if (e.getSource() == mi4) {
p.repaint();
} else if (e.getSource() == mi5) {
Color c = JColorChooser.showDialog(this, "Choose Color", g.getColor());
g.setColor(c);
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
x1 = e.getX();
y1 = e.getY();
}
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
if (g != null) {
if (mi1.isSelected()) {
g.drawLine(x1, y1, x2, y2);
} else if (mi2.isSelected()) {
g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1), Math.abs(y2 - y1));
} else if (mi3.isSelected()) {
g.drawOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1), Math.abs(y2 - y1));
}
}
}
public void mouseDragged(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
if (g != null) {
if (mi1.isSelected()) {
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
} else if (mi2.isSelected()) {
p.repaint();
g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1), Math.abs(y2 - y1));
} else if (mi3.isSelected()) {
p.repaint();
g.drawOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1), Math.abs(y2 - y1));
}
}
}
public void mouseMoved(MouseEvent e) {
}
public void paint(Graphics g) {
super.paint(g);
this.g = p.getGraphics();
}
public static void main(String[] args) {
DrawingBoard db = new DrawingBoard();
}
}
```
这个绘图板可以绘制直线、矩形、椭圆形,并且可以选择颜色和清除画布。你可以尝试运行这段代码,看看效果。