【发布时间】:2019-11-17 17:36:47
【问题描述】:
我正在使用一个组合框,我添加了一些字符串,并且我还添加了一个占位符。 我的目标是让用户从 ComboBox 中选择一些东西,但是当我尝试获取 ComboBox 的值并且我没有选择任何东西时,它给了我一个 NullPointerException,因为所选项目是一个 placeHolder。
我怎样才能检测到所选项目是占位符?
控制器:
package sample;
public class Controller implements Initializable {
public ComboBox Cb_tipusDocument;
@Override
public void initialize(URL location, ResourceBundle resources) {
ObservableList<String> ol_str_llistatPerSelect = FXCollections.observableArrayList("A", "B", "C");
Cb_tipusDocument.setItems(ol_str_llistatPerSelect);
}
public void executar(ActionEvent actionEvent) {
if ( Cb_tipusDocument.getValue().equals("")) {
//...
}else {
//...
}
}
Sample.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.ComboBox?>
<AnchorPane fx:id="Ap_principal" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="500.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<Pane prefHeight="500.0" prefWidth="600.0">
<children>
<ComboBox fx:id="Cb_tipusDocument" layoutX="94.0" layoutY="131.0" prefHeight="25.0" prefWidth="406.0" promptText="Seleccioneu una opció" />
</children>
</Pane>
<ToolBar layoutY="440.0" prefHeight="60.0" prefWidth="600.0">
<items>
<Pane prefHeight="0.0" prefWidth="200.0" />
<Button mnemonicParsing="false" onAction="#executar" prefHeight="33.0" prefWidth="180.0" text="Generar Config" />
</items>
</ToolBar>
</children>
</AnchorPane>
主要
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Trying new things");
primaryStage.setScene(new Scene(root, 600, 500));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
【问题讨论】:
-
实际上,你得到了一个 NPE,因为你没有选择任何东西,这意味着它是空的。只需添加一个简单的空检查
-
@Stultuske 我太笨了??!!非常感谢我使用了
Cb_tipusDocument.getValue() == null和 WORKED -
与您的问题无关:请学习 java 命名约定并遵守它们。
-
@kleopatra 我会记住的,谢谢。
标签: java javafx nullpointerexception