如何通过单击按钮关闭Java窗口 - JavaFX项目 [英] How to close a java window with a button click - JavaFX Project
问题描述
我创建了一个JavaFX项目,并为java Scene Builder中的第一个登录框架创建了GUI。登录成功后,必须关闭登录框,并且必须显示下一帧(主程序框)。我可以让新框架出现,但我无法关闭登录框架。我试过像 dispose()
之类的东西,但没有任何作用。下面是主类的代码:
I made a JavaFX project and created the GUI for the first-login frame in the java Scene Builder. When the login is successful, the login frame must be closed and the next frame must be visible (main program frame). I can make the new frame appear, but I can't make the login frame closed. I tried stuff like dispose()
but nothing works. Below is the code for the main class:
public class KuberComm extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setResizable(false);
stage.setTitle("Login to KuberComm");
stage.setScene(scene);
stage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
登录按钮的处理程序是位于另一个类(NetBeans IDE生成的控制器类)中。我无法弄清楚框架的名称是什么,以便在控制器类中使用它。
The handler for the login button is located in another class (controller class made by the NetBeans IDE). I can't figure out what the frame's name is in order to use it in the controller class.
任何帮助将不胜感激!
推荐答案
在控制器类中为您的按钮命名:
give your button a name in the controller class:
@FXML
public Button closeButton;
并添加此方法:
@FXML
public void handleCloseButtonAction(ActionEvent event) {
Stage stage = (Stage) closeButton.getScene().getWindow();
stage.close();
}
在FXML中,您需要引用按钮名称和方法来调用onAction:
In your FXML you need a reference to the button name and the method to call onAction:
<Button fx:id="closeButton" cancelButton="true" layoutX="350.0" layoutY="767.0" mnemonicParsing="false" onAction="#handleCloseButtonAction" prefWidth="100.0" text="Close" />
这将关闭此按钮所在的阶段。
This would close the stage that this button is on.
这篇关于如何通过单击按钮关闭Java窗口 - JavaFX项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!