gpt4 book ai didi

java - ComboBox 占位符 NullPointerException JavaFX

转载 作者:搜寻专家 更新时间:2023-11-01 02:56:42 29 4
gpt4 key购买 nike

我使用的是 ComboBox,我添加了一些字符串,还向其中添加了一个占位符。我的目标是让用户从 ComboBox 中选择一些东西,但是当我尝试获取 ComboBox 的值并且我没有选择任何东西时,它会给我一个 NullPointerException,因为所选的 Item 是一个占位符。

如何检测所选项目是 PlaceHolder?

Controller :

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 {
//...
}
}

示例.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);
}
}


最佳答案

添加一个简单的空检查就可以解决: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 {
//...
}
}

关于java - ComboBox 占位符 NullPointerException JavaFX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56930941/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com