cssjavafxjfoenix

JavaFX SetText CSS options


I'm using the Jfoenix libary, and I have gotten it to show both the day of the year, and day of the month (after asking here for the first hint). They are both inside the setText line. I'm trying to figure out if I can add CSS to them individually so I can make the Day of the Year appear smaller, in the right corner and maybe a different color. I've googled quite a bit but not getting the answers I'm looking for. Thank you.

    endDate.setDayCellFactory(p -> new DateCell() {

        @Override
        public void updateItem(LocalDate item, boolean empty) {
            super.updateItem(item, empty);

            if (item == null) {
                setText("");
            } else {
                setText(Integer.toString(item.getDayOfYear()) + "\r\n" + Integer.toString(item.getDayOfMonth()));
            }
        }

    });

Solution

  • You cannot style the text in the same Labeled differently, but you can use the graphic property instead to display the date:

    DatePicker datePicker = new DatePicker();
    datePicker.setDayCellFactory(p -> new DateCell() {
    
        private final Text doy = new Text();
        private final Text dom = new Text();
    
        private final VBox graphic = new VBox(doy, dom);
    
        {
            setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            doy.setFont(Font.font(8));
            dom.setFont(Font.font(15));
            VBox.setMargin(dom, new Insets(0, 0, 0, 10));
        }
    
        @Override
        public void updateItem(LocalDate item, boolean empty) {
            super.updateItem(item, empty);
            if (item == null) {
                setGraphic(null);
            } else {
                setGraphic(graphic);
                doy.setText(Integer.toString(item.getDayOfYear()));
                dom.setText(Integer.toString(item.getDayOfMonth()));
            }
        }
    
    });
    

    BTW: For java internal string handling usually \r is not required. This is only necessary, if you write the string to a file or use a class that depends on the line separator of the OS; only \n works just fine for the purpose you're using it for here. If you need to use different line separation on different OS, hardcoding \r\n is not a good idea; use System.lineSeparator() instead.