【发布时间】:2016-12-16 03:08:46
【问题描述】:
是否可以向CheckComboBox 添加标题/标签?我正在考虑一个不可选择的默认项目。我正在使用一个没有输入字段标签的内联表单。我想为 CheckComboBox 使用内联标题。
【问题讨论】:
标签: javafx controlsfx
是否可以向CheckComboBox 添加标题/标签?我正在考虑一个不可选择的默认项目。我正在使用一个没有输入字段标签的内联表单。我想为 CheckComboBox 使用内联标题。
【问题讨论】:
标签: javafx controlsfx
据我所知,API 中没有这方面的功能。
但不久前我自己为ComboBox 实现了这个,我认为调整它以满足您的需求不会有任何问题。我在下面发布了一个 MCVE。至少你明白了。
编辑:似乎CheckComboBox 没有setCellFactory 方法。所以也许我的实现对你没有太大帮助。也许一种替代方法是从普通的JavaFX 中的ComboBox 实现您自己的CheckComboBox。
MCVE:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class MCVE extends Application {
@Override
public void start(Stage stage) {
HBox box = new HBox();
ComboBox<ComboBoxItem> cb = new ComboBox<ComboBoxItem>();
cb.setCellFactory(e -> 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());
// If item is a header we disable it.
setDisable(!item.isHeader());
// If item is a header we add a style to it so it looks like a header.
if (item.isHeader()) {
setStyle("-fx-font-weight: bold;");
} else {
setStyle("-fx-font-weight: normal;");
}
}
}
});
ObservableList<ComboBoxItem> items = FXCollections.observableArrayList(new ComboBoxItem("Header", true),
new ComboBoxItem("Option", false));
cb.getItems().addAll(items);
box.getChildren().add(cb);
stage.setScene(new Scene(box));
stage.show();
}
public static void main(String[] args) {
launch();
}
/**
* A wrapping class for a String that also has a boolean that indicates
* whether this item should be disabled or not.
*
* @author Jonatan Stenbacka
*/
public class ComboBoxItem implements Comparable<ComboBoxItem> {
private String text;
private boolean isHeader = false;
public ComboBoxItem(String text, boolean isHeader) {
this.text = text;
this.isHeader = isHeader;
}
public ComboBoxItem(String text) {
this.text = text;
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
public boolean isHeader() {
return isHeader;
}
@Override
public String toString() {
return text;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof ComboBoxItem) {
ComboBoxItem item = (ComboBoxItem) obj;
if (text.equals(item.getText())) {
return true;
}
} else if (obj instanceof String) {
String item = (String) obj;
if (text.equals(item)) {
return true;
}
}
return false;
}
@Override
public int compareTo(ComboBoxItem o) {
return getText().compareTo(o.getText());
}
@Override
public int hashCode() {
return text.hashCode();
}
}
}
【讨论】: