如何使Combobox的标题更加明显?

 2023-02-15    373  

问题描述

在我以前的问题中,您如何添加标签Combobox和列表中的选项?

我问了如何将标头添加到我的Combobox中!答案很完美,但我却可以区分我的标题和选择.
是否可以缩进可以选择的任何东西?还是让我的标题大胆?我的代码几乎是我以前问题的最佳答案.这是…

如何使Combobox的标题更加明显?

所有标题都不可选.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class ComboBoxWithSections extends Application {

@Override
public void start(Stage primaryStage) {
    ComboBox<ComboBoxItem> combo = new ComboBox<>();
    combo.getItems().addAll(
        new ComboBoxItem("Short Duration", false),
        new ComboBoxItem("Last Hour",      true),
        new ComboBoxItem("Last 2 hours",   true),
        new ComboBoxItem("Last 24 hours",  true),
        new ComboBoxItem("",               false),
        new ComboBoxItem("Long Duration",  false),
        new ComboBoxItem("Last Month",     true),
        new ComboBoxItem("Last Year",      true)            
    );

    combo.setCellFactory(listView -> new ListCell<ComboBoxItem>() {
        @Override
        public void updateItem(ComboBoxItem item, boolean empty) {
            super.updateItem(item, empty);
            if (empty) {
                setText(null);
                setDisable(false);
            } else {
                setText(item.toString());
                setDisable(! item.isSelectable());
            }
        }
    });

    BorderPane root = new BorderPane(null, combo, null, null, null);
    primaryStage.setScene(new Scene(root, 250, 400));
    primaryStage.show();
}

public static class ComboBoxItem {
    private final String name ;
    private final boolean selectable ;

    public ComboBoxItem(String name, boolean selectable) {
        this.name = name ;
        this.selectable = selectable ;
    }

    public String getName() {
        return name ;
    }

    public boolean isSelectable() {
        return selectable ;
    }

    @Override
    public String toString() {
        return name ;
    }
}

public static void main(String[] args) {
    launch(args);
}
}

推荐答案

您需要了解单元工厂.方法updateItem是绘制单元格的地方.

super.updateItem(item, empty);//does important things in super
        if (empty) {                  //what to do if cell is empty   
            setText(null);
            setDisable(false);        //reset the disabled state 
        } else {
            setText(item.toString()); //calls toString in your custom class
            setDisable(! item.isSelectable()); //what stops you from selecting
            setTextFill(item.isSelectable()
                    ?Color.BLUE:Color.BLACK); //changing the color
        }

您可以在自定义类中添加颜色或字体,只需使用它而不是isselectable()来确定颜色.

您也可以使用CSS对残疾单元进行样式的样式不同,但这可能不那么灵活.

以上所述是小编给大家介绍的如何使Combobox的标题更加明显?,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!

原文链接:https://77isp.com/post/33777.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。