如何让组合框更明显?

时间:2014-11-11 22:13:52

标签: java combobox javafx

在我之前的问题中,How do you add labels to the options in combobox and list?

我曾问过如何在我的组合框中添加标题!答案很完美,但我无法区分我的标题和选项。 是否有可能缩进任何可以选择的内容?或者让我的标题变大胆?我的代码几乎是我上一个问题的最佳答案。哪个是......

所有标题都不可选。

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);
}
}

1 个答案:

答案 0 :(得分:0)

您需要了解细胞工厂。 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来区别对已禁用的单元格进行设置,但这可能不太灵活。