I'm attempting to bind between a ListView where more than one item can be selected and a ObjectProperty. When an item is selected, I want to filter a TableView column accordingly:
With the two lower filters (Components, Details), I do the binding like this:
ObjectProperty<Predicate<Log>> detailsSearchFilter = new SimpleObjectProperty<>();
TextField detailsSearchField = new TextField();
detailsSearchField.setPromptText("e.g. finished initializing");
detailsSearchFilter.bind(Bindings.createObjectBinding(() ->
log -> log.getDetails().toLowerCase().contains(detailsSearchField.getText().toLowerCase()),
detailsSearchField.textProperty()
));
Then later adding the logical operator method and() in order to be able to combine all filters:
logFilteredList.predicateProperty().bind(Bindings.createObjectBinding(() ->
detailsSearchFilter.get().and(componentSearchFilter.get()).and(sourceFilter.get()),
detailsSearchFilter, componentSearchFilter, sourceFilter
));
For the other two ListView filters, I was thinking to do something like this:
private final static String[] sources = new String[]{"ECS","IISNode","PrismWebServer"};
ListView<String> sourceList = new ListView<>();
ObservableList sourceItems = FXCollections.observableArrayList(sources);
sourceList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
sourceList.getItems().addAll(sources);
ListView<String> selected = new ListView<>();
sourceList.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
selected.setItems(sourceList.getSelectionModel().getSelectedItems());
System.out.println(Arrays.toString(selected.getItems().toArray()));
});
So the selected list now includes all values that are currently selected.
How do I bind the sourceFilter with all values of the selected list?
I was thinking of iterating through each value in the list and binding this way:
sourceFilter.bind(Bindings.createObjectBinding(() ->
log -> log.getSource().toLowerCase().contains(selected.getItems().get(i).toLowerCase()),
sourceList.selectionModelProperty()
));
But it seems not very elegant and I'm not sure I'm using the selectionModelProperty in the right way.
The selectionModelProperty only triggers changes when the selectionModel is replaced which usually doesn't happen. The dependency should be to sourceList.getSelectionModel().getSelectedItems().
Furthermore the way I understand it you should query, if the Log's source is among the selected items, not if the source string contains some part of the string at some position in the selected items list.
Also note that using a ListView just for storing the data should be avoided and for large lists it's much more efficient to do the contains checks on a Set instead of a List.
You could use code like this:
ObjectBinding<Predicate<Log>> binding = new ObjectBinding<Predicate<String>>() {
private final Set<String> strings = new HashSet<>();
{
sourceList.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<String>() {
#Override
public void onChanged(ListChangeListener.Change<? extends String> c) {
boolean changed = false;
// modify set on selection change
while (c.next()) {
if (c.wasRemoved()) {
changed = true;
c.getRemoved().stream().map(String::toLowerCase).forEach(strings::remove);
}
if (c.wasAdded()) {
changed = true;
c.getAddedSubList().stream().map(String::toLowerCase).forEach(strings::add);
}
}
if (changed) {
invalidate();
}
}
});
}
#Override
protected Predicate<Log> computeValue() {
return log -> strings.contains(log.getSource().toLowerCase());
}
};
sourceFilter.bind(binding);
Related
I would to ask why does IndexOutOfBoundsException appear when I try to delete the first row from the table view of supplement which is index 0. I am using a button to delete the row
Update: update the code to have a minimal reproducible example
SupplementTest.java
public class SupplementTest extends Application {
WindowController windowGUI = new WindowController();
Stage stageGUI;
Scene sceneGUI;
#Override
public void start(Stage primaryStage) throws IOException {
FXMLLoader assignment2 = new FXMLLoader(getClass().getResource("SupplementFXML.fxml"));
Parent fxmlFile = assignment2.load();
try {
stageGUI = primaryStage;
windowGUI.initialize();
sceneGUI = new Scene(fxmlFile, 250, 350);
stageGUI.setScene(sceneGUI);
stageGUI.setTitle("Supplement");
stageGUI.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
WindowController.java
public class WindowController {
Stage newWindow = new Stage();
boolean deleteSupplement;
#FXML
private GridPane primaryGrid = new GridPane();
#FXML
private Label supplementLabel = new Label();
#FXML
private Button deleteBtn = new Button(), addBtn = new Button();
public TableView<Supplement> supplementView = new TableView<>();
int suppIndex;
ArrayList<Supplement> supplementList = new ArrayList<>();
// initialize Method
public void initialize() {
newWindow.initModality(Modality.APPLICATION_MODAL);
newWindow.setOnCloseRequest(e -> e.consume());
initializeWindow();
updateSupplementList();
}
public void initializeWindow() {
deleteSupplement = false;
TableColumn<Supplement, String> suppNameColumn = new TableColumn<>("Name");
suppNameColumn.setCellValueFactory(new PropertyValueFactory<>("supplementName"));
TableColumn<Supplement, Double> suppCostColumn = new TableColumn<>("Weekly Cost");
suppCostColumn.setCellValueFactory(new PropertyValueFactory<>("weeklyCost"));
supplementView.getColumns().addAll(suppNameColumn, suppCostColumn);
supplementView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
suppIndex = supplementView.getSelectionModel().getSelectedIndex();
addBtn.setOnAction(e -> {
supplementList.add(new Supplement("Test1", 10));
supplementList.add(new Supplement("Test2", 20));
supplementList.add(new Supplement("Test3", 15));
updateSupplementList();
});
// remove button
deleteBtn.setOnAction(e -> {
deleteSupplement = true;
deleteSupplement();
});
}
public void updateSupplementList() {
supplementView.getItems().clear();
if (supplementList.size() > 0) {
for(int i = 0; i < supplementList.size(); i++) {
Supplement supplement = new Supplement(supplementList.get(i).getSupplementName(),
supplementList.get(i).getWeeklyCost());
supplementView.getItems().add(supplement);
}
}
}
public void deleteSupplement() {
try {
ObservableList<Supplement> supplementSelected, allSupplement;
allSupplement = supplementView.getItems();
supplementSelected = supplementView.getSelectionModel().getSelectedItems();
supplementSelected.forEach(allSupplement::remove);
supplementList.remove(suppIndex);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Supplement.java
public class Supplement implements Serializable {
private String supplementName;
private double weeklyCost;
public Supplement() {
this.supplementName = "";
this.weeklyCost = 0.00;
}
public Supplement(String suppName, double weeklyCost) {
this.supplementName = suppName;
this.weeklyCost = weeklyCost;
}
public String getSupplementName() {
return supplementName;
}
public double getWeeklyCost() {
return weeklyCost;
}
public void setSupplementName(String supplementName) {
this.supplementName = supplementName;
}
public void setWeeklyCost(double weeklyCost) {
this.weeklyCost = weeklyCost;
}
}
How do I fix it so that when I delete any index in the table view the IndexOutOfBoundsException does not appear?
It's difficult to know for certain what is causing the exception, because your code is both incomplete (so no-one here can copy, paste, and run it to reproduce the error), and very confusing (it is full of seemingly-unnecessary code). However:
You seem to be doing two different things to delete the selected item(s) from the table:
supplementSelected = supplementView.getSelectionModel().getSelectedItems();
supplementSelected.forEach(allSupplement::remove);
which is an attempt to delete all selected items (though I don't believe it will work if more than one item is selected)
and
supplementList.remove(suppIndex);
which will delete the selected item, as defined by the selected index property in the selection model. (It is the currently selected item in a single selection model, or the last selected item in a multiple selection model, or -1 if nothing is selected.)
The latter will not work, because you only ever set suppIndex in your initialization code:
public void initializeWindow() {
// ...
suppIndex = supplementView.getSelectionModel().getSelectedIndex();
// ...
}
Of course, when this code is executed, the user has not had a chance to selected anything (the table isn't even displayed at this point), so nothing is selected, and so suppIndex is assigned -1. Since you never change it, it is always -1, and so when you call
supplementList.remove(suppIndex);
you get the obvious exception.
If you are only supporting single selection, and want to delete the currently selected item (or the last selected item in multiple selection), just get the selection at the time. You probably still want to check something is selected:
public void deleteSupplement() {
int selectedIndex = supplementView.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0) {
supplementView.getItems().remove(selectedIndex);
}
}
A slight variation on this, which I think is preferable, is to work with the actual object instead of its index:
public void deleteSupplement() {
Supplement selection = supplementView.getSelectionModel().getSelectedItem();
if (selection != null) {
supplementView.getItems().remove(selection);
}
}
Now, of course (in a theme that is common to a lot of your code), you can remove suppIndex entirely; it is completely redundant.
If you want to support multiple selection, and delete all selected items, then the code you currently have for that will cause an issue if more than one item is selected. The problem is that if a selected item is removed from the table's items list, it will also be removed from the selection model's selected items list. Thus, the selected items list (supplementSelected) in your code changes while you are iterating over it with forEach(...), which will throw a ConcurrentModificationException.
To avoid this, you should copy the list of selected items into another list, and remove those items:
public void deleteSupplement() {
List<Supplement> selectedItems
= new ArrayList<>(supplementView.getSelectionModel().getSelectedItems());
supplementView.getItems().removeAll(selectedItems);
}
Of course, this code also works with single selection (when the list is always either length 0 or length 1).
To address a couple of other issues: there is really no point in keeping a separate list of Supplement items. The table already keeps that list, and you can reference it at any time with supplementView.getItems(). (If you wanted to reference the list elsewhere, e.g. in a model in a MVC design, you should make sure that there is just a second reference to the existing list; don't create a new list.)
In particular, you should not rebuild the table entirely from scratch every time you add a new item to the list. Get rid of the redundant supplementList entirely from your code. Get rid of updateSupplementList() entirely; it is firstly doing way too much work, and secondly (and more importantly) will replace all the existing items just because you add a new one. This will lost important information (for example it will reset the selection).
To add new items, all you need is
addBtn.setOnAction(e -> {
supplementView.getItems().add(new Supplement("Test1", 10));
supplementView.getItems().add(new Supplement("Test2", 20));
supplementView.getItems().add(new Supplement("Test3", 15));
});
There are various other parts of your code that don't make any sense, such as:
The deleteSupplement variable. This seems to have no purpose.
The try-catch in the deleteSupplement method. The only exceptions that can be thrown here are unchecked exceptions caused by programming logic errors (such as the one you see). There is no point in catching those; you need to fix the errors so the exceptions are not thrown.
The #FXML annotations. You should never initialize fields that are annotated #FXML. This annotation means that the FXMLLoader will initialize these fields. In this case (as far as I can tell) these are not even associated with an FXML file at all, so the annotation should be removed.
i have a data model "Rule"
A Rule consists of 1-x String parts saved as a List and an boolean value weather the rule is active or not.
To show this in my UI i want to add a TableView with 2 Columns.
Column 1 should display the Rule Text as a whole, but heavily customized. In the cell i add a textfield for each rule part which then get binded to the StrinProperty (Thats why i need a List of String Properties.
The 2. column should display a checkbox to activate or deactivate the rule (this is no problem an works fine)
Before my rule Model had the boolean isActive flag i used a Listview which had the whole Rule model class as Object. I made my own ListCell implementation and overrode updateItem(Object item, boolean isEmpty) to customize the cell to look like this:
I want the tablecell in column 1 to look exactly how the listcell in my listview looked.
Because ListCell and Tablecell both inherit from IndexedCell i saw no problem in my way of changing the visual of the cell.
My problem is to bind the new datamodel to the table:
private TableView<Rule> tvRules;
this.tvRules = new TableView<Rule>();
this.tvRules.setPrefSize(GuiCore.prefWidth * 0.32, GuiCore.prefHeight * 0.32);
this.tvRules.setEditable(true);
headerBoxLbl = new Label("Active");
headerBox = new CheckBox();
headerBoxLbl.setGraphic(headerBox);
headerBoxLbl.setContentDisplay(ContentDisplay.RIGHT);
headerBox.setOnAction(e -> this.changeAllActiveBoxes());
rulePartsColumn = new TableColumn<Rule, List<SimpleStringProperty>>("Rule");
rulePartsColumn.setCellFactory((callback) -> new RuleTableCell());
rulePartsColumn.setCellValueFactory(cellData -> cellData.getValue().getRulePartsProperty());
rulePartsColumn.setResizable(false);
rulePartsColumn.prefWidthProperty().bind(this.widthProperty().multiply(0.8));
isActiveColumn = new TableColumn<Rule, Boolean>();
isActiveColumn.setCellValueFactory(cellData -> cellData.getValue().getIsActiveProperty());
isActiveColumn.setCellFactory(cellData -> new CheckBoxTableCell<>());
isActiveColumn.setResizable(false);
isActiveColumn.prefWidthProperty().bind(this.widthProperty().multiply(0.2));
isActiveColumn.setStyle( "-fx-alignment: CENTER;");
isActiveColumn.setGraphic(headerBoxLbl);
this.tvRules.getColumns().addAll(rulePartsColumn, isActiveColumn);
As you see i create 2 Columns with the TableDataType Rule, one with Boolean type and one with the List as Data type.
The problem ist that i dont get the binding of the rulePartsColumn to the rule Model to work:
I really dont know how to bind this so in the cell i can work with a List of StringProperties (or SimpleStringProperties).
For reference my Model class Rule:
public class Rule {
private SimpleListProperty<SimpleStringProperty> ruleParts;
private SimpleBooleanProperty isActive;
public Rule() {
this(true, Arrays.asList("", "=", ""));
}
public Rule(final boolean isActive, final List<String> ruleParts) {
this.isActive = new SimpleBooleanProperty(isActive);
this.ruleParts = new SimpleListProperty<SimpleStringProperty>(FXCollections.observableArrayList());
for(int i = 0; i < ruleParts.size(); i++) {
this.ruleParts.add(new SimpleStringProperty(ruleParts.get(i)));
}
}
public SimpleListProperty<SimpleStringProperty> getRulePartsProperty() {
return this.ruleParts;
}
public List<SimpleStringProperty> getRulePartsProperties() {
return (List<SimpleStringProperty>)this.ruleParts;
}
public List<String> getRuleParts() {
List<String> parts = new ArrayList<String>();
for(int i = 0; i < this.ruleParts.size(); i++) {
parts.add(this.ruleParts.get(i).get());
}
return parts;
}
public SimpleBooleanProperty getIsActiveProperty() {
return this.isActive;
}
public boolean isActive() {
return isActive.get();
}
public void setActive(boolean isActive) {
this.isActive.set(isActive);
}
}
Thanks in advance
Basically, I wanted to know if I could create a tree and custom it on javaFX...
I tried to do it, but couldn't do anything so far with this code...
public class Main{
......
public Main() throws Exception{
......
// TreeView created
TreeView tv = (TreeView) fxmlLoader.getNamespace().get("treeview");
TreeItem<String> rootItem = new TreeItem<String>("liss");
rootItem.setExpanded(true);
tv.setRoot(rootItem);
/*for (int i = 1; i < 6; i++) {
TreeItem<String> item = new TreeItem<String> ("Message" + i);
rootItem.getChildren().add(item);
}
TreeItem<String> item = new TreeItem<String> ("MessageWoot");
rootItem.getChildren().add(item);
*/
//tv.setEditable(true);
tv.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() {
#Override
public TreeCell<String> call(TreeView<String> arg0) {
// custom tree cell that defines a context menu for the root tree item
return new MyTreeCell();
}
});
stage.show();
}
//
private static class MyTreeCell extends TextFieldTreeCell<String> {
private ContextMenu addMenu = new ContextMenu();
public boolean clickedFirstTime = false;
public MyTreeCell() {
// instantiate the root context menu
MenuItem addMenuItem = new MenuItem("Expand");
addMenu.getItems().add(addMenuItem);
addMenuItem.setOnAction(new EventHandler() {
public void handle(Event t) {
TreeItem n0 =
new TreeItem<String>("'program'");
TreeItem n1 =
new TreeItem<String>("<identifier>");
TreeItem n2 =
new TreeItem<String>("body");
getTreeItem().getChildren().add(n0);
getTreeItem().getChildren().add(n1);
getTreeItem().getChildren().add(n2);
}
});
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
// if the item is not empty and is a root...
//if (!empty && getTreeItem().getParent() == null && this.clickedFirstTime) {
System.out.println("UPDATEITEM -> clickedFirstTime : "+this.clickedFirstTime);
if (!this.clickedFirstTime) {
System.out.println("WOOT");
setContextMenu(addMenu);
this.clickedFirstTime = true;
}
}
}
And I'm questioning myself if this is the right "technology" which will solve what I'm trying to do...
What's my objective in this?
Firstly, I'm looking to add or delete a treeItem. I must say that a certain treeItem may be added only once or any N times, like a restriction (for example: treeItem < 6 for a certain level scope and a certain path of the root of tree view).
Secondly, make some treeItem editable and others not editable! When it is Editable, you may pop up something for the user in order to insert some input for example!
Is it possible ?
I saw the tutorial from https://docs.oracle.com/javafx/2/ui_controls/tree-view.htm#BABJGGGF but I'm really confused with this tutorial ... I don't really understand the cell factory mechanism... The fact that he does apply to TreeView when i want only a certain TreeItem... Or how could I control that effect/behaviour ?
I mean, I'm really really lost with TreeView. Probably, TreeView isn't what I'm looking for ...
P.S.: I know that I cannot apply any visual effect or add menus to a tree items and that i use a cell factory mechanism to overcome this obstacle. Just I don't understand the idea and how could I do it !
Sure this is the right "technology", if you want to use JavaFX. You should probably use a more complex type parameter for TreeItem however. You can use your a custom TreeCell to allow the desired user interaction.
This example allows adding children and removing nodes via context menu (unless the content is "nocontext") as well as editing the content (as long as the content is not "noedit"); on the root node the delete option is disabled:
tv.setEditable(true);
tv.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() {
private final MyContextMenu contextMenu = new MyContextMenu();
private final StringConverter converter = new DefaultStringConverter();
#Override
public TreeCell<String> call(TreeView<String> param) {
return new CustomTreeCell(contextMenu, converter);
}
});
public class CustomTreeCell extends TextFieldTreeCell<String> {
private final MyContextMenu contextMenu;
public CustomTreeCell(MyContextMenu contextMenu, StringConverter<String> converter) {
super(converter);
if (contextMenu == null) {
throw new NullPointerException();
}
this.contextMenu = contextMenu;
this.setOnContextMenuRequested(evt -> {
prepareContextMenu(getTreeItem());
evt.consume();
});
}
private void prepareContextMenu(TreeItem<String> item) {
MenuItem delete = contextMenu.getDelete();
boolean root = item.getParent() == null;
if (!root) {
delete.setOnAction(evt -> {
item.getParent().getChildren().remove(item);
contextMenu.freeActionListeners();
});
}
delete.setDisable(root);
contextMenu.getAdd().setOnAction(evt -> {
item.getChildren().add(new TreeItem<>("new item"));
contextMenu.freeActionListeners();
});
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setContextMenu("nocontext".equals(item) ? null : contextMenu.getContextMenu());
setEditable(!"noedit".equals(item));
}
}
}
public class MyContextMenu {
private final ContextMenu contextMenu;
private final MenuItem add;
private final MenuItem delete;
public MyContextMenu() {
this.add = new MenuItem("add child");
this.delete = new MenuItem("delete");
this.contextMenu = new ContextMenu(add, delete);
}
public ContextMenu getContextMenu() {
return contextMenu;
}
public MenuItem getAdd() {
return add;
}
public MenuItem getDelete() {
return delete;
}
/**
* This method prevents memory leak by setting all actionListeners to null.
*/
public void freeActionListeners() {
this.add.setOnAction(null);
this.delete.setOnAction(null);
}
}
Of course more complex checks can be done in the updateItem and prepareContextMenu and different user interactions can be supported (TextFieldTreeCell may not be the appropriate superclass for you; You could use a "normal" TreeCell and show a different stage/dialog to edit the item when the user selects a MenuItem in the context menu).
Some clarification about cell factories
Cell factories are used to create the cells in a class that displays data (e.g. TableColumn, TreeView, ListView). When such a class needs to display content, it uses it's cell factory to create the Cells that it uses to display the data. The content displayed in such a cell may be changed (see updateItem method).
Example
(I'm not 100% sure this is exactly the way it's done, but it should be sufficiently close)
A TreeView is created to display a expanded root node with 2 non expanded children.
The TreeView determines that it needs to display 3 items for the root node and it's 2 children. The TreeView therefore uses it's cell factory to creates 3 cells and adds them to it's layout and assigns the displayed items.
Now the user expands the first child, which has 2 children of it's own. The TreeView determines that it needs 2 more cells to display the items. The new cells are added at the end of the layout for efficiency and the items of the cells are updated:
The cell that previously contained the last child is updated and now contains the first child of the first item.
The 2 newly added cells are updated to contain the second child of the first child and the second child of the root respecitvely.
So I decided to eliminate TreeView (because the documentation is so trash...) and, instead, I decided to implement a Webview !
Why ?
Like that, I could create an HTML document and use jstree (jquery plugin - https://www.jstree.com ) in there. It is a plugin which will create the treeview basically.
And the documentation is ten time better than treeview oracle documentation unfortunately.
Also, the possibility in creating/editing the tree with jstree is better.
Which concludes me that it was the best solution that I could figure out for me.
Also, whoever who will read me, I did a bridge with the webview and my javafx application ! It is a connection between my HTML document and the java application (Read more here - https://blogs.oracle.com/javafx/entry/communicating_between_javascript_and_javafx).
Hope It will help more people.
I am creating application in javaFX, Where I have used Treeview
with CheckBoxTreeItem of String as its nodes.
I want to get all checked item in the treeview , How do I achieve that?
Heres code :
private TreeView<String> treeView_businessAreas;
Set<String> businessAreas = config.getBusinessAreas();
CheckBoxTreeItem<String> item = null;
for (String businessArea : businessAreas) {
item = new CheckBoxTreeItem<>(businessArea);
root.getChildren().add(item);
}
treeView_businessAreas.setRoot(root);
This is the code that you need:
treeView_businessAreas.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<TreeItem>() {
#Override
public void onChanged(Change<? extends TreeItem> change) {
ObservableList<TreeItem<String>> allSelectedItems = (ObservableList<TreeItem<String>>) treeView_businessAreas.getSelectionModel().getSelectedItems();
//DO SOMETHING HERE WITH THE SELECTED ITEMS
}
});
I have problem with adding of column to TableView dynamically. The problem is, that it adds data for one cell into entire row. I think the problem could be in my callback, or in the part where I add data in tableView.
This is my callback method:
Callback<CellDataFeatures<String,String> ,ObservableValue<String>> cb;
cb = new Callback<CellDataFeatures<String,String> ,ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<String, String> param) {
return new SimpleStringProperty(param.getValue());
}
};
and this is where I add data, listOfNewValues is ArrayList which contains new String values:
ObservableList<String> addData = FXCollections.observableArrayList();
addData = aktualTable.getItems();
for(String data : listOfNewValues) {
addData.add(data);
}
aktualTable.setItems(addData);