我正在使用Java FX(类项目是必需的),并且正在努力格式化MVC,以便可以将多个视图加载到舞台(各种场景)上。我有一个Controller,如下所示,其中有2个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();
}
}
问题发生在第view2 = new View1(theStage);
行。没有此行,输出是带有背景图像的大画布。但是,没有那条线,它只是空白画布。下面是我的视图,我尽可能地简化了它,只是一张背景图像,以确定它是否正确加载。 (为了简化起见,我省略了导入,如果需要,我可以将其重新添加)
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);
}
}
我不确定我是否正确处理了多个视图,我的意图是只包含多个场景,但不确定如何构造它。任何帮助将不胜感激。