하기위한 항목 클래스를 만들기 당신의 선택 가능한 항목인지 아닌지를 선언하는 콤보 상자. (당신은 또한이 나타내는 시간에 편리한 접근,이에 다른 유용한 API를 추가 할 수 있습니다.)
는 그런 선택하지 않은 항목을 나타내는 세포 비활성화 셀 공장 사용
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);
}
}
을
업데이트이 elsewhere 답했지만 나는 CSS PseudoClass와 외부 CSS 파일을 사용하여 헤더의 스타일을 변경합니다 :
추가
,745,
start(...)
방법
, 다음과 같이 셀 공장의 updateItem(...)
방법을 변경 :
scene.getStylesheets().add("combo-box-with-sections.css");
및 CSS 파일은
처럼 보일 수 :
public void updateItem(ComboBoxItem item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setDisable(false);
pseudoClassStateChanged(header, false);
} else {
setText(item.toString());
setDisable(! item.isSelectable());
pseudoClassStateChanged(header, ! item.isSelectable());
}
}
이제 Scene
에 CSS 파일을 첨부
combo-box-with-sections.css :
.combo-box-popup .list-cell {
-fx-padding: 4 0 4 20 ;
}
.combo-box-popup .list-cell:section-header {
-fx-font: italic 10pt sans-serif ;
-fx-padding: 4 0 4 5 ;
}
그래, 내가 원했던 바로 그거야! 그것은 꽤 오래지만 : – Indigo
예,하지만 'String'을 사용하는 대신 아이템에 대한 실제 클래스의 추가 이점을 얻습니다. 이제는 올바른 시간 범위에 있는지 여부를 판단하기 위해 '문자열'을 켜야하는 대신 필요한 API를 추가 할 수 있습니다. 즉, 오버 헤드의 대부분은 어쨌든 실제 앱에서 수행하고자하는 작업입니다. –
나는 당신의 요점을 본다! 나는 대부분의 코드를 이해했지만, 코드를 읽는 사람이 누구인지 이해할 수 있도록 대답에 약간의 설명을 추가하면 좋을 것이다. 나도 솔직히 .setCellFactory를 잘 이해하지 못했지만 원하는 방식으로 작동합니다. – Indigo