为什么他们“忘记”实现这一点,这是一个很好的问题。我会争辩说,JavaFX 仍在开发中(应该说一切)。但是,我很久以前就需要这个,并且我使用命令模式实现了我自己的方法。如下图,这并不费力,也很简单。
首先您需要创建一个名为Command 的接口,以在您的应用程序中执行一些操作。
public interface Command {
/**
* This is called to execute the command from implementing class.
*/
public abstract void execute();
/**
* This is called to undo last command.
*/
public abstract void undo();
}
接下来,您将需要一个名为History 的类来保存已执行的命令并撤消它们。
public final class History {
// ...
private static History instance = null;
private final Stack<Command> undoStack = new Stack<Command>();
// ...
public void execute(final Command cmd) {
undoStack.push(cmd);
cmd.execute();
}
public void undo() {
if (!undoStack.isEmpty()) {
Command cmd = undoStack.pop();
cmd.undo();
} else {
System.out.println("Nothing to undo.");
}
}
public static History getInstance() {
if (History.instance == null) {
synchronized (History.class) {
if (History.instance == null) {
History.instance = new History();
}
}
}
return History.instance;
}
private History() { }
}
然后在您的 FXML 中为您的 GUI 创建一个按钮,该按钮应该调用您的应用程序的撤消功能。在您的 FXML 中创建一个按钮,如下所示:
<Button fx:id="btnUndo" font="$x2" onAction="#onUndo" prefWidth="75.0"
text="Undo" textAlignment="CENTER" underline="false">
<tooltip>
<Tooltip text="Undo last command" textAlignment="JUSTIFY" />
</tooltip>
<HBox.margin>
<Insets left="5.0" right="5.0" fx:id="x1" />
</HBox.margin>
</Button>
在您的控制器类中,您从 FXML 中引用按钮。
public class Controller {
// ...
@FXML private Button btnUndo;
// ...
@FXML
public void onUndo(ActionEvent event)
{
History.getInstance().undo();
}
}
如您所见,最好的事情是 History 类是一个单例。因此,您可以从任何地方访问该课程。
从Command接口继承来实现一个新的命令。使用一些按钮或类似的 GUI 元素来实现新功能,并使用您的历史记录执行自定义命令。
// You can give arguments to command constructor if you like
Command someCmd = new SomeCommand();
History.getInstance().execute(someCmd); // Saved to history; now you're able to undo using button
通过这种方法,您将能够撤消您的操作。也可以实现一些重做功能。为此,只需在 FXML 中添加一个重做按钮,并在 History 类和 Command 接口中添加适当的方法。
有关命令模式的更多信息,请查看here。
编码愉快!