在eclipse里用窗体的形式做以下功能:使用命令模式设计一个图形绘制系统,该系统可以绘制矩形、椭圆、三角形等图形,要求有恢复和撤销功能。绘制类图并编程实现。
时间: 2024-02-15 15:01:28 浏览: 191
好的,这是一个比较复杂的问题,我会尽力回答。首先,我们需要设计一个命令接口,用于执行和撤销绘图命令。接口可以定义两个方法:execute()和undo()。
```java
public interface DrawCommand {
void execute();
void undo();
}
```
接下来,我们需要实现具体的绘图命令类,例如矩形绘图命令类、椭圆绘图命令类、三角形绘图命令类等。这些类都需要实现DrawCommand接口,并实现execute()和undo()方法。
```java
public class RectangleCommand implements DrawCommand {
private Rectangle rectangle;
private Graphics graphics;
public RectangleCommand(Rectangle rectangle, Graphics graphics) {
this.rectangle = rectangle;
this.graphics = graphics;
}
@Override
public void execute() {
graphics.drawRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
}
@Override
public void undo() {
graphics.clearRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
}
}
```
在每次绘图时,我们可以创建一个新的绘图命令对象,并将其添加到命令历史记录中。当需要撤销时,可以从历史记录中取出最后一个命令,并调用其undo()方法。
```java
public class DrawCanvas extends JPanel {
private List<DrawCommand> commandHistory = new ArrayList<>();
private Graphics graphics;
private DrawCommand currentCommand;
public DrawCanvas() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Rectangle rectangle = new Rectangle(e.getX(), e.getY(), 0, 0);
currentCommand = new RectangleCommand(rectangle, graphics);
commandHistory.add(currentCommand);
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
graphics = g;
for (DrawCommand command : commandHistory) {
command.execute();
}
}
public void undo() {
if (!commandHistory.isEmpty()) {
DrawCommand lastCommand = commandHistory.remove(commandHistory.size() - 1);
lastCommand.undo();
repaint();
}
}
}
```
最后,我们需要在窗体中添加绘图面板,并添加撤销按钮。当点击撤销按钮时,我们可以调用绘图面板的undo()方法。
```java
public class MainFrame extends JFrame {
private DrawCanvas canvas;
public MainFrame() {
canvas = new DrawCanvas();
getContentPane().add(canvas, BorderLayout.CENTER);
JButton undoButton = new JButton("Undo");
undoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
canvas.undo();
}
});
getContentPane().add(undoButton, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
```
以上是一个简单的命令模式实现的图形绘制系统,可以绘制矩形、椭圆、三角形等图形,并支持撤销和恢复操作。
阅读全文
相关推荐
















