【发布时间】:2018-02-18 12:02:15
【问题描述】:
你能帮我解决这个问题吗?
我在Cell 类中创建按钮,并向该按钮添加一些默认操作。
public class Cell {
private Button button;
public Cell() {
this.button = new Button();
this.button.setOnAction(e -> System.out.println("Default action"));
}
public Button getButton() {
return button;
}
}
在Game 类中,我想向此按钮添加其他操作,但我也想保留默认操作。
public class Game {
public Game(Button button) {
// this add new action to button but delete previous one
// I want use both actions
button.setOnAction(e -> System.out.println("additional action"));
}
}
我知道新操作会覆盖之前的操作。所以如果我点击按钮,它只会打印additional action。
public class Main extends Application{
public static void main(String[] args) {
launch();
}
@Override
public void start(Stage primaryStage) throws Exception {
Cell cell = new Cell();
Button button = cell.getButton();
Game game = new Game(button);
VBox vBox = new VBox(button);
Scene scene = new Scene(vBox);
primaryStage.setScene(scene);
primaryStage.show();
}
}
是否可以向按钮添加新动作并保留以前的动作?
【问题讨论】:
-
想要达到什么目的?如果你想要两个动作,为什么不在一个动作中写呢??