我正在使用ComboBox,添加了一些字符串,并且还向其中添加了占位符。 我的目标是让用户从ComboBox中选择内容,但是当我尝试获取ComboBox的值而我没有选择任何内容时,它给了我NullPointerException,因为所选的Item是placeHolder。
如何检测所选的项目是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);
}
}
答案 0 :(得分:3)
添加简单的null检查即可解决:Cb_tipusDocument.getValue() == null
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() == null) {
//...
}else {
//...
}
}