如何在表视图中显示字符串而不是整数(FXML)

How to show String instead of integer in tableview (FXML)

我的数据库 table 中有一个存储整数的字段。为了使程序更加用户友好,我想在 TableViews 和 ComboBoxes 中将数据表示为字符串而不是整数。例如,它应该显示 "unsupported" 而不是 0 而应该显示 "supported" 而不是 1。这是我的领域之一:

private final SimpleIntegerProperty status = new ReadOnlyIntegerWrapper();
 public int getStatus() {
    return status.get();
}
public void setStatus(int val)
{
    status.set(val);
}

我成功地使用 FXML 检索数据并将其注入到 TableView,但它显示 0 或 1;我如何在 Java 中实现它?

我需要组合框的解决方案,以便用户可以 select 一个有意义的字符串而不是数字。

创建您的StringConverter,它可以将每个状态转换为您想要的表达式。

public class StatusStringConverter extends StringConverter<Integer> {

    // Manage selectable options as Integer here
    final public static ObservableList<Integer> OPTIONS = FXCollections.observableArrayList(0, 1);

    @Override
    public String toString(Integer value) {
        switch (value) {
            case 0: return "unsupported";
            case 1: return "supported";
            default: return "-";
        }
    }
    @Override
    public Integer fromString(String string) {
        return null;
    }
}

使用 ComboBoxTableCellStatusStringConverter 可以在单元格和 ComboBox 选项中显示您的表达式。试试吧。

table.setEditable(true);
column.setEditable(true);
column.setCellValueFactory(new PropertyValueFactory<>("status"));
column.setCellFactory(ComboBoxTableCell.forTableColumn(
        new StatusStringConverter(), StatusStringConverter.OPTIONS));