java


Getting selected Items from a ListView | CheckBoxListCell


I want to create a simple ListView with CheckBox for each item. This has been done. Now I am looking for a way to get all selected Items from this ListView.
I have figured out that I can use the method setCellFactory() to add items when they are selected in a separate Collection and remove them when they are unselected. But I think this is an ugly way to do that.
ListView<String> listView = new ListView<>();
String[] toppings = {"Cheese", "Pepperoni", "Black Olives"};
listView.getItems().addAll(toppings);
listView.setCellFactory(CheckBoxListCell.forListView(new Callback<String, ObservableValue<Boolean>>() {
#Override
public ObservableValue<Boolean> call(String item) {
BooleanProperty observable = new SimpleBooleanProperty();
observable.addListener((obs, wasSelected, isNowSelected)
-> System.out.println("Check box for " + item + " changed from " + wasSelected + " to " + isNowSelected)
);
return observable;
}
}));
How can I get the list of selected items from the ListView?
Use this way
public void start(Stage primaryStage) {
try {
ListView<String> listView = new ListView<>();
Button button = new Button("Get");
List<String> list = new ArrayList<>();
String[] toppings = { "Cheese", "Pepperoni", "Black Olives" };
listView.getItems().addAll(toppings);
listView.setCellFactory(CheckBoxListCell.forListView(new Callback<String, ObservableValue<Boolean>>() {
#Override
public ObservableValue<Boolean> call(String item) {
BooleanProperty observable = new SimpleBooleanProperty();
observable.addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
list.add(item);
} else {
list.remove(item);
}
});
return observable;
}
}));
button.setOnAction(e -> {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
});
VBox root = new VBox();
root.setAlignment(Pos.CENTER);
root.getChildren().addAll(listView, button);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
If you add a boolean property to your model class, e.g.:
public class Topping {
private final String name ;
private final BooleanProperty selected = new SimpleBooleanProperty();
public BooleanProperty selectedProperty() {
return selected ;
}
public final boolean isSelected() {
return selectedProperty().get();
}
public final void setSelected(boolean selected) {
selectedProperty().set(selected);
}
public Topping(String name) {
this.name = name ;
}
public String getName() {
return name ;
}
#Override
public String toString() {
return getName();
}
}
and use it in the check box list cell:
listView.setCellFactory(CheckBoxListCell.forListView(Topping::selectedProperty));
then you can just create a filtered list which contains all the selected toppings:
ListView<Topping> listView = new ListView<>();
listView.getItems().addAll(new Topping("Cheese"), new Topping("Pepperoni"),
new Topping("Black Olives"));
ObservableList<Topping> selectedToppings =
listView.getItems().filtered(Topping::isSelected);
Now selectedToppings will always contain exactly the toppings that have their check boxes checked in the list view.
Unless the selected property is a part of your model you are now blending a user interaction need with your model, which I would try to avoid.
For example, if you would create two lists where you move the items from one or the other, would you still use this property or would be containment in that list be enough for you?
In your (Pizza?) example an order for once confirmed to the user should only contain toppings that are selected, it would be a strange model if your pizza order would contain all possible toppings and the kitchen would have to iterate over the list in order to find the needed toppings. This is a strong indication that the fact that it is selected is not part of the model but a user interaction item.
To avoid mixing user interface and model you could use the CheckListView of the ControlsFX library which has a CheckModel which not only allowes you to query the checked items, but also manipulate it if your logic would require to do so.

Related Links

MouseMotionListener in a Thread
Search Yahoo Answers using Jsoup
Is there a way to add a local database to a netbeans java project package?
Can I call a method which I create in another class in my current class in java?
Jdbm2 Tree index usage
Insert Large Blob with Java Cassandra Driver
outputStream writing a byteArray - XSS prevention
Android App opening url in browser not through webview in application
maven-license-plugin: Use license for parentPom for all children
Stack linkedlist with initial Capacity
How to avoid OutOfMemoryError in Android
eclipse crashes on launch
Duplicate values in eclipse debugger
Embedded Tomcat doesn't execute jsf pages
Stemming text in java [duplicate]
primefaces:row edit event not working when click on pencil icon

Categories

HOME
compiler-construction
pandas
ionic-framework
google-chrome-extension
hook
ngrx
pycharm
google-play
react-virtualized
include
stock
vmware
jsp-tags
google-docs
rsync
react-redux
sharepoint-designer
ckeditor
azure-storage-tables
cloudkit
handsontable
windows-azure-storage
static-libraries
workload-scheduler
systemc
jqwidget
code-review
excel-vba-mac
emulator
custom-wordpress-pages
java-7
microsoft-sync-framework
brunch
gitignore
tasklet
binary-data
yadcf
code-contracts
usbserial
hybridauth
openoffice.org
ghost4j
google-api-nodejs-client
restlet
swisscomdev
android-tabhost
midl
total-commander
gpx
node-sass
.net-4.6.2
babel-core
angular-resource
python-c-api
colorama
nsarray
cudafy.net
nested-sets
deadbolt-2
bstr
firebaseui
testng-dataprovider
packagist
pyke
prerequisites
qdialog
feedback
mmc
umbraco6
google-style-guide
gui-test-framework
asp.net-web-api-odata
srs
typo3-neos
coverflow
dotnetnuke-5
tws
flash-builder4.5
drools-planner
chuck
trusted
datawindow
uiviewanimation-curve
windows-phone-7.1.1
work-stealing
yui-datatable
sortable-tables
infrastructure
suppress
getresponsestream
filtered-index
multi-tier
audio-capture
exchange-server-2003
mtj
boost-smart-ptr
sustainable-pace
spec#
genealogy
signal-handling

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile