gpt4 book ai didi

java - 如何使组合框标题更明显?

转载 作者:行者123 更新时间:2023-12-05 07:57:32 25 4
gpt4 key购买 nike

在我之前的问题中,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);
}
}

最佳答案

你需要了解细胞工厂。方法 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 为禁用的单元格设置不同的样式,但这可能不太灵活。

关于java - 如何使组合框标题更明显?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26875590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com