我有一个文本字段和两个按钮“添加”和“删除”。当按下“添加”/“删除”按钮时,我正在尝试获取文本字段数据,但我得到了空指针异常。以下是我的代码
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的新手,请帮助我
发布于 2018-06-23 04:33:24
<TextField id="tagTextField" layoutX="173.0" layoutY="46.0" promptText="add tag here" onKeyPressed="#sendMethod"/>
在FXML文件的这行代码中,您将CSS id
声明为"tagTextField“。您应该使用fx:id="tagTextField"
将其链接到您的控制器。
https://stackoverflow.com/questions/50995052
复制相似问题