I have the following files in my project:
- main.java for starting up the application
- RootLayout.fxml & RootlayoutController.java which serves as the main stage and will be used for a menu bar
- Overview.fxml and OverviewController.java for the main window of the application
- point.java which contains the application logic
The OverviewController's test()-method is triggered by a Button's onAction-Event. Essentially I am looking for a way to give the Point.java class access to the OverviewController.java class, so it can call the associated drawPoint(double x, double y) method.
I have been researching this question for quite a while now, but have been unable to find an understandable answer - since my knowledge of JavaFX is somewhat limited.
My sincere thanks for taking your time to answer my question.
Main.java
public class Main extends Application {
public Stage primaryStage;
private BorderPane rootLayout;
public Main(){
}
@Override
public void start(Stage primaryStage) throws Exception{
this.primaryStage = primaryStage;
this.primaryStage.setTitle("");
initRootLayout();
showOverview();
}
public void initRootLayout(){
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class
.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.setHeight(900);
primaryStage.setWidth(900);
// Give the controller access to the main app.
RootLayoutController controller = loader.getController();
controller.setMainApp(this);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void showOverview(){
try {
// Load Overview
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/Overview.fxml"));
AnchorPane overview = (AnchorPane) loader.load();
// Set overview into the center of root layout.
rootLayout.setCenter(overview);
// Give the controller access to the main app.
OverviewController controller = loader.getController();
controller.setMainApp(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
OverviewController.java
public class OverviewController {
private sample.Main Main;
public void setMainApp(Main mainApp) {
this.Main = mainApp;
}
@FXML
Canvas canvas;
public void test(){
Point point = new Point(5,5);
point.drawPoint();
}
public void draw(double x, double y){
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.rgb(255, 0, 0));
gc.fillOval(x-4, y-4, 8, 8);
}
}
Point.java
public class Point {
public double x;
public double y;
point(double x, double y){
this.x = x;
this.y = y;
}
drawPoint(){
// This is where I want to build a reference to OverviewController.java's draw(double x, double y)-Method
}
}