创建交互式图形编辑器-使用javax.swing
发布时间:2023-12-23 02:45:18
交互式图形编辑器是一种允许用户在窗口界面中绘制和编辑图形的应用程序。使用javax.swing包,我们可以很容易地创建这样一个应用程序,并为用户提供直观的图形编辑体验。
以下是一个使用javax.swing创建交互式图形编辑器的示例代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GraphicEditor extends JFrame {
private Canvas canvas;
private JButton circleButton;
private JButton rectangleButton;
private JButton clearButton;
private JLabel statusBar;
private enum Mode {
CIRCLE,
RECTANGLE
}
private Mode mode;
public GraphicEditor() {
super("Interactive Graphic Editor");
// 初始化界面元素
canvas = new Canvas();
circleButton = new JButton("Circle");
rectangleButton = new JButton("Rectangle");
clearButton = new JButton("Clear");
statusBar = new JLabel();
// 设置布局和组件位置
setLayout(new BorderLayout());
add(canvas, BorderLayout.CENTER);
add(circleButton, BorderLayout.NORTH);
add(rectangleButton, BorderLayout.WEST);
add(clearButton, BorderLayout.EAST);
add(statusBar, BorderLayout.SOUTH);
// 设置按钮事件监听器
circleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mode = Mode.CIRCLE;
statusBar.setText("Drawing Circle");
}
});
rectangleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mode = Mode.RECTANGLE;
statusBar.setText("Drawing Rectangle");
}
});
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.clear();
statusBar.setText("Canvas Cleared");
}
});
// 设置鼠标事件监听器
canvas.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if (mode == Mode.CIRCLE) {
canvas.drawCircle(x, y);
} else if (mode == Mode.RECTANGLE) {
canvas.drawRectangle(x, y);
}
}
});
}
public static void main(String[] args) {
GraphicEditor editor = new GraphicEditor();
editor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editor.setSize(800, 600);
editor.setVisible(true);
}
// 画布类
private class Canvas extends JPanel {
private Graphics2D g2d;
public Canvas() {
setBackground(Color.WHITE);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g2d = (Graphics2D) g;
}
public void drawCircle(int x, int y) {
g2d.setColor(Color.RED);
g2d.fillOval(x - 20, y - 20, 40, 40);
}
public void drawRectangle(int x, int y) {
g2d.setColor(Color.BLUE);
g2d.fillRect(x - 30, y - 20, 60, 40);
}
public void clear() {
g2d.clearRect(0, 0, getWidth(), getHeight());
}
}
}
在上面的代码中,我们创建了一个名为GraphicEditor的类,继承自JFrame。在构造函数中,我们初始化了界面元素,包括一个Canvas画布对象、三个JButton按钮对象和一个JLabel标签对象,用于显示状态栏。
在GraphicEditor的构造函数中,我们为三个按钮对象分别添加了点击事件监听器。当用户点击Circle按钮时,会将编辑模式设置为画圆,并在状态栏显示"Drawing Circle";当用户点击Rectangle按钮时,会将编辑模式设置为画矩形,并在状态栏显示"Drawing Rectangle";当用户点击Clear按钮时,会清空画布并在状态栏显示"Canvas Cleared"。
此外,我们还为画布对象添加了鼠标事件监听器。当用户在画布上点击鼠标时,根据当前的编辑模式,在鼠标点击位置绘制对应的图形。
最后,在main方法中创建了一个GraphicEditor对象,并设置了应用程序的大小和可见性。
运行这个交互式图形编辑器应用程序,就可以在窗口界面中使用鼠标绘制和编辑图形了。
