I am using Java FX (required for a class project), and I am struggling to format my MVC so that I can load multiple views onto the stage (various scenes). I have a Controller as seen below that has 2 instances of View1.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.animation.AnimationTimer;
public class Controller extends Application {
public int page = 0;
private View1 view2;
private View1 view1;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage theStage) {
view1 = new View1(theStage);
view2 = new View1(theStage);
new AnimationTimer() {
public void handle(long currentNanoTime)
{
switch (page){
case 0:
view1.update();
break;
case 1:
view2.update();
break;
default:
page = 0;
}
try {
Thread.sleep(33);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
theStage.show();
}
}
The problem occurs at the line view2 = new View1(theStage);. Without this line, the output is a large canvas with a background image. With that line, however, there is no background image it is just a blank canvas. Below is my View I simplified it as much as possible, just one background image to determine if it's loaded correctly. (I left the imports out in order to keep it concise, if needed I can add them back in)
public class View1 {
Stage theStage;
Group root;
Scene theScene;
Canvas canvas;
// value of the height and width of screen
int canvasWidth = 1000;
int canvasHeight = 800;
GraphicsContext gc;
Image background;
//View1 constructor initialize the starting position for the image
//Called in controller
public View1(Stage theStage) {
this.theStage = theStage;
this.theStage.setTitle("Estuary Game");
root = new Group();
theScene = new Scene(root);
this.theStage.setScene(theScene);
canvas = new Canvas(canvasWidth, canvasHeight);
root.getChildren().add(canvas);
gc = canvas.getGraphicsContext2D();
background = createImage("assets/mini-game-1.png");
}
//Read image from file and return
private Image createImage(String image_file) {
Image img = new Image(image_file);
return img;
}
//method used to repaint on the image and called in controller
public void update() {
// draw background and sharkMove such like current
gc.drawImage(background, 0, 0);
}
}
I am not sure I am tackling the multiple views correctly, my intentions are to just have multiple scenes but I wasn't sure how to structure it.