Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a different value than the 'label' for a combobox

Tags:

java

javafx

fxml

I am looking to use a 'value' for my combo box lists similar to how you can do in HTML where you can have the label (whatever is shown in the combo box) and the value (being the returned value) like so:

List 1:

label="9am - 12pm", value="Morning"  
label="12pm - 3pm", value="Afternoon"  
label="3pm - 6pm", value="Evening"

So, the combo box will display the "9am - 12pm", etc. but the value returned will be "Morning".

Maybe I've been spending too much time on my web assignments that I'm going about this in a stupid way but any help would be appreciated.

like image 347
Deano3607 Avatar asked Oct 20 '25 01:10

Deano3607


1 Answers

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()).

like image 120
James_D Avatar answered Oct 21 '25 14:10

James_D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!