Reputation: 107
I have a table view that I add row manually and I want to know before to add a row if that record that will be add it is already in the table.
Upvotes: 2
Views: 3492
Reputation: 11
This works for me
Boolean checkItemAdded = table.getitems().stream().anyMatch(itemCheck->itemName.equals(itemCheck.getItem)));
//ItemName can be a string from a component like a ListView. Then:
If(!CheckItemAdded) { table.getItems().addAll(); }
Else
{
//enter code here
}
Upvotes: 1
Reputation: 14731
James_D is saying that you have to add @Override public boolean equals(Object obj)
method in your class. This will allow you to use default List contains()
function so you can just do something like this in your controller code
if(!table.getItems().contains(newObj))
table.getItems().add(newObj);
Here is example code:
public void start(Stage primaryStage) throws Exception {
ObservableList<MyObject> items = FXCollections.observableArrayList(
new MyObject("Robert"),
new MyObject("Nick"),
new MyObject("John"),
new MyObject("Kate"));
TableView<MyObject> table = new TableView<>();
table.setItems(items);
TableColumn<MyObject, String> column = new TableColumn<>("Column Name");
column.setCellValueFactory(new PropertyValueFactory<>("name"));
table.getColumns().addAll(column);
table.setItems(items);
TextField textField = new TextField();
Button button = new Button("Add");
button.setOnMouseClicked(event -> {
MyObject newObj = new MyObject(textField.getText());
if(!table.getItems().contains(newObj)){
table.getItems().addAll(newObj);
}
});
VBox root = new VBox();
root.getChildren().addAll(table, textField, button);
primaryStage.setScene(new Scene(root, 600, 475));
primaryStage.show();
}
public static class MyObject {
private String name;
public MyObject(String name) {
setName(name);
}
@Override
public boolean equals(Object obj) {
return obj instanceof MyObject &&
((MyObject) obj).name.equals(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And it will be a propper way to go, but if you can't change objects class you can always use this or similar helper function.
public static boolean contains(TableView<MyObject> table, MyObject obj){
for(MyObject item: table.getItems())
if (item.getName().equals(obj.getName()))
return true;
return false;
}
Upvotes: 5