是否可以在具有Stackpane的类外部隐藏或关闭JavaFx中具有Stackpane的场景?如果没有,我该怎么办?例如,当我单击“窗口2”按钮时,我想隐藏或关闭window1并显示window2。谢谢。
package application;
import javafx.application.Application;
import javafx.stage.Stage;
import view.StackP;
import javafx.scene.Scene;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
StackP root = new StackP();
Scene scene = new Scene(root,1280,720);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
StackPane类:
package view;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
public class StackP extends BorderPane{
private Button btnMenu1;
private Window1 win1;
private Window2 win2;
private StackPane stack;
public StackP() {
this.setCenter(getStack());
hideAll();
this.getWin1().setVisible(true);
}
public void hideAll() {
for(Node child:getStack().getChildren()) {
child.setVisible(false);
}
}
public Button getBtnMenu1() {
if(btnMenu1==null) {
btnMenu1=new Button("Menu 1");
btnMenu1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
hideAll();
getWin1().setVisible(true);
}
});
}
return btnMenu1;
}
public Window1 getWin1() {
if(win1==null) {
win1=new Window1();
}
return win1;
}
public Window2 getWin2() {
if(win2==null) {
win2=new Window2();
}
return win2;
}
public StackPane getStack() {
if(stack==null) {
stack=new StackPane();
stack.getChildren().addAll(getWin1(),getWin2());
}
return stack;
}
}
window1类:
package view;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
public class Window1 extends GridPane{
private Label lbl1;
private Button win2;
public Window1() {
this.setPadding(new Insets(10,10,10,10));
this.setGridLinesVisible(true);
this.add(getWin2(), 1, 0);
this.add(getLbl1(), 3, 1);
}
public Label getLbl1() {
if(lbl1==null) {
lbl1=new Label("A label");
}
return lbl1;
}
public Button getWin2() {
if(win2==null) {
win2=new Button("Window 2");
}
return win2;
}
}
window2类:
package view;
import javafx.geometry.Insets;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
public class Window2 extends GridPane{
private TextField txt1;
public Window2() {
this.setPadding(new Insets(10,10,10,10));
this.setGridLinesVisible(true);
this.add(getTxt1(), 3, 1);
}
public TextField getTxt1() {
if(txt1==null) {
txt1=new TextField();
}
return txt1;
}
}