我正在练习一个小的聊天框窗口,因此我尝试这样做,因此用户必须在文本字段框中输入一个名称(用户名),但是我遇到了问题,我相信这将不是第一次。每次尝试使用其中一个变量时,我都会不断得到nullpointerexception,目前,它是文本字段。因此,我对其进行了初始化,但是即使输入用户名,它也始终为空字符串。

app.java

public class app extends Application {

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("FXMLApp.fxml"));

    Scene scene = new Scene(root);

    stage.setScene(scene);
    stage.show();
}

public static void main(String[] args) {
    launch();
}

}


FXMLApp.fxml(删除了不需要的内容)

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" maxHeight="900.0" maxWidth="800.0" minHeight="300.0" minWidth="200.0" prefHeight="600.0" prefWidth="500.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="chatappclient.FXMLChatAppClientController">
    <children>
      <TextField fx:id="username" layoutX="176.0" layoutY="488.0" promptText="enter username" />
      <Button fx:id="login" layoutX="176.0" layoutY="519.0" mnemonicParsing="false" onAction="#login" text="Login" />
    </children>
</AnchorPane>


如您所见,登录按钮调用

onAction="#login"


最后一个文件:FXMLAppController

    package chatappclient;

    import java.net.URL;
    import java.util.ResourceBundle;
    import javafx.application.Platform;
    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.control.TextArea;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.Pane;
    import javax.swing.JOptionPane;

    public class FXMLAppController implements Initializable
    {
        @FXML
        private Pane top_container;
        private Pane bottom_container;
        private TextField username ;
        private String name;
        private Button login;

        public FXMLChatAppClientController ()
        {
           // without this, I get nullpointerexception
            // with it, the textfield is always null
            username = new TextField();
        }

        @Override
        public void initialize(URL url, ResourceBundle rb)
        {}


        @FXML
        private void login()
        {
            // this returns empty string, if I did not initialize it, it would be an exception
            System.out.println("DEBUG: " + username.getText());
        }
    }

最佳答案

您需要使用@FXML注释FXML文件中定义的每个字段:

private Pane top_container;
private Pane bottom_container;
@FXML
private TextField username ;
private String name;
@FXML
private Button login;

10-04 12:22