如何通过单击按钮关闭 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屋!