我使用这种方法来改变场景JavaFX:
/**
* Controller class for menuFrame.fxml
*/
public class MenuFrameControl implements Initializable {
@FXML private Button sceneButton1;
@FXML private Button sceneButton2;
@FXML private Button sceneButton3;
/**
* Event handling method, loads new scene from .fxml file
* according to clicked button and initialize all components.
* @param event
* @throws IOException
*/
@FXML
private void handleMenuButtonAction (ActionEvent event) throws IOException {
Stage stage = null;
Parent myNewScene = null;
if (event.getSource() == sceneButton1){
stage = (Stage) sceneButton1.getScene().getWindow();
myNewScene = FXMLLoader.load(getClass().getResource("/mvc/view/scene1.fxml"));
} else if (event.getSource() == sceneButton2){
stage = (Stage) flightBtn.getScene().getWindow();
myNewScene = FXMLLoader.load(getClass().getResource("/mvc/view/scene2.fxml"));
} else if (event.getSource() == sceneButton3) {
stage=(Stage) staffBtn.getScene().getWindow();
myNewScene = FXMLLoader.load(getClass().getResource("/mvc/view/scene3.fxml"));
}
Scene scene = new Scene(myNewScene);
stage.setScene(scene);
stage.setTitle("My New Scene");
stage.show();
}
@Override
public void initialize(URL location, ResourceBundle resources) { }
Run Code Online (Sandbox Code Playgroud)
所以基本上当你点击按钮时,它会将实际显示的Stage对象保存到stage变量中。然后它将Scene.fxml 文件中的新对象加载到myNewScene变量中,然后将这个新加载的Scene对象放入您保存的Stage对象中。
使用此代码,您可以制作基本的三按钮菜单,其中每个按钮只需使用单个Stage对象即可切换到不同的场景。
| 归档时间: |
|
| 查看次数: |
11511 次 |
| 最近记录: |