[英]Java FXML GridPane.getRowIndex(source) returning null always when handling mouse event in Scene Builder
我是 Java FXML 的新手。 我仍在學習如何使用 Scene Builder 2.0 和 controller 類。 我不明白為什么要返回 null
@FXML
public void gridClick(MouseEvent e){
Node source = (Node)e.getSource() ;
Integer colIndex = grid.getColumnIndex(source);
Integer rowIndex = grid.getRowIndex(source);
System.out.println("Mouse entered cell ["+colIndex+","+rowIndex+"]");
}
我在 SceneBuilder 中啟動了所有網格單元網格窗格已在 SceneBuilder 中創建然后我在 controller class 初始化中為每個單元格創建了錨窗格:
for(int row=0;row<numRows;row++){
for(int col=0;col<numCols;col++){
AnchorPane slot=new AnchorPane();
slot.setStyle("-fx-border-color: black;-fx-border-width: 0.2;");
grid.add(slot,col,row);
}
}
我不知道這是否是一種糟糕的方法,但我正在努力學習。 請幫助我如何以不同的方式執行此操作,或者為什么它會給我 null 值。 當用戶單擊其中一個網格單元格時,即它們應該是錨窗格,我想要他們單擊的錨窗格或網格單元格行和列。
我不知道這是否是個問題,但在尋找答案時我遇到了這個話題,所以我會回答它以防有人需要答案。 首先,問題在於使用命令訪問節點本身: Integer colIndex = grid.getColumnIndex(source);
. 命令 getColumnIndex 是 static,所以你必須直接訪問類型: GridPane.getColumnIndex(source);
其次,您正在嘗試檢索網格窗格內沒有任何內容的網格窗格的坐標,這不起作用,因為沒有子項的網格窗格單元格,這意味着節點類型,是 null。網格窗格交叉點內必須有一個節點,比方說 ImageView,這意味着所有節點都必須轉換為 ImageView 類型節點:
for(Node i: grid.getChildren){ImageView iv = (ImageView)i;
現在您可以檢索索引:
int colIndex = GridPane.getColumnIndex(iv);}
基本上,這意味着該方法必須知道它正在檢索其索引的節點的類型。
最后,小心 fxml,因為,例如,如果您將 ImageView 或按鈕拖放到 SceneBuilder 中的網格窗格,如果網格窗格單元格的行或列索引為 0,則 fxml 將采用默認值,即零,並且它不會顯式賦值:
<example>
<ImageView fx:id="IvTarget_0_0" fitHeight="55.0" fitWidth="58.0" onDragDropped="#handleImageDrop" pickOnBounds="true" preserveRatio="true">
<GridPane.margin>
<Insets left="12.0" />
</GridPane.margin>
</ImageView>
</example>
因此您會在 fxml 編輯器中看到坐標為 0,0 的節點沒有設置GridPane.columnIndex
或GridPane.rowIndex
值。 這對於其他功能來說是可以的,但是當涉及到檢索索引時,它會拋出 nullPtr 異常,即使多個子項中只有一個沒有設置這些屬性。 在這種情況下,您必須在 fxml 編輯器中查看所有節點並手動設置它們。
<example>
<ImageView fx:id="IvTarget_0_0" GridPane.columnIndex="0" GridPane.rowIndex="0" fitHeight="55.0" fitWidth="58.0" onDragDropped="#handleImageDrop" pickOnBounds="true" preserveRatio="true">
<GridPane.margin>
<Insets left="12.0" />
</GridPane.margin>
</ImageView>
</example>
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.