为组合框使用与“标签”不同的值

Dea*_*607 2 java javafx fxml

我希望对组合框列表使用“值”,类似于在HTML中的操作,在HTML中可以使用标签(无论组合框中显示了什么)和值(即返回的值),如下所示:

清单1:

label="9am - 12pm", value="Morning"  
label="12pm - 3pm", value="Afternoon"  
label="3pm - 6pm", value="Evening"
Run Code Online (Sandbox Code Playgroud)

因此,组合框将显示“ 9am-12pm”,依此类推,但是返回的值将是“ Morning”。

也许我花了太多时间在网络任务上,以一种愚蠢的方式来解决这个问题,但是任何帮助都将不胜感激。

Jam*_*s_D 5

创建一个类以封装要在组合框中显示的实体:

import java.time.LocalTime ;

// maybe an enum would be good here too
public class TimeOfDay {

    private final LocalTime startTime ;
    private final LocalTime endTime ;

    private final String shortDescription ;

    public TimeOfDay(LocalTime startTime, LocalTime endTime, String description) {
        this.startTime = startTime ;
        this.endTime = endTime ;
        this.shortDescription = description ;
    }

    public LocalTime getStartTime() {
        return startTime ;
    }

    public LocalTime getEndTime() {
        return endTime ;
    }

    public String getShortDescription() {
        return shortDescription ;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以制作一个ComboBox显示以下内容的:

ComboBox<TimeOfDay> timeOfDayCombo = new ComboBox<>();

timeOfDayCombo.getItems().addAll(
    new TimeOfDay(LocalTime.of(9,0), LocalTime.of(12,0), "Morning"),
    new TimeOfDay(LocalTime.of(12,0), LocalTime.of(15,0), "Afternoon"),
    new TimeOfDay(LocalTime.of(15,0), LocalTime.of(18,0), "Evening"));
Run Code Online (Sandbox Code Playgroud)

您可以通过定义列表单元格来定制显示:

import java.time.LocalTime ;
import java.time.format.DateTimeFormatter ;

public class TimeOfDayListCell extends ListCell<TimeOfDay> {

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ha");

    @Override
    protected void updateItem(TimeOfDay timeOfDay, boolean empty) {
        super.updateItem(timeOfDay, empty) ;
        if (empty) {
            setText(null);
        } else {
            setText(String.format("%s - %s",
                formatter.format(timeOfDay.getStartTime()),
                formatter.format(timeOfDay.getEndTime())));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后

timeOfDayCombo.setCellFactory(lv -> new TimeOfDayListCell());
timeOfDayCombo.setButtonCell(new TimeOfDayListCell());
Run Code Online (Sandbox Code Playgroud)

现在,调用timeOfDayCombo.getValue()将返回TimeOfDay实例,您可以从中调用所需的任何方法(例如getShortDescription())。