我试图将某个程序的某些部分分开,以便一切都井然有序。我希望我的Main.java包含需要加载的初始设置。然后它从MainStage.java启动app(加载舞台),MainStage.java又从另一个类(SceneOne.java,SceneTwo.Java等)加载一个场景。 SceneOne.java和其余部分包含要包含在场景中的所有对象(文本框,按钮,标签等)。可能会有一个不必要的"有一个MainStage.java,但我不确定。不过,我现在的目标是弄清楚如何从SceneOne.java加载场景。 这是我到目前为止所做的,我主要从一些教程网站获得。
Main.java
package ppmp.main;
import ppmp.ui.MainStage;
import javafx.application.*;
public class Main
{
public static void main(String args[])
{
System.out.println("Application Starting");
Application.launch(MainStage.class);
}
}
MainStage.java
package ppmp.ui;
import javafx.application.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
public class MainStage extends Application {
Button btnscene1, btnscene2;
Label lblscene1, lblscene2;
FlowPane pane1, pane2;
Scene scene1, scene2;
Stage thestage;
@Override
public void start(Stage primaryStage) {
thestage=primaryStage;
//can now use the stage in other methods
//make things to put on panes
btnscene1=new Button("Click to go to Other Scene");
btnscene2=new Button("Click to go back to First Scene");
btnscene1.setOnAction(e-> ButtonClicked(e));
btnscene2.setOnAction(e-> ButtonClicked(e));
lblscene1=new Label("Scene 1");
lblscene2=new Label("Scene 2");
//make 2 Panes
pane1=new FlowPane();
pane2=new FlowPane();
pane1.setVgap(10);
pane2.setVgap(10);
//set background color of each Pane
pane1.setStyle("-fx-background-color: tan;-fx-padding: 10px;");
pane2.setStyle("-fx-background-color: red;-fx-padding: 10px;");
//add everything to panes
pane1.getChildren().addAll(lblscene1, btnscene1);
pane2.getChildren().addAll(lblscene2, btnscene2);
//make 2 scenes from 2 panes
scene1 = new Scene(pane1, 200, 100);
scene2 = new Scene(pane2, 200, 100);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene1);
primaryStage.show();
}
public void ButtonClicked(ActionEvent e)
{
if (e.getSource()==btnscene1)
thestage.setScene(scene2);
else
thestage.setScene(scene1);
}
}
SceneOne.java
package ppmp.ui;
import javafx.application.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
public class SceneOne extends Scene {
public static class MyStackPane extends StackPane{
public MyStackPane() {
getChildren().add(new Label("Hello World"));
}
}
}
一个非常具体的问题是,我应该用什么替换scene1来加载primaryStage.setScene(scene1)中的SceneOne.java;?
编辑:我忘了提及,我知道场景的大部分代码都在MainStage.java中。我试图弄清楚如何将所有这些转移到SceneOne.java中。