0

I want to call the method getRow() inside Controller from the main method of class Main in JavaFX. I really have no idea how to use JavaFX so I don't even know if that's something you should do with Controller.

public class Controller {

    public Button button00 = new Button();

    public int getRow(){
        return GridPane.getRowIndex(button00);
    }
}

I'm making chess in JavaFX (GridPane with 64 buttons) but I already have made a chess as a normal Java project and so I want to somehow make it work with JavaFX. But my original code needs the position of the selected playing piece (which in there was entered from the console) so i tried to get the position of the button which is selected. However I need that position in my main method and I don't know how to get it.

  • No you should not be calling it in your main method, you should be calling it in a event in your controller. Can you describe what you are trying to do – SteelToe Apr 05 '18 at 20:37
  • 1
    1. You can't call it from the `main()` method; there is simply no way to get a reference to any controller instance there. 2. There is no need to: in fact, you simply *shouldn't* try to do this. Why not just call the method from `start()` (if you need to call it when the app starts up, for some reason)? – James_D Apr 05 '18 at 20:59
  • I'm making chess in JavaFX but I already have made a chess as a normal Java project and so I want to somehow make it work with JavaFX. But my original code needs the position of the selected playing piece so i tried to get the position of the button which is selected. However I need that position in my main method and I don't know how to get it. – TheWarInMyMind Apr 05 '18 at 21:28
  • Again, you can't get it in the main method. That method shouldn't be doing any real work anyway. – James_D Apr 05 '18 at 21:44
  • @James_D He does not want to get into the Main method rather access the Controller from the Main method instead – arxakoulini Apr 06 '18 at 10:38
  • @koulini I know. It says that in the question. As I stated earlier, there is no way to get access to any of the controller instances (plural, note) that will be created when FXML file(s) are loaded. – James_D Apr 06 '18 at 11:45
  • @James_D My answer's code does just that (unless I have misunderstood the problem). I am using this methodology in several JavaFX projects and it works great. Please add a comment explaining why, if you believe otherwise. – arxakoulini Apr 06 '18 at 11:48

1 Answers1

0

You can get Controller from FXMLLoader:

//loading scene fxml
FXMLLoader loader = new FXMLLoader(Main.class.getResource("your_path.fxml"));
Parent sceneFXML = loader.load();
//getting controller object
Controller ctrl = (Controller)(loader.getController());

Now you can access needed attributes or methods from ctrl.

ctrl.getRow();
Powercoder
  • 695
  • 1
  • 5
  • 25