javafxcombobox

Is there a way to display Integer values in JavaFx ComboBox with two digits?


I'm implementing a kind of clock in JavaFx. I have 2 combo boxes with integer values to select a time, one representing hours and the other minutes.

Is there a simple way of displaying the selected Integer with 2 digits in the ComboBox, for example instead of 1 there is 01?

One solution might be to have the combo box with string values and convert them to integers when I use them. However, I was wondering if there was another way to change the presentation of integers in the combo box properties directly.


Solution

  • Try using setCellFactory. As stated by @James_D in the commments and his edit to this answer, you also need to use setButtonCell.

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.ComboBox;
    import javafx.scene.control.ListCell;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    
    
    /**
     * JavaFX App
     */
    public class App extends Application {
    
        @Override
        public void start(Stage stage) {
    
            ComboBox<Integer> cmb = new ComboBox();
            cmb.getItems().addAll(1, 2, 3, 10);
    
            cmb.setCellFactory(_ -> createCell());
            cmb.setButtonCell(createCell());
            
            cmb.setValue(1);
            
            Scene scene = new Scene(new StackPane(cmb));            
            stage.setScene(scene);
            stage.setMaximized(true);
            stage.show();
        }
    
        private ListCell<Integer> createCell() {
            return new ListCell<Integer>() 
            {            
                @Override protected void updateItem(Integer item, boolean empty) {
                    super.updateItem(item, empty);
                    
                    if (item == null || empty) 
                    {
                        setText(null);
                    } 
                    else 
                    {
                        setText(String.format("%02d", item));
                    }
                }
            };
        }
    
        public static void main(String[] args) {
            launch();
        }
    
    }
    

    enter image description here