【问题标题】:Can't read text from TextField input from DialogPane, JavaFX无法从 DialogPane、JavaFX 的 TextField 输入中读取文本
【发布时间】:2019-03-11 17:34:24
【问题描述】:

我正在尝试在 JavaFX 中创建一个简单的联系人应用程序。当我想创建新联系人时,它有一个带有 TableView 的主窗口和一个 DialogPane 打开。在 DialogPane 中有几个 TextField,我想从中收集文本以创建联系人列表。我的问题是,当我想从 DialogPane(来自 TextFields)读取输入时,该输入是具有单独控制器(与主控制器分开)的单独 fxml 文件,应用程序运行错误(java.lang.NullPointerException)。当我在我的主窗口 FXML 文件中放置一个 TextField 时,我可以从 textField 中访问这个文本就好了。当我想从 DialogPane 读取数据时,为什么会出现错误(错误-->文件:Controller.java,我注释了出现错误的部分)??我被困住了。谁能建议我做错了什么?这是我的代码:

Main.java

public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception{
    Parent root = FXMLLoader.load(getClass().getResource("mainwindow.fxml"));
    primaryStage.setTitle("Your Contacts");
    primaryStage.setScene(new Scene(root, 900, 600));
    primaryStage.show();
}


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

Controller.java

public class Controller {


@FXML
private BorderPane mainPanel;


public ObservableList<Contact> contactsList = FXCollections.observableArrayList();


@FXML
public void showAddContactDialog() {
    Dialog<ButtonType> dialog = new Dialog<>();
    dialog.initOwner(mainPanel.getScene().getWindow());
    dialog.setTitle("Add new contact");
    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(getClass().getResource("addContactDialog.fxml"));
    try {
       dialog.getDialogPane().setContent(fxmlLoader.load());
    } catch (IOException e) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("Error");
        alert.setHeaderText(null);
        alert.setContentText("Couldn't load the dialog");
        alert.showAndWait();
        e.printStackTrace();
        return;
    }

    dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
    dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);

    Optional<ButtonType> result = dialog.showAndWait();
    if(result.isPresent() && result.get() == ButtonType.OK) {

    //========================================================================================

        //here is the error, I cannot read values from addContactDialog controller

        ContactController contactController = new ContactController();

        String firstName = contactController.getNewContact().getFirstName();
        String lastName = contactController.getNewContact().getLastName();
        String phoneNumber = contactController.getNewContact().getPhoneNumber();
        String emailAddress = contactController.getNewContact().getEmailAddress();

        Contact newContact = new Contact(firstName, lastName, phoneNumber, emailAddress);
        contactsList.add(newContact);

        //or alternatively
        //            Contact newContact = contactController.getNewContact();
        //            contactsList.add(newContact);


    //========================================================================================
    }

}
}

ContactController.java

public class ContactController {


@FXML
private TextField firstNameField;

@FXML
private TextField lastNameField;

@FXML
private TextField phoneNumberFiled;

@FXML
private TextField emailField;


public Contact getNewContact() {

    String firstName = firstNameField.getText();
    String lastName = lastNameField.getText();
    String phoneNumber = phoneNumberFiled.getText();
    String emailAddress = emailField.getText();

    Contact newContact = new Contact(firstName, lastName, phoneNumber, emailAddress);
    return newContact;
}

Contact.java

public class Contact {

private SimpleStringProperty firstName = new SimpleStringProperty("");
private SimpleStringProperty lastName = new SimpleStringProperty("");
private SimpleStringProperty phoneNumber = new SimpleStringProperty("");
private SimpleStringProperty emailAddress = new SimpleStringProperty("");

public Contact() {
}

public Contact(String firstName, String lastName, String phoneNumber, String emailAddress) {
    this.firstName.set(firstName);
    this.lastName.set(lastName);
    this.phoneNumber.set(phoneNumber);
    this.emailAddress.set(emailAddress);
}



public String getFirstName() {
    return firstName.get();
}

public SimpleStringProperty firstNameProperty() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName.set(firstName);
}

public String getLastName() {
    return lastName.get();
}

public SimpleStringProperty lastNameProperty() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName.set(lastName);
}

public String getPhoneNumber() {
    return phoneNumber.get();
}

public SimpleStringProperty phoneNumberProperty() {
    return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber.set(phoneNumber);
}

public String getEmailAddress() {
    return emailAddress.get();
}

public SimpleStringProperty emailAddressProperty() {
    return emailAddress;
}

public void setEmailAddress(String emailAddress) {
    this.emailAddress.set(emailAddress);
}


@Override
public String toString() {
    return "Contact{" +
            "firstName=" + firstName +
            ", lastName=" + lastName +
            ", phoneNumber=" + phoneNumber +
            ", emailAddress=" + emailAddress +
            '}';
}
}

主窗口.fxml

<BorderPane fx:id="mainPanel" fx:controller="sample.Controller"
        xmlns:fx="http://javafx.com/fxml">


<top>
    <MenuBar>
        <menus>
            <Menu text="Contacts">
                <items>
                    <MenuItem text="Add new" onAction="#showAddContactDialog"/>
                </items>
                <items>
                    <MenuItem text="Edit" />
                </items>
                <items>
                    <MenuItem text="Delete"/>
                </items>
                <items>
                    <MenuItem text="Exit"/>
                </items>
            </Menu>
        </menus>
        <menus>
            <Menu text="Info">
                <items>
                    <MenuItem text="About"/>
                </items>

            </Menu>
        </menus>
    </MenuBar>
</top>

<center>
    <TableView fx:id="contactsTable">
        <columnResizePolicy>
            <TableView fx:constant="CONSTRAINED_RESIZE_POLICY"/>
        </columnResizePolicy>
        <columns>
            <TableColumn text="First Name">
                <cellValueFactory>
                    <PropertyValueFactory property="firstName"/>
                </cellValueFactory>
            </TableColumn>

            <TableColumn text="Last Name">
                <cellValueFactory>
                    <PropertyValueFactory property="lastName"/>
                </cellValueFactory>
            </TableColumn>

            <TableColumn text="Phone Number">
                <cellValueFactory>
                    <PropertyValueFactory property="phoneNumber"/>
                </cellValueFactory>
            </TableColumn>

            <TableColumn text="Email">
                <cellValueFactory>
                    <PropertyValueFactory property="emailAddress"/>
                </cellValueFactory>
            </TableColumn>
        </columns>
    </TableView>
</center>
</BorderPane>

addContactDialog.fxml

<DialogPane fx:controller="sample.ContactController" xmlns:fx="http://javafx.com/fxml">
    <headerText>
    Fill in the information for the new Contact
</headerText>
<content>
    <GridPane vgap="10" hgap="10">
        <Label text="First Name: " GridPane.rowIndex="0" GridPane.columnIndex="0"/>
        <TextField fx:id="firstNameField" GridPane.rowIndex="0" GridPane.columnIndex="1"/>

        <Label text="Last Name: " GridPane.rowIndex="1" GridPane.columnIndex="0"/>
        <TextField fx:id="lastNameField" GridPane.rowIndex="1" GridPane.columnIndex="1"/>

        <Label text="Phone Number: " GridPane.rowIndex="2" GridPane.columnIndex="0"/>
        <TextField fx:id="phoneNumberField" GridPane.rowIndex="2" GridPane.columnIndex="1"/>

        <Label text="Notes: " GridPane.rowIndex="3" GridPane.columnIndex="0"/>
        <TextField fx:id="notesField" GridPane.rowIndex="3" GridPane.columnIndex="1"/>

    </GridPane>
</content>
</DialogPane>

【问题讨论】:

    标签: javafx input textfield


    【解决方案1】:

    好的,我发现了错误 - 我在 ContactController.java 文件中打错了字。它应该有 phoneNumberField 而不是 phoneNumberFiled String...

    【讨论】:

      【解决方案2】:

      你试过把.toString 像这样 String firstName = contactController.getNewContact().getFirstName().toString();

      【讨论】:

      • 我做了,但没有任何改变,更重要的是,IntelliJ 将其突出显示为冗余方法。
      • 为什么在String 上调用toString() 会有什么不同?
      猜你喜欢
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      相关资源
      最近更新 更多