JavaFX中getText方法失效问题求助
Hey Jonas, let's dig into why your btnLogin.getText() call isn't returning the expected button text. I've looked at your code, and here are the most likely issues and fixes:
First, Check FXML Controller Binding
The #1 reason for failed control injection (and thus null references) is missing or incorrect controller mapping in your FXML file.
Make sure your FXML's root element includes the fx:controller attribute pointing to your MainController's full package path. For example:
<!-- Replace "com.yourpackage" with your actual package name --> <AnchorPane xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="com.yourpackage.MainController"> <!-- Your Button, PasswordField, etc. go here --> <Button id="btnLogin" alignment="CENTER" layoutX="18.0" layoutY="143.0" mnemonicParsing="false" onAction="#login" prefHeight="27.0" prefWidth="165.0" text="Anmelden" /> </AnchorPane>
Without this attribute, the FXMLLoader has no idea which controller to inject your button into, leaving btnLogin as null (calling getText() on a null reference would either throw an exception or return nothing).
Verify FXML Loading Logic
Ensure you're loading the FXML correctly in your main application class—don't manually instantiate the controller. Let the FXMLLoader handle it:
public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ FXMLLoader loader = new FXMLLoader(getClass().getResource("main.fxml")); Parent root = loader.load(); // Don't do this: MainController controller = new MainController(); primaryStage.setTitle("Login"); primaryStage.setScene(new Scene(root)); primaryStage.show(); } }
If you create the controller manually, the @FXML annotations won't trigger injection.
Double-Check Naming Consistency
While your code looks correct here, confirm:
- The controller variable
btnLoginmatches the FXML button'sidattribute exactly (JavaFX is case-sensitive) - If you used Scene Builder, you set the button's
fx:idtobtnLogin(not just theidfield—though they often align)
Debug the Injection Status
Add a quick check in your login() method to confirm if the button is actually injected:
@FXML public void login() { System.out.println("login"); System.out.println("Button reference: " + btnLogin); // Will print null if injection failed if (btnLogin != null) { System.out.println(btnLogin.getText()); } else { System.out.println("Error: btnLogin is null - injection failed!"); } }
If this prints null, circle back to the controller binding and FXML loading steps above.
内容的提问来源于stack exchange,提问作者Jonas

