【发布时间】:2016-07-18 19:42:13
【问题描述】:
我有两个场景,场景 1 上有一个标签,上面写着“这是场景 1”,它还有一个按钮,上面写着“按我去场景 2”。场景 2 与场景 1 类似,但场景 2 上的标签和文本则相反。
问题很简单,至少应该如此。我可以通过 javaFX 方式做到这一点,但似乎无法通过 FXML 方式做到这一点。
我有一个主课-
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class ManinApp extends Application
{
Stage primaryStage;
private AnchorPane rootLayout;
public static void main(String [] args)
{
launch(args);
}
public void start(Stage primaryStage)
{
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Two Scenes");
initRootLayout();
//showSecondScene();
}
public void initRootLayout()
{
try
{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(ManinApp.class.getResource("Scene1.fxml"));
rootLayout = (AnchorPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
/**
public void showSecondScene()
{
try
{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(ManinApp.class.getResource("Scene2.fxml"));
AnchorPane secondScene = (AnchorPane)loader.load();
rootLayout.getChildren().add(secondScene);
}
catch(IOException e)
{
e.printStackTrace();
}
}
*/
public Stage getPrimaryStage()
{
return primaryStage;
}
}
showSecondScene() 目前已被注释掉。我的理解是,您还需要一个 Controller 类来将代码连接到 SceneBuilder?
FX 方式的解决方案
btnscene1.setOnAction(e ->
{
if(e.getSource() == btnscene1)
thestage.setScene(scene2);
else
thestage.setScene(scene1);
});
btnscene2.setOnAction(e ->
{
if(e.getSource()==btnscene2)
thestage.setScene(scene1);
else
thestage.setScene(scene2);
});
为格式化道歉!
我如何能够使用控制器类来做到这一点,我可以从中使用我的主类中声明的主要阶段和两个场景?
我希望它有意义
【问题讨论】:
标签: javafx-8 scenebuilder