好的,我的问题很简单:我制作了 Paint 应用程序,并且我想提供某种“撤消”功能。我阅读了有关撤消管理器等的信息,但这种方法对我来说似乎很难理解,所以我决定自己设计。我的想法很简单:因为我在 JPanel 上绘图,所以我只会在进行任何绘图操作之前保存其当前内容。撤消按钮只会恢复上一个。
问题是:我无法“恢复”保存的图像并将其放在 JPanel 上。我很困惑,因为我已经在硬盘驱动器上“保存”了当前图像,并从硬盘驱动器“打开”了任意图像。两者都工作得很好。
不幸的是,为我的“撤消”系统尝试完全相同的方法不起作用。
查看代码:(为简化起见,我手动“保存”当前图片 -> 用于测试目的)
public class PictureEdit { //class for saving the current JPanel drawing for undo
public BufferedImage saveBI;
public Graphics2D saveG2D;
}
public void actionPerformed(ActionEvent e) { //action for "UNDO" button, not working
//drawingField - instance of JPanel
//pe - instance of PictureEdit class
drawingField.setBufferedImg(drawingField.pe.saveBI);
drawingField.updateArea(drawingField.getBufferedImg());
}
public void actionPerformed(ActionEvent e) { //action for manual "save" (for undo)
drawingField.pe.saveBI=drawingField.getBufferedImg();
drawingField.pe.saveG2D=(Graphics2D)drawingField.getBufferedImg().getGraphics();
}
现在是我的工作解决方案的示例,但与 HDD 上的 wok witk 文件有关:
public void actionPerformed(ActionEvent e){ //Opening file from harddrive - works fine
JFileChooser jfc = new JFileChooser();
int selection = jfc.showOpenDialog(PaintUndo.this);
if (selection == JFileChooser.APPROVE_OPTION){
try {
drawingField.setBufferedImg(ImageIO.read(jfc.getSelectedFile()));
drawingField.updateArea(drawingField.getBufferedImg());
} catch (IOException ex) {
Logger.getLogger(PaintUndo.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(PaintUndo.this, "Could not open file");
}
}
}
public void actionPerformed(ActionEvent e) { //Saving to harddrive - works fine
int n = JOptionPane.showConfirmDialog(PaintUndo.this, "Are you sure you want to save?", "Saving image...", JOptionPane.OK_CANCEL_OPTION);
if (n == JOptionPane.YES_OPTION){
JFileChooser jfc = new JFileChooser();
int nn = jfc.showSaveDialog(PaintUndo.this);
if (nn == JFileChooser.APPROVE_OPTION){
File saveFile = new File(jfc.getSelectedFile()+".bmp");
try {
ImageIO.write(drawingField.getBufferedImg(), "bmp", saveFile);
} catch (IOException ex) {
Logger.getLogger(PaintUndo.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(PaintUndo.this, "Error while saving file");
}
}
}
}
以防万一有人好奇:updateArea
函数(表示提到的扩展 JPanel 类的成员drawingField
):
public void updateArea(BufferedImage img){ //it is just resizing the current picture (if necessary) and then assigns the new Graphics.
area.height=img.getHeight();
area.width=img.getWidth();
this.setPreferredSize(area);
g2d = (Graphics2D)this.getGraphics();
}
基本上程序是完全相同的,处理文件是可以的,而当我对变量进行操作时,我无法保存和恢复图像......可能有什么问题?有任何想法吗?drawingField
当我使用 Undo/UndoSave 按钮时,我的 JPanel ( )中绝对没有任何变化
任何帮助表示赞赏