0

i have a text-field and two buttons add and delete i am trying to get text field data when add/delete button is pressed but i am getting null pointer exception here is my code

tag.fxml
<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.server.serverController">
   <children>
      <Label id="taglabel" layoutX="44.0" layoutY="71.0" text="Tags list" />
      <TextField id="tagTextField" layoutX="173.0" layoutY="46.0" promptText="add tag here" onKeyPressed="#sendMethod"/>

      <Button id="tagInsertButton" layoutX="365.0" layoutY="46.0" mnemonicParsing="false" text="Insert Tag" onAction="#insertButtonAction" >
         <opaqueInsets>
            <Insets />
         </opaqueInsets>
      </Button>
      <Button id="tagDeleteButton" layoutX="458.0" layoutY="46.0" mnemonicParsing="false" text="Delete Tag" onAction="#deleteButtonAction"/>
   </children>
</Pane>

serverController.java

public class serverController implements Initializable{

    @FXML
    private TextField tagTextField;
    @FXML
    private Button tagInsertButton;
    @FXML
    private Button tagDeleteButton;

    public void insertButtonAction() throws IOException {
        String msg = tagTextField.getText();
        if (!tagTextField.getText().isEmpty()) {
            System.out.println("insert button pressed with value"+tagTextField.getText());
            tagTextField.clear();
        }
    }

    public void deleteButtonAction() throws IOException {
        String msg = tagTextField.getText();
        if (!tagTextField.getText().isEmpty()) {
            System.out.println("delete button pressed with value"+tagTextField.getText());
            tagTextField.clear();
        }
    }

    public void sendMethod(KeyEvent event) throws IOException {

        if (event.getSource() == tagInsertButton)
            insertButtonAction();

        if (event.getSource() == tagDeleteButton)
            deleteButtonAction();

    }

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
        // TODO Auto-generated method stub

    }
}

i am getting null pointer exception on this line

String msg = tagTextField.getText();

i am sure i am missing something i am new in javafx please help

swaheed
  • 3,671
  • 10
  • 42
  • 103

1 Answers1

1

<TextField id="tagTextField" layoutX="173.0" layoutY="46.0" promptText="add tag here" onKeyPressed="#sendMethod"/>

In this line of code in your FXML file, you're declaring the CSS id as "tagTextField". You should use fx:id="tagTextField" instead to link it to your controller.

Blake Ordway
  • 308
  • 1
  • 8