0

I want to get GridPane's index when I act MouseClickEvent. I made clickevent on AnchorPane in GridPane. I succeed to change mainmenu.fxml to koreanfood.fxml on click. But I want to get GridPane's index because I want to do Same thing on one .fxml when i click on another AnchorPane in GridPane.

I tried this method and this method and this method

But getRowIndex()and getColumnIndex() always returned null

Main.java:

package application;

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) {
        try {
            Parent root=FXMLLoader.load(getClass().getResource("mainmenu.fxml"));
            primaryStage.setScene(new Scene(root));         
            primaryStage.setTitle("recipe");
            primaryStage.show();
//          primaryStage.setResizable(false);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Controller.java:

package application;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class Controller {
    @FXML
    private Label food;
    @FXML
    private void clickmainmenu(MouseEvent event) {

        try {
            Parent koreanfood = FXMLLoader.load(getClass().getResource("koreanfood.fxml"));
            Scene scene = new Scene(koreanfood);
            Stage primaryStage = (Stage)((Node) event.getSource()).getScene().getWindow();

            Integer row = GridPane.getRowIndex((Node)event.getSource() );
            int column=GridPane.getColumnIndex((Node)event.getSource() );
            System.out.println("r : "+row+"c : "+column);
            if(row==0) {
                switch(column) {
                case 0:
                    food.setText("한식");
                    break;
                case 1:
                    food.setText("중식");
                    break;
                case 2:
                    food.setText("일식");
                    break;
                case 3:
                    food.setText("양식");
                    break;      
                }
            }
            else if(row==1) {
                switch(column) {
                case 0:
                    food.setText("분식");
                    break;
                case 1:
                    food.setText("야식");
                    break;
                case 2:
                    food.setText("랜덤");
                    break;
                case 3:
                    food.setText("ㅋ");
                    break;      
                }
            }           

            primaryStage.setScene(scene);
            primaryStage.setTitle("recipe");
        } catch(Exception e) {
            e.printStackTrace();
        }

    }
    @FXML
    private void clickfoodmenu(MouseEvent event) {
        try {
            Parent cookingrecipe = FXMLLoader.load(getClass().getResource("cookingrecipe.fxml"));
            Scene scene = new Scene(cookingrecipe);

            Stage primaryStage = (Stage)((Node) event.getSource()).getScene().getWindow();

            primaryStage.setScene(scene);
            primaryStage.setTitle("recipe");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    @FXML
    private void clickBackMain(MouseEvent event) {
        try {
            Parent koreanfood = FXMLLoader.load(getClass().getResource("mainmenu.fxml"));
            Scene scene = new Scene(koreanfood);

            Stage primaryStage = (Stage)((Node) event.getSource()).getScene().getWindow();

            primaryStage.setScene(scene);
            primaryStage.setTitle("recipe");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    @FXML
    private void clickBackKor(MouseEvent event) {
        try {
            Parent mainmenu = FXMLLoader.load(getClass().getResource("koreanfood.fxml"));
            Scene scene = new Scene(mainmenu);

            Stage primaryStage = (Stage)((Node) event.getSource()).getScene().getWindow();

            primaryStage.setScene(scene);
            primaryStage.setTitle("recipe");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

mainmenu.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="600.0" prefWidth="800.0" style="-fx-background-color: yellow;" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Controller">
   <children>
      <GridPane hgap="30.0" layoutX="70.0" layoutY="200.0" prefHeight="320.0" prefWidth="682.0" vgap="30.0">
        <columnConstraints>
            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
          <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 onMouseClicked="#clickmainmenu" prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: white;">
               <children>
                  <ImageView fitHeight="101.0" fitWidth="103.0" layoutX="27.0" layoutY="7.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@../../../resources/iconfinder_Food_C226_2427886.png" />
                     </image></ImageView>
                  <Label layoutX="54.0" layoutY="119.0" text="한식">
                     <font>
                        <Font size="21.0" />
                     </font></Label>
               </children>
            </AnchorPane>
            <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
               <children>
                  <Button layoutY="1.0" mnemonicParsing="false" onMouseClicked="#clickmainmenu" prefHeight="123.0" prefWidth="119.0" style="-fx-background-color: white;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                  <ImageView fitHeight="114.0" fitWidth="116.0" layoutX="14.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@../../../resources/dim-sum.png" />
                     </image>
                  </ImageView>
                  <Label layoutX="54.0" layoutY="119.0" text="중식">
                     <font>
                        <Font size="21.0" />
                     </font>
                  </Label>
               </children>
            </AnchorPane>
            <AnchorPane prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: white;" GridPane.columnIndex="2">
               <children>
                  <Label layoutX="51.0" layoutY="121.0" text="일식">
                     <font>
                        <Font size="21.0" />
                     </font>
                  </Label>
                  <ImageView fitHeight="128.0" fitWidth="122.0" layoutX="13.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@../../../resources/iconfinder_Food_C212_2427856.png" />
                     </image>
                  </ImageView>
               </children>
            </AnchorPane>
            <AnchorPane prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: white;" GridPane.columnIndex="3">
               <children>
                  <ImageView fitHeight="114.0" fitWidth="114.0" layoutX="17.0" pickOnBounds="true" preserveRatio="true" />
                  <Label layoutX="51.0" layoutY="121.0" text="양식">
                     <font>
                        <Font size="21.0" />
                     </font>
                  </Label>
               </children></AnchorPane>
            <AnchorPane prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: white;" GridPane.rowIndex="1">
               <children>
                  <ImageView fitHeight="114.0" fitWidth="114.0" layoutX="17.0" pickOnBounds="true" preserveRatio="true" />
                  <Label layoutX="51.0" layoutY="114.0" text="분식">
                     <font>
                        <Font size="21.0" />
                     </font>
                  </Label>
               </children></AnchorPane>
            <AnchorPane prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: white;" GridPane.columnIndex="1" GridPane.rowIndex="1">
               <children>
                  <ImageView fitHeight="114.0" fitWidth="114.0" layoutX="21.0" pickOnBounds="true" preserveRatio="true" />
                  <Label layoutX="51.0" layoutY="114.0" text="야식">
                     <font>
                        <Font size="21.0" />
                     </font>
                  </Label>
               </children></AnchorPane>
            <AnchorPane prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: white;" GridPane.columnIndex="2" GridPane.rowIndex="1">
               <children>
                  <ImageView fitHeight="114.0" fitWidth="114.0" layoutX="17.0" pickOnBounds="true" preserveRatio="true" />
                  <Label layoutX="51.0" layoutY="114.0" text="랜덤">
                     <font>
                        <Font size="21.0" />
                     </font>
                  </Label>
               </children></AnchorPane>
            <AnchorPane prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: white;" GridPane.columnIndex="3" GridPane.rowIndex="1">
               <children>
                  <ImageView fitHeight="114.0" fitWidth="130.0" layoutX="11.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@../../../resources/food.png" />
                     </image></ImageView>
                  <Label layoutX="10.0" layoutY="119.0" text="너만의 레시피">
                     <font>
                        <Font size="21.0" />
                     </font>
                  </Label>
               </children></AnchorPane>
         </children>
      </GridPane>
      <Label layoutX="300.0" layoutY="47.0" prefHeight="94.0" prefWidth="220.0" text="뭐먹어">
         <font>
            <Font size="72.0" />
         </font>
      </Label>
   </children>
</AnchorPane>

koreanfood.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.image.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="600.0" prefWidth="800.0" style="-fx-background-color: yellow;" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Controller">
   <children>
      <Label fx:id="food" layoutX="327.0" layoutY="14.0" prefHeight="99.0" prefWidth="146.0">
         <font>
            <Font size="70.0" />
         </font>
      </Label>
      <GridPane hgap="20.0" layoutX="61.0" layoutY="121.0" prefHeight="448.0" prefWidth="678.0" vgap="20.0">
        <columnConstraints>
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            <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 minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <children>
            <AnchorPane onMouseClicked="#clickfoodmenu" prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: white;">
               <children>
                  <ImageView fitHeight="99.0" fitWidth="121.0" layoutX="17.0" layoutY="14.0" pickOnBounds="true" preserveRatio="true" />
                  <Label layoutX="54.0" layoutY="104.0" prefHeight="29.0" prefWidth="58.0" text="111" />
               </children>
            </AnchorPane>
            <AnchorPane prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: white;" GridPane.rowIndex="1" />
            <AnchorPane prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: white;" GridPane.rowIndex="2" />
            <AnchorPane prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: white;" GridPane.columnIndex="1" />
         </children>
      </GridPane>
      <ImageView fitHeight="72.0" fitWidth="132.0" layoutX="32.0" layoutY="24.0" onMouseClicked="#clickBackMain" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../../../resources/reply%20(2).png" />
         </image>
      </ImageView>
   </children>
</AnchorPane>

error:

java.lang.NullPointerException
    at application.Controller.clickmainmenu(Controller.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.reflect.misc.Trampoline.invoke(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3470)
    at javafx.scene.Scene$ClickGenerator.access$8100(Scene.java:3398)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3766)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Unknown Source)

What should I do? Can anybody help me??

Yuheon
  • 3
  • 3
  • What is line 25 of your `Controller.java`? – Zephyr Nov 24 '18 at 15:01
  • That is "int column=GridPane.getColumnIndex((Node)event.getSource() );" But at Line 24 "Integer row = GridPane.getRowIndex((Node)event.getSource() );" row was also null when I print row. – Yuheon Nov 24 '18 at 15:44

1 Answers1

1

The rowIndex/columnIndex is null unless you initialize this property. It's not necessary to specify those properties, since GridPane treats them as 0 by default.

Also note that MouseEvent.source contains the node the event handler is added to, so

  • The first node you add the event handler to is located at cell (0, 0) and to reduce the fxml size SceneBuilder does not specify the values, since the effect is on the layout is the same resulting in the values being null.
  • The second node you add the event handler to is not a child of the GridPane, but a child of the child of the GridPane and for this reason has neither rowIndex nor columnIndex specified. (In addition for Buttons it would be better to use the onAction event; this is a ActionEvent though.)

You could nonetheless deal with these issues by

  1. Going up through the scene structure until a child of the GridPane is found.
  2. Treating null as 0
private static int toIndex(Integer value) {
    return value == null ? 0 : value;
}
@FXML
private GridPane grid;
<GridPane fx:id="grid" hgap="30.0" layoutX="70.0" layoutY="200.0" prefHeight="320.0" prefWidth="682.0" vgap="30.0">
Node node = (Node) event.getSource();
Parent p = node.getParent();

while (p != grid) {
    node = p;
    p = p.getParent();
}

int row = toIndex(GridPane.getRowIndex(node));
int column = toIndex(GridPane.getColumnIndex(node));
fabian
  • 80,457
  • 12
  • 86
  • 114
  • I tried it then I succeed. If you had not been, I would have had a hard time. I solved your problem thanks to you. But I did not understand the explanation for the first node. And there was a problem in the sentence below. n the sentence "food.setText (" Korean ");" error was occurred. error : "java.lang.NullPointerException at application.Controller.clickmainmenu (Controller.java:44) " – Yuheon Nov 24 '18 at 16:56