2014-09-21 16 views
1

我正在使用scenebuilder製作UI。我想在按下鼠標或按下按鈕時改變按鈕的顏色。我是否可以爲鼠標按下和觸摸屏事件設置相同的方法,併爲多個按鈕設置相同的事件?就像有3個按鈕,我想在鼠標按下和屏幕觸摸的事件中改變它們的顏色,並且只使用一種方法。 謝謝使用相同的方法爲鼠標按下和觸摸按下事件的多個按鈕

回答

1

比方說,你有三個按鈕

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 pressedscreen 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"); 
}