【发布时间】:2019-11-07 20:17:12
【问题描述】:
我正在使用 Java FX(类项目需要),并且我正在努力格式化我的 MVC,以便我可以将多个视图加载到舞台上(各种场景)。我有一个控制器,如下所示,它有 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, 0);
}
}
我不确定我是否正确处理了多个视图,我的意图是只有多个场景,但我不确定如何构建它。
【问题讨论】:
标签: java javafx model-view-controller