我把网格设置得很好。但是如何在每个单元格中放置事件处理程序?像鼠标双击并右键单击。 有人可以举个例子吗?谢谢!
答案 0 :(得分:0)
您没有完全指定您想要的内容,但我希望这些示例可以帮助您
第一个例子(我为所有节点添加相同的事件)
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package stackover;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
/**
*
* @author Ala_Eddine
*/
public class FXMLDocumentController implements Initializable {
@FXML
private Label label;
@FXML
private GridPane gridPane;
@FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
label.setText("Hello World!");
}
@Override
public void initialize(URL url, ResourceBundle rb) {
addGridEvent();
}
private void addGridEvent() {
gridPane.getChildren().forEach(item -> {
item.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getClickCount() == 2) {
System.out.println("doubleClick");
}
if (event.isPrimaryButtonDown()) {
System.out.println("PrimaryKey event");
}
}
});
});
}
**}
第二个例子**
private void addGridEvent() {
Button button = new Button("hi");
//You can use OnAction
button.addEventHandler(EventType.ROOT, (event) -> {
if (event.getEventType() == ActionEvent.ACTION) {
System.out.println("ActionEvent");
}
});
gridPane.getChildren().add(button);