java Gui徒手绘画
时间: 2023-06-18 22:02:34 浏览: 146
Java GUI(图形用户界面)可以使用Java Swing库进行开发,绘画可以使用Java Graphics2D类。下面是一个简单的Java GUI程序,该程序提供了一个绘画区和一些工具,可以选择画笔颜色和笔刷大小,还有橡皮擦工具。
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawingApp extends JFrame {
private JPanel canvas;
private JComboBox<String> colorChooser;
private JComboBox<Integer> sizeChooser;
private JToggleButton eraseButton;
private Color currentColor = Color.black;
private int currentSize = 5;
public static void main(String[] args) {
DrawingApp app = new DrawingApp();
app.setVisible(true);
}
public DrawingApp() {
setTitle("Drawing App");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create canvas panel and add to frame
canvas = new JPanel();
canvas.setBackground(Color.white);
canvas.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
Graphics2D g = (Graphics2D) canvas.getGraphics();
g.setColor(currentColor);
if (eraseButton.isSelected()) {
g.setColor(canvas.getBackground());
}
g.setStroke(new BasicStroke(currentSize,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.drawLine(e.getX(), e.getY(), e.getX(), e.getY());
}
});
canvas.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
Graphics2D g = (Graphics2D) canvas.getGraphics();
g.setColor(currentColor);
if (eraseButton.isSelected()) {
g.setColor(canvas.getBackground());
}
g.setStroke(new BasicStroke(currentSize,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.drawLine(e.getX(), e.getY(), e.getX(), e.getY());
}
});
add(canvas, BorderLayout.CENTER);
// create tool panel and add to frame
JPanel toolPanel = new JPanel();
add(toolPanel, BorderLayout.NORTH);
colorChooser = new JComboBox<String>(new String[] {"Black", "Red", "Green", "Blue"});
colorChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String color = (String) colorChooser.getSelectedItem();
switch (color) {
case "Black":
currentColor = Color.black;
break;
case "Red":
currentColor = Color.red;
break;
case "Green":
currentColor = Color.green;
break;
case "Blue":
currentColor = Color.blue;
break;
}
}
});
toolPanel.add(new JLabel("Color:"));
toolPanel.add(colorChooser);
sizeChooser = new JComboBox<Integer>(new Integer[] {1, 3, 5, 10});
sizeChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentSize = (Integer) sizeChooser.getSelectedItem();
}
});
toolPanel.add(new JLabel("Size:"));
toolPanel.add(sizeChooser);
eraseButton = new JToggleButton("Eraser");
toolPanel.add(eraseButton);
}
}
```
该程序创建了一个JFrame窗口,并在其中添加了一个绘画区(JPanel)和一个工具区(JPanel)。绘画区使用MouseListener和MouseMotionListener监听鼠标事件,并使用Graphics2D类绘制图形。工具区提供了选择颜色、笔刷大小和橡皮擦工具的选项。
阅读全文