JavaFX场景构建器下如何在Controller中实现按钮点击弹出新窗口
How to Create a Popup Window in JavaFX Controller Class
Hey there! I see you're trying to launch a popup window from your Controller instead of the Main class, and your current code isn't working because of misconfigured FXMLLoader settings. Let's fix this step by step.
The Problem with Your Current Code
You’re setting loader.setRoot(this) and loader.setController(this), which tells the FXMLLoader to use your main controller as both the root node and controller for the popup. That’s not right—your popup should be a separate, independent UI component with its own structure.
Corrected Controller Code
Here’s the proper way to load and display your Popup.fxml from the Controller:
import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.Node; import javafx.stage.Stage; import javafx.event.ActionEvent; import java.io.IOException; // ... rest of your Controller class code ... @FXML private void onButtonClicked(ActionEvent ae) { try { // Load the Popup.fxml file (double-check the path matches your project structure) FXMLLoader loader = new FXMLLoader(getClass().getResource("Popup.fxml")); Parent popupRoot = loader.load(); // Create a new Stage for the popup window Stage popupStage = new Stage(); popupStage.setTitle("My Popup"); // Set your preferred window title popupStage.setScene(new Scene(popupRoot)); // Optional (but recommended): Attach the popup to the main window // This makes the popup stay on top of the main window and minimize alongside it popupStage.initOwner(((Node) ae.getSource()).getScene().getWindow()); // Show the popup window popupStage.show(); } catch (IOException e) { e.printStackTrace(); } }
Key Details to Keep in Mind:
- Remove
setRootandsetController: Unless your popup intentionally shares the same controller as the main interface (which it shouldn’t), let FXMLLoader handle the controller automatically. If your popup needs its own logic, add afx:controllerattribute toPopup.fxmlpointing to its dedicated controller class:<!-- Inside Popup.fxml --> <AnchorPane fx:controller="your.package.name.PopupController" ...> <!-- Your popup UI elements go here --> </AnchorPane> - Path Validation: Make sure
Popup.fxmlis in the same package as your Controller class, or adjust the resource path to an absolute one (e.g.,"/com/yourproject/Popup.fxml") if it’s in a different location. initOwner: This optional setting ties the popup to the main window, creating a more intuitive user experience by keeping the popup linked to its parent window.
That should get your popup working smoothly from the Controller class!
内容的提问来源于stack exchange,提问作者Jino
相关产品推荐
相关产品推荐

