我有一个文本字段和两个按钮添加和删除,当我按添加/删除按钮时我试图获取文本字段数据,但是我得到了空指针异常 这是我的代码
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
}
}
我在此行上得到空指针异常
String msg = tagTextField.getText();
我确定我缺少javafx中的新功能,请帮助
答案 0 :(得分:1)
<TextField id="tagTextField" layoutX="173.0" layoutY="46.0" promptText="add tag here" onKeyPressed="#sendMethod"/>
在FXML文件中的这一行代码中,您将CSS id
声明为“ tagTextField”。您应该使用fx:id="tagTextField"
将其链接到您的控制器。