下面列出了怎么用javafx.scene.control.ListCell的API类实例代码及写法,或者点击链接到github查看源代码。
private ComboBox<ConstellationColor> makeNamedCombo() {
final ObservableList<ConstellationColor> namedColors = FXCollections.observableArrayList();
for (final ConstellationColor c : ConstellationColor.NAMED_COLOR_LIST) {
namedColors.add(c);
}
final ComboBox<ConstellationColor> namedCombo = new ComboBox<>(namedColors);
namedCombo.setValue(ConstellationColor.WHITE);
final Callback<ListView<ConstellationColor>, ListCell<ConstellationColor>> cellFactory = (final ListView<ConstellationColor> p) -> new ListCell<ConstellationColor>() {
@Override
protected void updateItem(final ConstellationColor item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
final Rectangle r = new Rectangle(12, 12, item.getJavaFXColor());
r.setStroke(Color.BLACK);
setText(item.getName());
setGraphic(r);
}
}
};
namedCombo.setCellFactory(cellFactory);
namedCombo.setButtonCell(cellFactory.call(null));
return namedCombo;
}
public static <T> Callback<ListView<T>, ListCell<T>> simpleListCellFactory(Function<T, String> converter, Function<T, String> toolTipMaker) {
return collection -> new ListCell<T>() {
@Override
protected void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
Tooltip.uninstall(this, getTooltip());
} else {
setText(converter.apply(item));
Tooltip.install(this, new Tooltip(toolTipMaker.apply(item)));
}
}
};
}
@Override
public void start(Stage primaryStage) throws Exception {
StackPane pane = new StackPane();
Scene scene = new Scene(pane, 300, 150);
primaryStage.setScene(scene);
ObservableList<String> list = FXCollections.observableArrayList(
"Item 1", "Item 2", "Item 3", "Item 4");
ListView<String> lv = new ListView<>(list);
lv.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> param) {
return new XCell();
}
});
pane.getChildren().add(lv);
primaryStage.show();
}
@Override
public void start(Stage primaryStage) throws Exception {
StackPane pane = new StackPane();
Scene scene = new Scene(pane, 300, 150);
primaryStage.setScene(scene);
ObservableList<String> list = FXCollections.observableArrayList(
"Item 1", "Item 2", "Item 3", "Item 4");
ListView<String> lv = new ListView<>(list);
lv.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> param) {
return new XCell();
}
});
pane.getChildren().add(lv);
primaryStage.show();
}
@Override
public void start(Stage primaryStage) throws Exception {
StackPane pane = new StackPane();
Scene scene = new Scene(pane, 300, 150);
primaryStage.setScene(scene);
ObservableList<String> list = FXCollections.observableArrayList(
"Item 1", "Item 2", "Item 3", "Item 4");
ListView<String> lv = new ListView<>(list);
lv.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> param) {
return new XCell();
}
});
pane.getChildren().add(lv);
primaryStage.show();
}
/**
* @param cellFactory
* Set a custom cell factory for the suggestions.
*/
public AutoCompletePopupSkin2(AutoCompletePopup<T> control, Callback<ListView<T>, ListCell<T>> cellFactory) {
this.control = control;
suggestionList = new ListView<>(control.getSuggestions());
suggestionList.getStyleClass().add(AutoCompletePopup.DEFAULT_STYLE_CLASS);
suggestionList.getStylesheets().add(AutoCompletionBinding.class
.getResource("autocompletion.css").toExternalForm()); //$NON-NLS-1$
/**
* Here we bind the prefHeightProperty to the minimum height between the max visible rows and the current items list. We also add an
* arbitrary 5 number because when we have only one item we have the vertical scrollBar showing for no reason.
*/
suggestionList.prefHeightProperty().bind(
Bindings.min(control.visibleRowCountProperty(), Bindings.size(suggestionList.getItems()))
.multiply(LIST_CELL_HEIGHT).add(18));
suggestionList.setCellFactory(cellFactory);
// Allowing the user to control ListView width.
suggestionList.prefWidthProperty().bind(control.prefWidthProperty());
suggestionList.maxWidthProperty().bind(control.maxWidthProperty());
suggestionList.minWidthProperty().bind(control.minWidthProperty());
registerEventListener();
}
@Test
void testEditingTheExistingTestCellThenRemoval(FxRobot robot) throws InterruptedException {
// create an appropriate panel and verify the basics are OK
createMainPanel(uiSubItem);
performAllCommonChecks(enumItem);
// first type some new text for the cell that is valid. Check the consumer is updated.
ListCell<String> lc = robot.lookup("#enumList .list-cell").query();
simulateListCellEdit(lc, "hello");
checkThatConsumerCalledWith("hello");
// now we add some bad text, and make sure it errors out.
simulateListCellEdit(lc, "bad\\");
verifyThat("#uiItemErrors", (Label l)-> l.getText().contains("Choices must not contain speech marks or backslash") && l.isVisible());
}
/**
* Wires the list view with the items source and configures filtering and sorting of the items.
*/
private void loadItems() {
// filtering -- default show all
FilteredList<ActivityItem> filteredItems = new FilteredList<>(activityLogger.getActivityItems(), p -> true);
txtFilter.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
// filter on predicate
filteredItems.setPredicate(new ActivityItemFilterPredicate(newValue));
}
});
// sorting
SortedList<ActivityItem> sortedItems = new SortedList<>(filteredItems, new ActivityItemTimeComparator());
// set item source
lstActivityLog.setItems(sortedItems);
lstActivityLog
.setCellFactory(new Callback<ListView<ActivityItem>, ListCell<ActivityItem>>() {
@Override
public ListCell<ActivityItem> call(ListView<ActivityItem> param) {
return new ActivityItemCell();
}
});
}
public void initScopesBox() {
try {
scopeSelector.setButtonCell(new ImageScopeCell());
scopeSelector.setCellFactory(new Callback<ListView<ImageScope>, ListCell<ImageScope>>() {
@Override
public ListCell<ImageScope> call(ListView<ImageScope> param) {
return new ImageScopeCell();
}
});
scopeSelector.setVisibleRowCount(15);
scopeDeleteButton.disableProperty().bind(
scopeSelector.getSelectionModel().selectedItemProperty().isNull()
);
scopeUseButton.disableProperty().bind(
scopeSelector.getSelectionModel().selectedItemProperty().isNull()
);
} catch (Exception e) {
logger.error(e.toString());
}
}
@Override
public ListCell<AlertCell> call(ListView<T> param) {
return new ListCell<AlertCell>(){
@Override
protected void updateItem(AlertCell item, boolean empty) {
super.updateItem(item, empty);
if(item == null || empty) {
setItem(null);
setGraphic(null);
setText(null);
} else {
setItem(item);
// setText(item.get);
System.out.println(item.getIcon());
setGraphic(item.getIcon());
}
}
};
}
public ListViewCellFactorySample() {
final ListView<Number> listView = new ListView<Number>();
listView.setItems(FXCollections.<Number>observableArrayList(
100.00, -12.34, 33.01, 71.00, 23000.00, -6.00, 0, 42223.00, -12.05, 500.00,
430000.00, 1.00, -4.00, 1922.01, -90.00, 11111.00, 3901349.00, 12.00, -1.00, -2.00,
15.00, 47.50, 12.11
));
listView.setCellFactory(new Callback<ListView<java.lang.Number>, ListCell<java.lang.Number>>() {
@Override public ListCell<Number> call(ListView<java.lang.Number> list) {
return new MoneyFormatCell();
}
});
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
getChildren().add(listView);
}
private void initListView() {
if (!doesAllowChildren) {
fillUpChildren(fileChooserInfo.getRoot());
}
childrenListView.setCellFactory(new Callback<ListView<File>, ListCell<File>>() {
@Override
public ListCell<File> call(ListView<File> param) {
return new ChildrenFileCell();
}
});
childrenListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (fileChooserInfo.isFileCreation()) {
return;
}
File selectedItem = childrenListView.getSelectionModel().getSelectedItem();
if (selectedItem == null) {
fileNameBox.clear();
}
});
}
private void initComponents() {
optionBox.setItems(model);
optionBox.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
if (newValue != null) {
updateTabPane();
}
});
optionBox.setCellFactory(new Callback<ListView<PlugInModelInfo>, ListCell<PlugInModelInfo>>() {
@Override
public ListCell<PlugInModelInfo> call(ListView<PlugInModelInfo> param) {
return new LauncherCell();
}
});
optionTabpane.setId("CompositeTabPane");
optionTabpane.setTabClosingPolicy(TabClosingPolicy.UNAVAILABLE);
optionTabpane.getStyleClass().add(TabPane.STYLE_CLASS_FLOATING);
VBox.setVgrow(optionTabpane, Priority.ALWAYS);
}
@NotNull
public static <T> ListCell<T> getComboBoxButtonCell(String title,
ComboBox<T> comboBox,
Boolean hideOriginalPrompt) {
return new ListCell<>() {
@Override
protected void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
// See https://github.com/jfoenixadmin/JFoenix/issues/610
if (hideOriginalPrompt)
this.setVisible(item != null || !empty);
if (empty || item == null) {
setText(title);
} else {
setText(comboBox.getConverter().toString(item));
}
}
};
}
protected int getIndexAt(ListView<?> listView, Point2D point) {
if (point == null) {
return listView.getSelectionModel().getSelectedIndex();
}
point = listView.localToScene(point);
Set<Node> lookupAll = getListCells(listView);
ListCell<?> selected = null;
for (Node cellNode : lookupAll) {
Bounds boundsInScene = cellNode.localToScene(cellNode.getBoundsInLocal(), true);
if (boundsInScene.contains(point)) {
selected = (ListCell<?>) cellNode;
break;
}
}
if (selected == null) {
return -1;
}
return selected.getIndex();
}
public ListViewCellFactorySample() {
final ListView<Number> listView = new ListView<Number>();
listView.setItems(FXCollections.<Number>observableArrayList(
100.00, -12.34, 33.01, 71.00, 23000.00, -6.00, 0, 42223.00, -12.05, 500.00,
430000.00, 1.00, -4.00, 1922.01, -90.00, 11111.00, 3901349.00, 12.00, -1.00, -2.00,
15.00, 47.50, 12.11
));
listView.setCellFactory(new Callback<ListView<java.lang.Number>, ListCell<java.lang.Number>>() {
@Override public ListCell<Number> call(ListView<java.lang.Number> list) {
return new MoneyFormatCell();
}
});
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
getChildren().add(listView);
}
public static ListCell<PaymentMethod> getPaymentMethodButtonCell() {
return new ListCell<>() {
@Override
protected void updateItem(PaymentMethod item, boolean empty) {
super.updateItem(item, empty);
if (item != null && !empty) {
String id = item.getId();
this.getStyleClass().add("currency-label-selected");
if (id.equals(GUIUtil.SHOW_ALL_FLAG)) {
setText(Res.get("list.currency.showAll"));
} else {
setText(Res.get(id));
}
} else {
setText("");
}
}
};
}
private void customizeCipherTextCellFactory() {
cipherTextList.setCellFactory(new Callback<ListView<AuthenticatedBallot>, ListCell<AuthenticatedBallot>>() {
@Override
public ListCell<AuthenticatedBallot> call(ListView<AuthenticatedBallot> param) {
return new ListCell<AuthenticatedBallot>() {
@Override
protected void updateItem(AuthenticatedBallot item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(DatatypeConverter.printHexBinary(item.getAuthenticatedEncryptedBallot()));
}
}
};
}
});
}
@Override
public ListCell<JFXListBoxSelectItem<T>> call(ListView<JFXListBoxSelectItem<T>> listView) {
return new ListCell<JFXListBoxSelectItem<T>>() {
public void updateItem(JFXListBoxSelectItem<T> item, boolean empty) {
super.updateItem(item, empty);
this.setManaged(false);
this.applyCss();
this.setGraphic(null);
this.setText(empty ? null : (item != null ? item.toString() : "null"));
if( item != null ) {
this.setPadding(getControl().computeCellPadding());
this.setPrefWidth(getControl().computeCellWidth(item));
this.setPrefHeight(getControl().computeCellHeight(item));
}
}
};
}
private double estimateHeight() {
// compute the border/padding for the list
double borderWidth = snapVerticalInsets();
// compute the gap between list cells
JFXListView<T> listview = (JFXListView<T>) getSkinnable();
double gap = listview.isExpanded() ? ((JFXListView<T>) getSkinnable()).getVerticalGap() * (getSkinnable().getItems()
.size()) : 0;
// compute the height of each list cell
double cellsHeight = 0;
for (int i = 0; i < flow.getCellCount(); i++) {
ListCell<T> cell = flow.getCell(i);
cellsHeight += cell.getHeight();
}
return cellsHeight + gap + borderWidth;
}
@Override
protected Node createEditorControls() {
final GridPane controls = new GridPane();
controls.setAlignment(Pos.CENTER);
controls.setHgap(CONTROLS_DEFAULT_HORIZONTAL_SPACING);
final Label connectionModeLabel = new Label("Connection Mode:");
final ObservableList<ConnectionMode> connectionModes = FXCollections.observableArrayList(ConnectionMode.values());
connectionModeComboBox = new ComboBox<>(connectionModes);
final Callback<ListView<ConnectionMode>, ListCell<ConnectionMode>> cellFactory = (final ListView<ConnectionMode> p) -> new ListCell<ConnectionMode>() {
@Override
protected void updateItem(final ConnectionMode item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item.name());
}
}
};
connectionModeComboBox.setCellFactory(cellFactory);
connectionModeComboBox.setButtonCell(cellFactory.call(null));
connectionModeLabel.setLabelFor(connectionModeComboBox);
connectionModeComboBox.getSelectionModel().selectedItemProperty().addListener((o, n, v) -> {
update();
});
controls.addRow(0, connectionModeLabel, connectionModeComboBox);
return controls;
}
@Override
protected Node createEditorControls() {
final GridPane controls = new GridPane();
controls.setAlignment(Pos.CENTER);
controls.setHgap(CONTROLS_DEFAULT_HORIZONTAL_SPACING);
final Label lineStyleLabel = new Label("Line Style:");
final ObservableList<LineStyle> lineStyles = FXCollections.observableArrayList(LineStyle.values());
lineStyleComboBox = new ComboBox<>(lineStyles);
final Callback<ListView<LineStyle>, ListCell<LineStyle>> cellFactory = (final ListView<LineStyle> p) -> new ListCell<LineStyle>() {
@Override
protected void updateItem(final LineStyle item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item.name());
}
}
};
lineStyleComboBox.setCellFactory(cellFactory);
lineStyleComboBox.setButtonCell(cellFactory.call(null));
lineStyleLabel.setLabelFor(lineStyleComboBox);
lineStyleComboBox.getSelectionModel().selectedItemProperty().addListener((o, n, v) -> {
update();
});
controls.addRow(0, lineStyleLabel, lineStyleComboBox);
return controls;
}
/**
* Make a list cell never overflow the width of its container, to
* avoid having a horizontal scroll bar showing up. This defers
* resizing constraints to the contents of the cell.
*
* @return The given cell
*/
public static <T> ListCell<T> makeListCellFitListViewWidth(ListCell<T> cell) {
if (cell != null) {
cell.prefWidthProperty().bind(
Val.wrap(cell.listViewProperty())
.flatMap(Region::widthProperty).map(it -> it.doubleValue() - 5)
.orElseConst(0.)
);
cell.setMaxWidth(Control.USE_PREF_SIZE);
}
return cell;
}
public static Callback<ListView<PaymentMethod>, ListCell<PaymentMethod>> getPaymentMethodCellFactory() {
return p -> new ListCell<>() {
@Override
protected void updateItem(PaymentMethod method, boolean empty) {
super.updateItem(method, empty);
if (method != null && !empty) {
String id = method.getId();
HBox box = new HBox();
box.setSpacing(20);
Label paymentType = new AutoTooltipLabel(
method.isAsset() ? Res.get("shared.crypto") : Res.get("shared.fiat"));
paymentType.getStyleClass().add("currency-label-small");
Label paymentMethod = new AutoTooltipLabel(Res.get(id));
paymentMethod.getStyleClass().add("currency-label");
box.getChildren().addAll(paymentType, paymentMethod);
if (id.equals(GUIUtil.SHOW_ALL_FLAG)) {
paymentType.setText(Res.get("shared.all"));
paymentMethod.setText(Res.get("list.currency.showAll"));
}
setGraphic(box);
} else {
setGraphic(null);
}
}
};
}
public static <T> Callback<ListView<T>, ListCell<T>> forListView(final ContextMenu contextMenu, final Callback<ListView<T>, ListCell<T>> cellFactory) {
return new Callback<ListView<T>, ListCell<T>>() {
@Override
public ListCell<T> call(ListView<T> listView) {
ListCell<T> cell = cellFactory == null ? new DefaultListCell<T>() : cellFactory.call(listView);
cell.setContextMenu(contextMenu);
return cell;
}
};
}
public void initColorBox() {
try {
scopeColorsList.setButtonCell(new ListColorCell());
scopeColorsList.setCellFactory(new Callback<ListView<Color>, ListCell<Color>>() {
@Override
public ListCell<Color> call(ListView<Color> p) {
return new ListColorCell();
}
});
scopeColorsList.getItems().addListener(new ListChangeListener<Color>() {
@Override
public void onChanged(Change<? extends Color> c) {
int size = scopeColorsList.getItems().size();
colorsSizeLabel.setText(message("Count") + ": " + size);
if (size > 100) {
colorsSizeLabel.setStyle(redText);
} else {
colorsSizeLabel.setStyle(blueText);
}
}
});
colorExcludedCheck.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (isSettingValues || scope == null) {
return;
}
scope.setColorExcluded(newValue);
indicateScope();
}
});
} catch (Exception e) {
logger.error(e.toString());
}
}
private void initComponents() {
VBox.setVgrow(historyView, Priority.ALWAYS);
historyView.setItems(FXCollections.observableArrayList(runHistoryInfo.getTests()));
historyView.setCellFactory(new Callback<ListView<JSONObject>, ListCell<JSONObject>>() {
@Override
public ListCell<JSONObject> call(ListView<JSONObject> param) {
return new HistoryStateCell();
}
});
VBox historyBox = new VBox(5);
HBox.setHgrow(historyBox, Priority.ALWAYS);
countField.setText(getRemeberedCount());
if (countNeeded) {
form.addFormField("Max count of remembered runs: ", countField);
}
historyBox.getChildren().addAll(new Label("Select test", FXUIUtils.getIcon("params")), historyView, form);
verticalButtonBar.setId("vertical-buttonbar");
historyPane.setId("history-pane");
historyPane.getChildren().addAll(historyBox, verticalButtonBar);
doneButton.setOnAction((e) -> onOK());
buttonBar.setButtonMinWidth(Region.USE_PREF_SIZE);
buttonBar.getButtons().addAll(doneButton);
}
@SuppressWarnings("rawtypes")
public ListCell<?> getVisibleCellAt(ListView listView, Integer index) {
Set<Node> lookupAll = getListCells(listView);
ListCell<?> cell = null;
for (Node node : lookupAll) {
if (((ListCell<?>) node).getIndex() == index) {
cell = (ListCell<?>) node;
break;
}
}
if (cell != null) {
return cell;
}
return null;
}
private Node getEditor() {
ListCell<?> cell = (ListCell<?>) getPseudoComponent();
cell.getListView().edit(cell.getIndex());
Node cellComponent = cell.getGraphic();
cellComponent.getProperties().put("marathon.celleditor", true);
cellComponent.getProperties().put("marathon.cell", cell);
return cellComponent;
}
@Override
public String _getText() {
ListCell<?> cell = (ListCell<?>) getPseudoComponent();
Node graphic = cell.getGraphic();
JavaFXElement graphicElement = (JavaFXElement) JavaFXElementFactory.createElement(graphic, driver, window);
if (graphic != null && graphicElement != null) {
if (graphic instanceof CheckBox) {
return cell.getText();
} else {
return graphicElement._getValue();
}
}
JavaFXElement cellElement = (JavaFXElement) JavaFXElementFactory.createElement(cell, driver, window);
return cellElement._getValue();
}