Can you write two different Java FX scenes as two separate classes?

半世苍凉 提交于 2019-12-23 12:55:51

问题


I'm a beginning Java programmer, finishing up the "Java 101" class at my local university. I'm also pushing myself to learn some extra topics on the side, including Java FX. I've worked through the Java FX tutorials on Oracle's website, plus sat through some YouTube videos, plus read "Java FX for Dummies" (which was the best book I could find for a beginner.) All of this material has taught me a lot of the basics, but some stuff that (should be) relatively simple escapes me.

For example: Let's say I have a Java FX program that uses multiple scenes on one stage. When the user clicks a "Switch!" button, the second scene is swapped out for the first. Easy. I can do all of this in one .java file, no problem. (See code below)

But my .java class file is getting really long and cumbersome to troubleshoot. It would be great if I could define/declare/initialize one scene as one class in one .java file and the second scene as another class in another .java file. This would make keeping track of the components of each scene much, much easier. The problem is, I can't figure out how to do this.

I'd imagine that you would write a Scene1.java class and then a Scene2.java class, and simply pass the stage object between the two when you want to switch scenes. But I can't find an example of how this is done, and all my attempts result in compiler errors or really scary runtime errors.

Does anyone know how this can be done? If so, what would I have to do to modify the SwitchScenes2() method below to create the new Scene2 object and pass it the stage?

Thanks! RAO

/*
    JavaFXExample.java
*/

import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.event.*;
import javafx.geometry.*;

public class JavaFXExample extends Application{

    public static void main(String[] args){
    launch(args);   
}

Button btnSw1;
Button btnSw2;
Button btnClose;
HBox hbox1;
VBox vbox1;
Scene scene1;
Scene scene2;
Stage stage;

@Override public void start(Stage primaryStage){
    btnSw1 = new Button("Switch Scenes!");
    btnSw1.setOnAction(
        e -> SwitchScenes2() );
    btnSw2 = new Button("Switch back!");
    btnSw2.setOnAction(
        e -> SwitchScenes1() );
    btnClose = new Button();
    btnClose.setText("Close me!");
    btnClose.setOnAction(e -> CloseWindowClick());

    hbox1 = new HBox(10);
    hbox1.getChildren().addAll(btnSw1);
    vbox1 = new VBox(10);
    vbox1.getChildren().addAll(btnSw2, btnClose);

    scene1 = new Scene(hbox1, 300, 300);
    scene2 = new Scene(vbox1, 200, 400);

    stage = primaryStage;
    stage.setScene(scene1);
    stage.setTitle("Example App");
    stage.show();
   }

    public void SwitchScenes1(){
        stage.setScene(scene1);
    }
    public void SwitchScenes2(){
        stage.setScene(scene2);
    }
    public void CloseWindowClick(){
        stage.close();
    }
}

回答1:


Pete as I understand you wish to separate one big java file into small files,create Java classes in each class create method(function) that will return layout(HBox,VBox, Flowpane or ....)then in your main create an object of that Java class and use those methods to build on big application.

in my sample I made one main and one separated class with one function,just to show you how its works. In my main there is 2 lables, 2 buttons one layout and one object of the separated class, by clicking the buttons scenes will change My Main:

public class SwitchSceneSample extends Application {
public static void main(String[] args) {
    launch(args);
}

Stage window;
Scene scene1, scene2;

@Override
public void start(Stage primaryStage) throws Exception {
    // I am using window as primaryStage
    window = primaryStage;
    // Label 1
    Label label1 = new Label("Welcome to the first scene!");
    // Label 2
    Label label2 = new Label("This is second scene!");
    // Button 1, by pressing this button primaryStage will be set as scene 2
    Button button1 = new Button("Go to scene 2");
    button1.setOnAction(e -> window.setScene(scene2));
    // Button 2, by pressing this button primaryStage will be set as scene 1
    Button button2 = new Button("Click to go scene 1");
    button2.setOnAction(e -> window.setScene(scene1));
    // Creating an object of the class'LayoutOne.java'
    LayoutOne l1 = new LayoutOne();
    // set my scene 1(by calling method called 'sceneView1()' from class 'LayoutOne.java')
    scene1 = new Scene(l1.sceneView1(label1, button1), 200, 200);
    // Set my scene 2 inside my main class
    StackPane layout2 = new StackPane();
    layout2.getChildren().addAll(label2, button2);
    scene2 = new Scene(layout2, 600, 300);
    // Making my 
    window.setScene(scene1);
    window.setTitle("Scene Switch Sample");
    window.show();
}

}

My Second Class:

public class LayoutOne {
public VBox sceneView1(Label label, Button button) {

    // Layout 1 - children are laid out in vertical column
    VBox layout1 = new VBox(20);
    layout1.getChildren().addAll(label, button);

    return layout1;
}

}




回答2:


What you will want to do is create separate classes that both have functions to return the scene. From there you will want to initialize these classes and with a button call a function that will add data to these scene or create a new blank scene (as a quick way to "delete" the scene). But if you want a more professional way to switch between scenes like this you will want to check out the TabPane().

Scene1 scene1 = new Scene1();
Scene2 scene2 = new Scene2();

TabPane tabPane = new TabPane();
Tab tab1 = new Tab();
tab1.setContent(scene1);
tabPane.getTabs().add(tab1);
Tab tab2 = new Tab();
tab2.setContent(scene2);
tabPane.getTabs().add(tab2);



回答3:


  1. Create a Manager class that contain the main method & initialize the first screen. eg.

public class VMCSManager extends Application {

private Parent content;
private static VMCSManager instance;

public VMCSManager() {
    instance=this;
}

public static void main(String[] args) {    
    launch(args);
}

public static VMCSManager getInstance() {
    return instance;
}

@Override
public void start(Stage primaryStage) throws Exception {    
    initializePanel();  
    Scene scene = new Scene(content);
    stageStyle(primaryStage);
    primaryStage.setScene(scene);
    primaryStage.show();
}

private void initializePanel() throws IOException{
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(getClass().getResource("fxml/SimulatorDisplay.fxml"));
    content = loader.load(); 
}

public void openCustomerPanel() throws IOException{
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(getClass().getResource("fxml/CustomerDisplay.fxml"));
    content = loader.load(); 
    Scene scene = new Scene(content);
    primaryStage.setScene(scene);
    primaryStage.show();
}

}

  1. Create main controller class for the first screen. eg;

public class SimulatorController implements Initializable{

@FXML
public void clickCustomer (ActionEvent event) throws IOException{
    log.info("Starting Customer Panel");
    VMCSManager.getInstance().openCustomerPanel();
}
@FXML
public void clickMaintainer(ActionEvent event) throws IOException{
    log.info("Starting Maintainer Panel");
    VMCSManager.getInstance().openMaintainerPanel();
}

}

  1. Lastly Create the controller class for the specified screen. eg`

public class CustomerController extends SimulatorController{

@FXML
private Label brand1Lbl;
@FXML
private Label brand2Lbl;
@FXML
private Label brand3Lbl;
@FXML
private Label brand4Lbl;
@FXML
private Label brand5Lbl;

@FXML
private Label statusLbl1;
@FXML
private Label statusLbl2;

private static final Logger log=LoggerFactory.getLogger(CustomerController.class);

public CustomerController() {
    context= new BuyingStateContext();
}

public void initialize(URL location, ResourceBundle resources) {
     this.location = location;
     this.rb = resources;
     coinsValidityFlash.setVisible(false);
     insertCoinTxt.setDisable(true);

     brand1Btn.setStyle("-fx-background-color:  #CACACA;");
     brand2Btn.setStyle("-fx-background-color:  #CACACA;");
     brand3Btn.setStyle("-fx-background-color:  #CACACA;");
     brand4Btn.setStyle("-fx-background-color:  #CACACA;");
     brand5Btn.setStyle("-fx-background-color:  #CACACA;");

     populateVending();
}
.
.
.

}

`



来源:https://stackoverflow.com/questions/36551431/can-you-write-two-different-java-fx-scenes-as-two-separate-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!