Create a class to encapsulate the entity that you want to be displayed in the combo box:
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 ;
}
}
Now you can make a ComboBox
that displays these:
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"));
You can customize the display by defining a list cell:
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())));
}
}
}
and then
timeOfDayCombo.setCellFactory(lv -> new TimeOfDayListCell());
timeOfDayCombo.setButtonCell(new TimeOfDayListCell());
Now calling timeOfDayCombo.getValue()
will return the TimeOfDay
instance, from which you can call any method you need (such as getShortDescription()
).