1
我正在使用scenebuilder制作UI。我想在按下鼠标或按下按钮时改变按钮的颜色。我是否可以为鼠标按下和触摸屏事件设置相同的方法,并为多个按钮设置相同的事件?就像有3个按钮,我想在鼠标按下和屏幕触摸的事件中改变它们的颜色,并且只使用一种方法。 谢谢使用相同的方法为鼠标按下和触摸按下事件的多个按钮
我正在使用scenebuilder制作UI。我想在按下鼠标或按下按钮时改变按钮的颜色。我是否可以为鼠标按下和触摸屏事件设置相同的方法,并为多个按钮设置相同的事件?就像有3个按钮,我想在鼠标按下和屏幕触摸的事件中改变它们的颜色,并且只使用一种方法。 谢谢使用相同的方法为鼠标按下和触摸按下事件的多个按钮
比方说,你有三个按钮
Button button1 = new Button();
Button button2 = new Button();
Button button3 = new Button();
创建一个方法说
private void handleButtonAction(ActionEvent event) {
// Button was clicked, change color
((Button)event.getTarget).setStyle("-fx-background-color:PINK");
}
所有按钮都被两个mouse pressed
和screen touched events
开了setOnAction()
。
的JavaDoc说
按钮的动作,每当按钮被触发时被调用。 这可能是由于用户用鼠标单击按钮或 通过触摸事件或按键,或者开发人员以编程方式调用fire()方法。
使用它:
button1.setOnAction(this::handleButtonAction);
button2.setOnAction(this::handleButtonAction);
button3.setOnAction(this::handleButtonAction);
如果您正在使用FXML
您可以定义一个动作为所有的按钮:
<Button id="button1" onAction="#handleButtonAction"/>
<Button id="button2" onAction="#handleButtonAction"/>
<Button id="button3" onAction="#handleButtonAction"/>
控制器内部:
@FXML
private void handleButtonAction(ActionEvent event) {
// Button was clicked, change color
((Button)event.getTarget).setStyle("-fx-background-color:PINK");
}