下面列出了怎么用javafx.scene.control.ListView的API类实例代码及写法,或者点击链接到github查看源代码。
public NameListPane() {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/preference/NameListPane.fxml"), bundle);
loader.setRoot(this);
loader.setController(this);
try {
loader.load();
}
catch (Exception ex) {
LOG.log(Level.SEVERE, "Unable to load FXML", ex);
}
listName.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
listName.setCellFactory(TextFieldListCell.forListView());
listName.setOnEditCommit((EventHandler<ListView.EditEvent<String>>) t -> {
listName.getItems().set(t.getIndex(), t.getNewValue());
listName.getSelectionModel().clearAndSelect(t.getIndex());
});
}
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);
}
@Test
public void selectListItemCheckBoxSelectedSelected() {
ListView<?> listViewNode = (ListView<?>) getPrimaryStage().getScene().getRoot().lookup(".list-view");
Item x = (Item) listViewNode.getItems().get(2);
x.setOn(true);
IJavaFXElement item = listView.findElementByCssSelector(".::select-by-properties('{\"select\":\"Item 3\"}')");
IJavaFXElement cb = item.findElementByCssSelector(".::editor");
cb.marathon_select("checked");
new Wait("Wait for list item check box to be selected") {
@Override
public boolean until() {
String selected = cb.getAttribute("selected");
return selected.equals("true");
}
};
}
@Override
public void start(Stage primaryStage) throws Exception {
final ListView<String> listView = new ListView<String>();
listView.setItems(FXCollections.observableArrayList("Row 1", "Row 2", "Long Row 3", "Row 4", "Row 5", "Row 6", "Row 7",
"Row 8", "Row 9", "Row 10", "Row 11", "Row 12", "Row 13", "Row 14", "Row 15", "Row 16", "Row 17", "Row 18",
"Row 19", "Row 20", "Row 21", "Row 22", "Row 23", "Row 24", "Row 25"));
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
Button button = new Button("Debug");
button.setOnAction((e) -> {
ObservableList<Integer> selectedIndices = listView.getSelectionModel().getSelectedIndices();
for (Integer index : selectedIndices) {
ListCell cellAt = getCellAt(listView, index);
System.out.println("SimpleListViewScrollSample.SimpleListViewScrollSampleApp.start(" + cellAt + ")");
}
});
VBox root = new VBox(listView, button);
primaryStage.setScene(new Scene(root, 300, 400));
primaryStage.show();
}
private void initCheckList() {
ToolBar toolBar = new ToolBar();
toolBar.getItems().add(new Text("Check Lists"));
toolBar.setMinWidth(Region.USE_PREF_SIZE);
leftPane.setTop(toolBar);
checkListElements = checkListInfo.getCheckListElements();
checkListView = new ListView<CheckListForm.CheckListElement>(checkListElements);
checkListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
CheckListElement selectedItem = checkListView.getSelectionModel().getSelectedItem();
if (selectedItem == null) {
doneButton.setDisable(true);
return;
}
Node checkListForm = getChecklistFormNode(selectedItem, Mode.DISPLAY);
if (checkListForm == null) {
doneButton.setDisable(true);
return;
}
doneButton.setDisable(false);
ScrollPane sp = new ScrollPane(checkListForm);
sp.setFitToWidth(true);
sp.setPadding(new Insets(0, 0, 0, 10));
rightPane.setCenter(sp);
});
leftPane.setCenter(checkListView);
}
public final void availableSourcesUI(){
availableSources = new DataSources();
availableSources.update();
sourceListView = new ListView<>();
sourceListView.setOrientation(Orientation.HORIZONTAL);
sourceListView.setItems(availableSources.list);
sourceListView.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends String> ov, String old_val, String new_val) -> {
});
UIUtils.setSize(sourceListView,Main.columnWidthLEFT,64);
Label sourceDescriptionLabel = new Label("https://dev.twitter.com/overview/api");
sourceDescriptionLabel.setId("smalltext");
UIUtils.setSize(sourceDescriptionLabel,Main.columnWidthLEFT,24);
VBox availableSourcesLEFT = new VBox();
availableSourcesLEFT.getChildren().addAll(sourceListView,new Rectangle(0,3),sourceDescriptionLabel);
HBox availableSourcesBOTH = new HBox(5);
availableSourcesBOTH.getChildren().addAll(availableSourcesLEFT,new Rectangle(Main.columnWidthRIGHT,0));
grid.add(availableSourcesBOTH,0,2);
}
private Parent buildUI() {
fc = new FileChooser();
fc.getExtensionFilters().clear();
ExtensionFilter jpgFilter = new ExtensionFilter("JPG, JPEG images", "*.jpg", "*.jpeg", "*.JPG", ".JPEG");
fc.getExtensionFilters().add(jpgFilter);
fc.setSelectedExtensionFilter(jpgFilter);
fc.setTitle("Select a JPG image");
lstLabels = new ListView<>();
lstLabels.setPrefHeight(200);
Button btnLoad = new Button("Select an Image");
btnLoad.setOnAction(e -> validateUrlAndLoadImg());
HBox hbBottom = new HBox(10, btnLoad);
hbBottom.setAlignment(Pos.CENTER);
loadedImage = new ImageView();
loadedImage.setFitWidth(300);
loadedImage.setFitHeight(250);
Label lblTitle = new Label("Label image using TensorFlow");
lblTitle.setFont(Font.font(Font.getDefault().getFamily(), FontWeight.BOLD, 40));
VBox root = new VBox(10,lblTitle, loadedImage, new Label("Results:"), lstLabels, hbBottom);
root.setAlignment(Pos.TOP_CENTER);
return root;
}
@Test
public void select() {
@SuppressWarnings("unchecked")
ListView<String> listView = (ListView<String>) getPrimaryStage().getScene().getRoot().lookup(".list-view");
LoggingRecorder lr = new LoggingRecorder();
Platform.runLater(() -> {
@SuppressWarnings("unchecked")
ComboBoxListCell<String> cell = (ComboBoxListCell<String>) getCellAt(listView, 3);
Point2D point = getPoint(listView, 3);
RFXListView rfxListView = new RFXListView(listView, null, point, lr);
rfxListView.focusGained(rfxListView);
cell.startEdit();
cell.updateItem("Option 3", false);
cell.commitEdit("Option 3");
rfxListView.focusLost(rfxListView);
});
List<Recording> recordings = lr.waitAndGetRecordings(1);
Recording recording = recordings.get(0);
AssertJUnit.assertEquals("recordSelect", recording.getCall());
AssertJUnit.assertEquals("Option 3", recording.getParameters()[0]);
}
@Test
public void testCreateProfile() {
openTrafficProfilesDialog();
assertCall(
() -> {
clickOn("#create-profile-button");
},
() -> lookup("#profile-stream-name-dialog").query() != null
);
setText("#profile-stream-name-dialog-name-text-field", "Test Profile");
assertCall(
() -> {
clickOn("#profile-stream-name-dialog-ok-button");
},
() -> lookup("#profile-stream-name-dialog").query() == null
);
final ListView profileList = lookup("#traffic-profile-dialog-profiles-list-view").query();
Assert.assertTrue(profileList.getItems().contains("Test Profile.yaml"));
}
/**
* Opens the JobView with the first of the currently selected Jobs.
*
* If no Jobs are selected, then nothing happens.
*/
private void openEditJobView() {
final ListView<String> jobList = ((MainView) super.getView()).getJobsList();
final List<String> selectedJobs = jobList.getSelectionModel().getSelectedItems();
if (selectedJobs.size() == 0) {
return;
}
final MainModel model = (MainModel) super.getModel();
final MainView view = (MainView) super.getView();
final String firstJobName = selectedJobs.get(0);
final Job job = model.getJobs().get(firstJobName);
final JobController controller = new JobController(new JobModel(job));
view.getJobsList().getItems().remove(job.getName());
model.getJobs().remove(job.getName());
view.getJobsList().getSelectionModel().clearSelection();
SceneManager.getInstance().swapToNewScene(controller);
}
private void init() {
getStyleClass().setAll("autofill-text");
textField = new TextField();
listview = new ListView();
limit = 5;
filterMode = false;
//setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
// //setMinHeight(24);
// clearButton = new Button();
// clearButton.setId("button-clear");
// clearButton.setVisible(false);
// getChildren().add(clearButton);
// clearButton.setOnAction((ActionEvent actionEvent) -> {
// textbox.setText("");
// textbox.requestFocus();
// });
// textbox.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
// clearButton.setVisible(textbox.getText().length() != 0);
// });
listen();
}
public final void initializeAvailableMethodList(){
methodMap = new HashMap<>();
methodList = new ListView<>();
methodList.setOrientation(Orientation.HORIZONTAL);
UIUtils.setSize(methodList,Main.columnWidthLEFT,64);
updateAvailableMethods();
methodList.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends String> ov, String old_val, String new_val) -> {
try {
selectedMethod = (InfluenceAnalysisMethod) Class.forName(methodMap.get(new_val)).newInstance();
methodDescriptionLabel.setText(selectedMethod.getDescription());
parameterTable.setItems(selectedMethod.parameters.list);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
Logger.getLogger(EventDetectionUI.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
/**
* {@inheritDoc}
*/
@Override
public void initializeParts() {
super.initializeParts();
node = new ListView<>();
node.getStyleClass().add("simple-listview-control");
fieldLabel = new Label(field.labelProperty().getValue());
node.setItems(field.getItems());
node.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
for (int i = 0; i < field.getItems().size(); i++) {
if (field.getSelection().contains(field.getItems().get(i))) {
node.getSelectionModel().select(i);
} else {
node.getSelectionModel().clearSelection(i);
}
}
}
/**
* Provide a callback that sets the given context menu on each cell, if and
* only if the constraint given passes. If the constraint is null, it will
* always pass.
* <p/>
* @param <T> the generic type of the cell.
* @param contextMenu the context menu to show.
* @param cellFactory the cell factory to use.
* @param constraint the constraint placed on showing the context menu - it
* will only be shown if this constraint passes, or it is null.
* @return a callback that sets the given context menu on each cell.
*/
public static <T> Callback<ListView<T>, ListCell<T>> forListView(final ContextMenu contextMenu, final Callback<ListView<T>, ListCell<T>> cellFactory,
final Constraint<T> constraint) {
return new Callback<ListView<T>, ListCell<T>>() {
@Override
public ListCell<T> call(ListView<T> listView) {
final ListCell<T> cell = cellFactory == null ? new DefaultListCell<T>() : cellFactory.call(listView);
cell.itemProperty().addListener(new ChangeListener<T>() {
@Override
public void changed(ObservableValue<? extends T> ov, T oldVal, T newVal) {
if(newVal == null || (constraint != null && !constraint.isTrue(newVal))) {
cell.setContextMenu(null);
}
else {
cell.setContextMenu(contextMenu);
}
}
});
return cell;
}
};
}
void loadEpisodes(EpisodeList episodesTmp) {
Platform.runLater(() -> {
episodes.setAll(episodesTmp.episodes());
episodeList = new ListView<>();
episodeList.setItems(episodes);
episodeList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
episodeList.setOnMouseClicked(event -> {
int selSize = episodeList.getSelectionModel().getSelectedIndices().size();
this.setCheckBoxStatus(selSize, episodes.size());
});
});
Platform.runLater(() -> {
VBox.setVgrow(episodeList, Priority.ALWAYS);
episodeBox.getChildren().setAll(episodeList);
});
}
@Override
public TemplateGuiActionsHandler<KafkaListenerConfig> createListenerConfigListViewActionHandler(AnchorPane rightContentPane,
TabPane masterTabPane,
Tab tab,
ListView<KafkaListenerConfig> listView,
ListView<KafkaTopicConfig> topicConfigListView,
ControllerProvider repository) {
return new ListenerConfigGuiActionsHandler(new TabPaneSelectionInformer(masterTabPane, tab),
new ListViewActionsHandler<>(interactor, listView),
modelDataProxy,
repository,
rightContentPane,
topicConfigListView,
applicationPorts.getListeners(),
new ToFileSaver(interactor));
}
/**
* Select value example. Implement whatever technique you want to change value of the NaviSelect
*/
private void selectEmail(NaviSelect<Email> navi) {
Stage dialog = new Stage(StageStyle.UTILITY);
dialog.setTitle("Choose person");
ListView<Email> listview = new ListView<>(FXCollections.observableArrayList(
new Email("[email protected]", "John Doe"),
new Email("[email protected]", "Jane Doe"),
new Email("[email protected]", "Some Dude")
));
listview.setOnMouseClicked(event -> {
Email item = listview.getSelectionModel().getSelectedItem();
if (item != null) {
navi.setValue(item);
dialog.close();
}
});
dialog.setScene(new Scene(listview));
dialog.setWidth(navi.getWidth());
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.setHeight(100);
dialog.showAndWait();
}
@Override
public ModelConfigObject selectedObject() {
final Tab selectedTab = tabPane.getSelectionModel().getSelectedItem();
final ListView<?> listView = (ListView<?>) selectedTab.getContent();
if (listView == brokersListView) {
return brokersListView.getSelectionModel().getSelectedItem();
} else if (listView == topicsListView) {
return topicsListView.getSelectionModel().getSelectedItem();
} else if (listView == messagesListView) {
return messagesListView.getSelectionModel().getSelectedItem();
} else if (listView == listenersListView) {
return listenersListView.getSelectionModel().getSelectedItem();
}
return null;
}
public ListenerConfigGuiActionsHandler(TabPaneSelectionInformer tabSelectionInformer,
ListViewActionsHandler<KafkaListenerConfig> listViewActionsHandler,
ModelDataProxy modelDataProxy,
ControllerProvider controllerProvider,
AnchorPane parentPane,
ListView<KafkaTopicConfig> topicConfigs,
Listeners activeConsumers,
ToFileSaver toFileSaver) {
super(tabSelectionInformer, listViewActionsHandler);
this.listViewActionsHandler = listViewActionsHandler;
this.modelDataProxy = modelDataProxy;
this.controllerProvider = controllerProvider;
this.parentPane = parentPane;
this.topicConfigs = topicConfigs;
this.activeConsumers = activeConsumers;
this.fromPojoConverter = new FromPojoConverter(modelDataProxy);
this.toFileSaver = toFileSaver;
}
public TopicConfigGuiActionsHandler(TabPaneSelectionInformer tabSelectionInformer,
ListViewActionsHandler<KafkaTopicConfig> listViewActionsHandler,
ModelDataProxy modelDataProxy,
ControllerProvider controllerProvider,
AnchorPane parentPane,
ListView<KafkaBrokerConfig> brokerConfigs) {
super(tabSelectionInformer, listViewActionsHandler);
this.listViewActionsHandler = listViewActionsHandler;
this.modelDataProxy = modelDataProxy;
this.controllerProvider = controllerProvider;
this.parentPane = parentPane;
this.brokerConfigs = brokerConfigs;
this.fromPojoConverter = new FromPojoConverter(modelDataProxy);
}
public SenderConfigGuiActionsHandler(TabPaneSelectionInformer tabSelectionInformer,
ListViewActionsHandler<KafkaSenderConfig> listViewActionsHandler,
ModelDataProxy modelDataProxy,
ControllerProvider controllerProvider,
AnchorPane parentPane,
ListView<KafkaTopicConfig> topicConfigs,
KafkaMessageSender sender) {
super(tabSelectionInformer, listViewActionsHandler);
this.listViewActionsHandler = listViewActionsHandler;
this.modelDataProxy = modelDataProxy;
this.controllerProvider = controllerProvider;
this.parentPane = parentPane;
this.sender = sender;
this.topicConfigs = topicConfigs;
this.fromPojoConverter = new FromPojoConverter(modelDataProxy);
}
@Override
public ControllerProvider createFor(TabPane leftViewTabPane,
ListView<KafkaBrokerConfig> brokersListView,
ListView<KafkaTopicConfig> topicsListView,
ListView<KafkaSenderConfig> messagesListView,
ListView<KafkaListenerConfig> listenersListView) {
final ModelConfigObjectsGuiInformer guiInformer = new DefaultModelConfigObjectsGuiInformer(leftViewTabPane,
brokersListView,
topicsListView,
messagesListView,
listenersListView);
return new DefaultControllerProvider(guiInformer,
statusChecker,
syntaxHighlightingConfigurator,
kafkaClusterProxies,
applicationSettings,
restartables);
}
/**
* *
* Present a dialog allowing user to select an entry from a list of
* available files.
*
* @param names list of filenames to choose from
* @return the selected element text or null if nothing was selected
*/
public static String getSelection(final String[] names) {
final Alert dialog = new Alert(Alert.AlertType.CONFIRMATION);
final ObservableList<String> q = FXCollections.observableArrayList(names);
final ListView<String> nameList = new ListView<>(q);
nameList.setCellFactory(p -> new DraggableCell<>());
nameList.setEditable(false);
nameList.setOnMouseClicked(event -> {
if (event.getClickCount() > 1) {
dialog.setResult(ButtonType.OK);
}
});
ButtonType removeButton = new ButtonType("Remove");
dialog.getDialogPane().setContent(nameList);
dialog.getButtonTypes().add(removeButton);
dialog.setResizable(false);
dialog.setTitle("Preferences");
dialog.setHeaderText("Select a preference to load.");
// The remove button has been wrapped inside the btOk, this has been done because any ButtonTypes added
// to an alert window will automatically close the window when pressed.
// Wrapping it in another button can allow us to consume the closing event and keep the window open.
final Button btOk = (Button) dialog.getDialogPane().lookupButton(removeButton);
btOk.addEventFilter(ActionEvent.ACTION, event -> {
JsonIO.deleteJsonPreference(nameList.getSelectionModel().getSelectedItem());
q.remove(nameList.getSelectionModel().getSelectedItem());
nameList.setCellFactory(p -> new DraggableCell<>());
dialog.getDialogPane().setContent(nameList);
event.consume();
});
final Optional<ButtonType> option = dialog.showAndWait();
if (option.isPresent() && option.get() == ButtonType.OK) {
return nameList.getSelectionModel().getSelectedItem();
}
return null;
}
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);
}
private void initializeOutputDestinations(){
removeOutputDestinationsButton.disableProperty().bind(outputDestinationsListView.getSelectionModel().selectedItemProperty().isNull());
editOutputDestinationsButton.disableProperty().bind(outputDestinationsListView.getSelectionModel().selectedItemProperty().isNull());
outputDestinationsListView.setItems(resultsDAO.listReportDestinations());
outputDestinationsListView.setEditable(false);
outputDestinationsListView.setCellFactory((ListView<ReportDestination> listView) -> new OutputPortalListCell());
// If empty, create a default local file output
if(resultsDAO.listReportDestinations().isEmpty()) {
ReportDestination op = new ReportDestination();
op.setName(System.getProperty("user.home"));
op.setBasePath(System.getProperty("user.home"));
op.setOutputProtocol(FileTransferTypes.LOCAL);
resultsDAO.saveReportDestination(op);
}
outputDestinationsListView.setOnMouseClicked((MouseEvent click) -> {
if (click.getClickCount() == 2) {
ReportDestination sp = outputDestinationsListView.getSelectionModel().selectedItemProperty().getValue();
editOutputDestination(sp);
}
});
}
public OnScreenMenu(GUIInterface gui) {
this.gui = gui;
menu = new ListView<>(menuItems);
gameMenu = new ListView(games);
addMenuListeners(menu);
addMenuListeners(gameMenu);
getChildren().addAll(menu, gameMenu);
gameMenu.setVisible(false);
setVisible(false);
}
private void copySelectedItems(final ListView<Object> list, final String dataType) {
ObservableList<Object> selectedItems = list.getSelectionModel().getSelectedItems();
AbstractAttributeInteraction<?> interaction = AbstractAttributeInteraction.getInteraction(dataType);
StringBuilder buffer = new StringBuilder();
selectedItems.stream().map(item -> {
if (item == null) {
buffer.append(NO_VALUE_TEXT);
} else {
buffer.append(interaction.getDisplayText(item));
}
return item;
}).forEach(_item -> buffer.append("\n"));
ClipboardUtilities.copyToClipboard(buffer.toString());
}
/**
* Select the current/new selection
*
* @param container The list view in which the selection should be updated
* @param newSelection The current/new selection
*/
private void updateNewSelection(ListView<CompactListElement<E>> container, ListWidgetSelection<E> newSelection) {
// select the new element
Optional.ofNullable(newSelection).map(ListWidgetSelection::getSelection).ifPresent(selection -> {
final int newValueIndex = getControl().getElements().indexOf(selection);
container.getSelectionModel().select(newValueIndex);
});
}
public Point2D getPoint(ListView<?> listView, int index) {
Set<Node> cells = listView.lookupAll(".list-cell");
for (Node node : cells) {
ListCell<?> cell = (ListCell<?>) node;
if (cell.getIndex() == index) {
Bounds bounds = cell.getBoundsInParent();
return cell.localToParent(bounds.getWidth() / 2, bounds.getHeight() / 2);
}
}
return null;
}
@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;
}