我正在使用scenebuilder来创建UI。我想让按钮的颜色在鼠标被按下或按钮被触摸时改变。我可以为鼠标按下和屏幕触摸事件设置相同的方法,也可以为多个按钮设置相同的事件吗?就像有3个按钮,我想改变他们的颜色在鼠标按下和屏幕触摸事件,并只使用一种方法的所有。谢谢
发布于 2014-09-21 19:38:35
让我们说,你有三个按钮
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");
}所有按钮都有一个setOnAction(),它在mouse pressed和screen touched events上都被触发。
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");
}https://stackoverflow.com/questions/25958890
复制相似问题