我有一个2×2 GridPane
,每列上都有一个AnchorPane
,我想知道用户使用MouseEvent
点击了网格的哪一列,但我得到的列和行索引
对于每个AnchorPane
是:null
,完整的项目:
完整的FXML代码:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.141" fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml/1">
<children>
<GridPane gridLinesVisible="true" onMouseClicked="#mouseclicked" prefHeight="400.0" prefWidth="600.0">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
<children>
<AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="0" GridPane.rowIndex="0" />
<AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1" GridPane.rowIndex="0"/>
<AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="0" GridPane.rowIndex="1" />
<AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1" GridPane.rowIndex="1" />
</children>
</GridPane>
</children>
</AnchorPane>
FXML控制器:
package sample;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
public class Controller {
@FXML
public void mouseclicked(MouseEvent ev){
Node source = (Node)ev.getSource() ;
Integer col = GridPane.getColumnIndex(source);
Integer row = GridPane.getRowIndex(source);
System.out.println("Column : "+col);
System.out.println("Row : "+row);
}
}
主要班级:
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我发现了什么是错误的,MouseEvent
不应该通过点击GridPane
本身来触发,而是通过点击列
来触发,所以发生的事情是它试图获取网格的索引
而不是列(即使用户点击了列),所以解决方案是网格不应该有任何类型的事件,但是列有!