How can a choice box, checkbox, and text field be implemented into one button with JavaFX [closed] - javafx

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to create a program that can take data from a choicebox, checkbox, and text field and put it into a single textArea as output. How can I have all the information combine from one button. I have already created the choicebox, checkbox, and text fields.
-There are two text fields. One of them takes a name, and the other takes a number. The number will determine how many times the program is looped.
-The checkbox will take what kind of prefix to put in front of the name (Mr, Mrs, etc).
-The choicebox give options on what follow up statement will be given. (How was your day?, I like your hat, etc)
After clicking the button, the program would display something like this in a textArea if the number in the textField had an input of 2
"1Hello Mr. Johnson. How was your day?"
"2Hello Mr. Johnson. How was your day?"
This is what I have in the button event handler. It only implements the text fields
private class CreateButtonHandler implements EventHandler<ActionEvent> {
#Override
public void handle(ActionEvent event) {
int i = 0;
String myString = number.getText();
int foo = Integer.parseInt(myString);
do {
OutputTxtArea.setText(OutputTxtArea.getText() + (i + 1) + "Hello " + firstNameTxtFld.getText() + "\n");
} while(i<foo);
}
}

Bindings!
Things are easier to do if you separate the layout from the data and the actions, and then have the actions work on the data. This leaves the screen to just be a screen, and you're not worried about "how do I deal with getting the CheckBox values?" kind of questions.
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.jetbrains.annotations.NotNull;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Greeter extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Model model = new Model();
ChoiceBox<String> questionChoiceBox = new ChoiceBox<>(model.questionList);
TextArea textArea = new TextArea("");
textArea.textProperty().bind(model.greetingProperty());
VBox vBox = new VBox(20,
createBoundCheckBox("Miss", model.isMissProperty()),
createBoundCheckBox("Missus", model.isMissusProperty()),
createBoundCheckBox("Mister", model.isMisterProperty()),
questionChoiceBox,
createBoundTextField(model.nameProperty()),
createBoundTextField(model.loopCountProperty()),
textArea);
primaryStage.setScene(new Scene(vBox, 200, 300));
primaryStage.show();
}
#NotNull
private Node createBoundCheckBox(String label, BooleanProperty boundProperty) {
CheckBox checkBox = new CheckBox(label);
boundProperty.bind(checkBox.selectedProperty());
return checkBox;
}
private Node createBoundTextField(StringProperty boundProperty) {
TextField textField = new TextField();
boundProperty.bind(textField.textProperty());
return textField;
}
class Model {
private StringProperty loopCount = new SimpleStringProperty("");
private BooleanProperty isMister = new SimpleBooleanProperty(false);
private BooleanProperty isMissus = new SimpleBooleanProperty(false);
private BooleanProperty isMiss = new SimpleBooleanProperty(false);
private StringProperty name = new SimpleStringProperty("");
private StringProperty question = new SimpleStringProperty("");
private ObservableList<String> questionList = FXCollections.observableArrayList();
Model() {
questionList.add("How was your day?");
questionList.add("Would you like kippers for breakfast");
}
public StringProperty loopCountProperty() {
return loopCount;
}
public BooleanProperty isMisterProperty() {
return isMister;
}
public BooleanProperty isMissusProperty() {
return isMissus;
}
public BooleanProperty isMissProperty() {
return isMiss;
}
public StringProperty nameProperty() {
return name;
}
public StringProperty questionProperty() {
return question;
}
public ObservableList<String> getQuestionList() {
return questionList;
}
public ObservableValue<String> greetingProperty() {
return Bindings.createStringBinding(() -> buildGreeting(), loopCount, isMiss, isMissus, isMister, question, name);
}
private String buildGreeting() {
int howMany;
try {
howMany = Integer.parseInt(loopCount.get());
} catch (Exception e) {
return "";
}
String title = "Master of Time and Space";
if (isMiss.get()) {
title = "Miss";
}
if (isMissus.get()) {
title = "Mrs.";
}
if (isMister.get()) {
title = "Mr.";
}
String greeting = "Hello " + title + " " + name.get() + " " + question.get();
return IntStream.range(1, howMany + 1).mapToObj(idx -> idx + greeting).collect(Collectors.joining("\n"));
}
}
}
So now the layout is just a layout, and all of the controls on the screen have their value properties bound to the Model. Then the model has the code to put all the stuff together to create the result. Technically, that code should belong in some sort of business logic class, but this should at least give you the idea.
I've left out the button because it doesn't really add any meaningful functionality, and it's slightly problematic to the UI. There's no way to indicate if the result in the TextArea is current to the last button click. For instance, you could click the button, then pick another title checkbox and now the selections on the screen don't match the TextArea. But there's no way for the user to know this, and to implement it you'd probably have to go to something like the DirtyFX library.
But if you really want a button, then all you have to do is introduce a new StringProperty for the result, then have the button call Model.buildGreeting() in its EventHandler:
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.jetbrains.annotations.NotNull;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class GreeterButton extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Model model = new Model();
ChoiceBox<String> questionChoiceBox = new ChoiceBox<>(model.questionList);
TextArea textArea = new TextArea("");
textArea.textProperty().bind(model.greetingProperty());
Button button = new Button("Say Hi!");
button.setOnAction(evt -> model.updateGreeting());
VBox vBox = new VBox(20,
createBoundCheckBox("Miss", model.isMissProperty()),
createBoundCheckBox("Missus", model.isMissusProperty()),
createBoundCheckBox("Mister", model.isMisterProperty()),
questionChoiceBox,
createBoundTextField(model.nameProperty()),
createBoundTextField(model.loopCountProperty()),
button,
textArea);
primaryStage.setScene(new Scene(vBox, 200, 300));
primaryStage.show();
}
#NotNull
private Node createBoundCheckBox(String label, BooleanProperty boundProperty) {
CheckBox checkBox = new CheckBox(label);
boundProperty.bind(checkBox.selectedProperty());
return checkBox;
}
private Node createBoundTextField(StringProperty boundProperty) {
TextField textField = new TextField();
boundProperty.bind(textField.textProperty());
return textField;
}
class Model {
private StringProperty loopCount = new SimpleStringProperty("");
private BooleanProperty isMister = new SimpleBooleanProperty(false);
private BooleanProperty isMissus = new SimpleBooleanProperty(false);
private BooleanProperty isMiss = new SimpleBooleanProperty(false);
private StringProperty name = new SimpleStringProperty("");
private StringProperty question = new SimpleStringProperty("");
private StringProperty greeting = new SimpleStringProperty("");
private ObservableList<String> questionList = FXCollections.observableArrayList();
Model() {
questionList.add("How was your day?");
questionList.add("Would you like kippers for breakfast");
}
public StringProperty loopCountProperty() {
return loopCount;
}
public BooleanProperty isMisterProperty() {
return isMister;
}
public BooleanProperty isMissusProperty() {
return isMissus;
}
public BooleanProperty isMissProperty() {
return isMiss;
}
public StringProperty nameProperty() {
return name;
}
public StringProperty questionProperty() {
return question;
}
public ObservableList<String> getQuestionList() {
return questionList;
}
String buildGreeting() {
int howMany;
try {
howMany = Integer.parseInt(loopCount.get());
} catch (Exception e) {
return "";
}
String title = "Master of Time and Space";
if (isMiss.get()) {
title = "Miss";
}
if (isMissus.get()) {
title = "Mrs.";
}
if (isMister.get()) {
title = "Mr.";
}
String greeting = "Hello " + title + " " + name.get() + " " + question.get();
return IntStream.range(1, howMany + 1).mapToObj(idx -> idx + greeting).collect(Collectors.joining("\n"));
}
public void updateGreeting() {
greeting.set(buildGreeting());
}
public StringProperty greetingProperty() {
return greeting;
}
}
}

Related

TableView row selection on Mouse Middle Button click

Currently in TableView, the row selection is not happening when we click mouse middle button. The row is selected if we do right or left click. I am trying to have the feature of selecting the row on middle button click.
I am already aware that including an event handler in table row factory can fix this. But I have a custom table view with lot of custom features for my application. And this custom TableView is widely used across my application. My main problem is, I cannot ask each and every table row factory to include this fix.
I am looking for a way to do this on higher level (may be on TableView level) so that the row factory does not need to care of that.
Any ideas/help is highly appreciated.
Below is a quick example of what I am trying to achieve.
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
public class TableRowSelectionOnMiddleButtonDemo extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
ObservableList<Person> persons = FXCollections.observableArrayList();
for (int i = 0; i < 4; i++) {
persons.add(new Person("First name" + i, "Last Name" + i));
}
CustomTableView<Person> tableView = new CustomTableView<>();
TableColumn<Person, String> fnCol = new TableColumn<>("First Name");
fnCol.setCellValueFactory(param -> param.getValue().firstNameProperty());
TableColumn<Person, String> lnCol = new TableColumn<>("Last Name");
lnCol.setCellValueFactory(param -> param.getValue().lastNameProperty());
tableView.getColumns().addAll(fnCol, lnCol);
tableView.getItems().addAll(persons);
tableView.setRowFactory(new Callback<TableView<Person>, TableRow<Person>>() {
#Override
public TableRow<Person> call(TableView<Person> param) {
return new TableRow<Person>(){
{
/* This will fix my issue, but I dont want each tableView rowfactory to set this behavior.*/
// addEventHandler(MouseEvent.MOUSE_PRESSED,e->{
// getTableView().getSelectionModel().select(getItem());
// });
}
#Override
protected void updateItem(Person item, boolean empty) {
super.updateItem(item, empty);
}
};
}
});
VBox sp = new VBox();
sp.setAlignment(Pos.TOP_LEFT);
sp.getChildren().addAll(tableView);
Scene sc = new Scene(sp);
primaryStage.setScene(sc);
primaryStage.show();
}
public static void main(String... a) {
Application.launch(a);
}
/**
* My custom tableView.
* #param <S>
*/
class CustomTableView<S> extends TableView<S> {
public CustomTableView() {
// A lot of custom behavior is included to this TableView.
}
}
class Person {
private StringProperty firstName = new SimpleStringProperty();
private StringProperty lastName = new SimpleStringProperty();
public Person(String fn, String ln) {
setFirstName(fn);
setLastName(ln);
}
public String getFirstName() {
return firstName.get();
}
public StringProperty firstNameProperty() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public String getLastName() {
return lastName.get();
}
public StringProperty lastNameProperty() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
}
}
The entry point for any global custom (per-control) functionality/behavior is the control's skin. More specifically: user interaction is controlled by the skin's behavior - which unfortunately didn't make it into public scope, such that its access/modification requires to go dirty (as in accessing internal classes/methods, partly via reflection).
Assuming that such access is allowed, the steps to tweak the mouse interaction into reacting the same way for the middle as for the primary button for a TableCell are
implement a custom TableCellSkin
reflectively access its behavior
find the mousePressed handler in the behavior's inputMap
replace the original handler with a custom handler that replaces the mouseEvent coming from the middle button by a mouseEvent coming from the primary button
make the custom TableCellSkin the default by css
Note: the TableRowSkin which is responsible for handling mouseEvents in the free space at the right of the table doesn't separate out the middle button, so currently nothing to do. If that changes in future, simple apply the same trick as for the table cells.
Example:
public class TableRowCustomMouse extends Application {
public static class CustomMouseTableCellSkin<T, S> extends TableCellSkin<T, S> {
EventHandler<MouseEvent> original;
public CustomMouseTableCellSkin(TableCell<T, S> control) {
super(control);
adjustMouseBehavior();
}
private void adjustMouseBehavior() {
// dirty: reflective access to behavior, use your custom reflective accessor
TableCellBehavior<T, S> behavior =
(TableCellBehavior<T, S>) FXUtils.invokeGetFieldValue(TableCellSkin.class, this, "behavior");
InputMap<TableCell<T, S>> inputMap = behavior.getInputMap();
ObservableList<Mapping<?>> mappings = inputMap.getMappings();
List<Mapping<?>> pressedMapping = mappings.stream()
.filter(mapping -> mapping.getEventType() == MouseEvent.MOUSE_PRESSED)
.collect(Collectors.toList());
if (pressedMapping.size() == 1) {
Mapping<?> originalMapping = pressedMapping.get(0);
original = (EventHandler<MouseEvent>) pressedMapping.get(0).getEventHandler();
if (original != null) {
EventHandler<MouseEvent> replaced = this::replaceMouseEvent;
mappings.remove(originalMapping);
mappings.add(new MouseMapping(MouseEvent.MOUSE_PRESSED, replaced));
}
}
}
private void replaceMouseEvent(MouseEvent e) {
MouseEvent replaced = e;
if (e.isMiddleButtonDown()) {
replaced = new MouseEvent(e.getSource(), e.getTarget(), e.getEventType(),
e.getX(), e.getY(),
e.getScreenX(), e.getScreenY(),
MouseButton.PRIMARY,
e.getClickCount(),
e.isShiftDown(), e.isControlDown(), e.isAltDown(), e.isMetaDown(),
true, false, false,
e.isSynthesized(), e.isPopupTrigger(), e.isStillSincePress(),
null
);
}
original.handle(replaced);
}
}
private Parent createContent() {
TableView<Person> table = new TableView<>(Person.persons());
TableColumn<Person, String> first = new TableColumn("First Name");
first.setCellValueFactory(cc -> cc.getValue().firstNameProperty());
TableColumn<Person, String> last = new TableColumn<>("Last Name");
last.setCellValueFactory(cc -> cc.getValue().lastNameProperty());
table.getColumns().addAll(first, last);
BorderPane content = new BorderPane(table);
return content;
}
#Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(createContent()));
// load the default css
stage.getScene().getStylesheets()
.add(getClass().getResource("customtablecellskin.css").toExternalForm());
stage.setTitle(FXUtils.version());
stage.show();
}
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings("unused")
private static final Logger LOG = Logger
.getLogger(TableRowCustomMouse.class.getName());
}
The css with custom skin for TableCell:
.table-cell {
-fx-skin: "<yourpackage>.TableRowCustomMouse$CustomMouseTableCellSkin";
}
Accepted #kleopatra's approach as an answer. However the solution to my question is a bit different to #kleopatra's answer. But the core idea is still the same.
I used the approach to override the doSelect method of TableCellBehavior
#Override
protected void doSelect(double x, double y, MouseButton button, int clickCount, boolean shiftDown, boolean shortcutDown) {
MouseButton btn = button;
if (button == MouseButton.MIDDLE) {
btn = MouseButton.PRIMARY;
}
super.doSelect(x, y, btn, clickCount, shiftDown, shortcutDown);
}
Below is the working demo which solved my issue:
DemoClass:
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
public class TableRowSelectionOnMiddleButtonDemo extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
ObservableList<Person> persons = FXCollections.observableArrayList();
for (int i = 0; i < 4; i++) {
persons.add(new Person("First name" + i, "Last Name" + i));
}
CustomTableView<Person> tableView = new CustomTableView<>();
TableColumn<Person, String> fnCol = new TableColumn<>("First Name");
fnCol.setCellValueFactory(param -> param.getValue().firstNameProperty());
TableColumn<Person, String> lnCol = new TableColumn<>("Last Name");
lnCol.setCellValueFactory(param -> param.getValue().lastNameProperty());
tableView.getColumns().addAll(fnCol, lnCol);
tableView.getItems().addAll(persons);
tableView.setRowFactory(new Callback<TableView<Person>, TableRow<Person>>() {
#Override
public TableRow<Person> call(TableView<Person> param) {
return new TableRow<Person>() {
{
/* This will fix my issue, but I dont want each tableView rowfactory to set this behavior.*/
// addEventHandler(MouseEvent.MOUSE_PRESSED,e->{
// getTableView().getSelectionModel().select(getItem());
// });
}
#Override
protected void updateItem(Person item, boolean empty) {
super.updateItem(item, empty);
}
};
}
});
VBox sp = new VBox();
sp.setAlignment(Pos.TOP_LEFT);
sp.getChildren().addAll(tableView);
Scene sc = new Scene(sp);
sc.getStylesheets().add(this.getClass().getResource("tableRowSelectionOnMiddleButton.css").toExternalForm());
primaryStage.setScene(sc);
primaryStage.show();
}
public static void main(String... a) {
Application.launch(a);
}
/**
* My custom tableView.
*
* #param <S>
*/
class CustomTableView<S> extends TableView<S> {
public CustomTableView() {
// A lot of custom behavior is included to this TableView.
}
}
class Person {
private StringProperty firstName = new SimpleStringProperty();
private StringProperty lastName = new SimpleStringProperty();
public Person(String fn, String ln) {
setFirstName(fn);
setLastName(ln);
}
public String getFirstName() {
return firstName.get();
}
public StringProperty firstNameProperty() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public String getLastName() {
return lastName.get();
}
public StringProperty lastNameProperty() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
}
}
CustomTableCellSkin class:
import com.sun.javafx.scene.control.behavior.TableCellBehavior;
import com.sun.javafx.scene.control.skin.TableCellSkinBase;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.input.MouseButton;
public class CustomTableCellSkin<S, T> extends TableCellSkinBase<TableCell<S, T>, TableCellBehavior<S, T>> {
private final TableColumn<S, T> tableColumn;
public CustomTableCellSkin(TableCell<S, T> tableCell) {
super(tableCell, new CustomTableCellBehavior<S, T>(tableCell));
this.tableColumn = tableCell.getTableColumn();
super.init(tableCell);
}
#Override
protected BooleanProperty columnVisibleProperty() {
return tableColumn.visibleProperty();
}
#Override
protected ReadOnlyDoubleProperty columnWidthProperty() {
return tableColumn.widthProperty();
}
}
class CustomTableCellBehavior<S, T> extends TableCellBehavior<S, T> {
public CustomTableCellBehavior(TableCell<S, T> control) {
super(control);
}
#Override
protected void doSelect(double x, double y, MouseButton button, int clickCount, boolean shiftDown, boolean shortcutDown) {
MouseButton btn = button;
if (button == MouseButton.MIDDLE) {
btn = MouseButton.PRIMARY;
}
super.doSelect(x, y, btn, clickCount, shiftDown, shortcutDown);
}
}
tableRowSelectionOnMiddleButton.css
.table-cell {
-fx-skin: "<package>.CustomTableCellSkin";
}

JavaFX Observable List only one property with value true

I would like to ask you, there is the simple way to add constraint to Observable list that are only one value true of property.
For example:
I Have an observable list of Persons. The class person has boolean Property "isKing" and string property "guild". It can be only one king for each guild.
Sure, I can ( and I know how) add an listener to change value of this property for others persons if new king will be added. But there is other way ??
( there is no database in local aplication to manage data integrations...)
It doesn't seem like such a property should be part of the elements of the list, but instead should be just an external value. In the example you suggest, you could create a separate class that encapsulated your list and the king:
public class Guild {
private final ReadOnlyObjectWrapper<Person> king = new ReadOnlyObjectWrapper<>();
private final ObservableList<Person> members = FXCollections.observableArrayList();
public ObservableList<Person> getMembers() {
return members ;
}
public ReadOnlyObjectProperty<Person> kingProperty() {
return king.getReadOnlyProperty();
}
public Person getKing() {
return kingProperty().get();
}
public void setKing(Person king) {
if (! population.contains(king)) {
throw new IllegalArgumentException("king must be a member of the guild");
}
this.king.set(king);
}
}
If the situation is more complex (e.g. a single population and multiple guilds, each with a king) the same basic idea should be feasible: define a model class that encapsulates whatever data structures you need, for example an ObservableList<Person> population and an ObservableMap<String, Person> kings, the latter keeping a single king for each guild.
Here is a more complex example:
Person.java:
package model;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Person {
private final StringProperty name = new SimpleStringProperty();
private final StringProperty guild = new SimpleStringProperty();
public Person(String name, String guild) {
setName(name);
setGuild(guild);
}
public final StringProperty nameProperty() {
return this.name;
}
public final String getName() {
return this.nameProperty().get();
}
public final void setName(final String name) {
this.nameProperty().set(name);
}
public final StringProperty guildProperty() {
return this.guild;
}
public final String getGuild() {
return this.guildProperty().get();
}
public final void setGuild(final String guild) {
this.guildProperty().set(guild);
}
}
DataModel.java:
package model;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.MapChangeListener.Change;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
public class DataModel {
private final ObservableMap<String, Person> kings = FXCollections.observableHashMap() ;
private final ObservableList<Person> population = FXCollections.observableArrayList() ;
public DataModel() {
// if a current king switches guild, remove them as king:
ChangeListener<String> guildListener = (obs, oldGuild, newGuild) ->
kings.remove(oldGuild);
kings.addListener((Change<? extends String, ? extends Person> c) -> {
if (c.wasAdded()) {
c.getValueAdded().guildProperty().addListener(guildListener);
}
if (c.wasRemoved()) {
c.getValueRemoved().guildProperty().removeListener(guildListener);
}
});
}
public ObservableList<Person> getPopulation() {
return population ;
}
public ObservableMap<String, Person> getKings() {
return FXCollections.unmodifiableObservableMap(kings);
}
public void makeKing(Person person) {
kings.put(person.getGuild(), person);
}
}
ConstrainedModelDemo.java:
package ui;
import java.util.List;
import java.util.Random;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import model.DataModel;
import model.Person;
public class ConstrainedModelDemo extends Application {
#Override
public void start(Stage primaryStage) {
DataModel model = new DataModel();
List<String> guilds = IntStream.rangeClosed(1, 5).mapToObj(i -> "Guild "+i).collect(Collectors.toList());
Random rng = new Random();
List<Person> population = IntStream.rangeClosed(1, 100).mapToObj(i -> new Person("Person "+i, guilds.get(rng.nextInt(guilds.size())))).collect(Collectors.toList());
model.getPopulation().setAll(population);
TableView<Person> table = new TableView<>();
table.setEditable(true);
table.getItems().addAll(population);
table.getColumns().add(column("Name", Person::nameProperty));
TableColumn<Person, String> guildColumn = column("Guild", Person::guildProperty);
guildColumn.setCellFactory(ComboBoxTableCell.forTableColumn(guilds.toArray(new String[guilds.size()])));
table.getColumns().add(guildColumn);
TableColumn<Person, Boolean> kingCol = new TableColumn<>("King");
kingCol.setCellValueFactory(cellData -> {
Person p = cellData.getValue();
return Bindings.createBooleanBinding(() ->
p == model.getKings().get(p.getGuild()), p.guildProperty(), model.getKings());
});
kingCol.setCellFactory(tc -> new TableCell<Person, Boolean>() {
private final CheckBox checkBox = new CheckBox();
{
checkBox.setOnAction(e -> {
if (checkBox.isSelected()) {
model.makeKing(table.getItems().get(getIndex()));
} else {
model.getKings().remove(table.getItems().get(getIndex()).getGuild());
}
});
}
#Override
protected void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
checkBox.setSelected(item);
setGraphic(checkBox);
}
}
});
table.getColumns().add(kingCol);
TableView<String> kingTable = new TableView<>();
kingTable.getItems().addAll(guilds);
kingTable.getColumns().add(column("Guild", guild -> new SimpleStringProperty(guild)));
kingTable.getColumns().add(column("King", guild -> Bindings.createStringBinding(() -> {
if (guild == null) return null ;
Person king = model.getKings().get(guild);
if (king == null) return null ;
return king.getName() ;
}, model.getKings())));
BorderPane root = new BorderPane(table);
root.setRight(kingTable);
Scene scene = new Scene(root, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
private <S,T> TableColumn<S,T> column(String title, Function<S, ObservableValue<T>> prop) {
TableColumn<S,T> col = new TableColumn<>(title);
col.setCellValueFactory(cellData -> prop.apply(cellData.getValue()));
return col ;
}
public static void main(String[] args) {
launch(args);
}
}

JavaFX TableView: Show sorted items + Background Task

I'm working with Javafx and I'm struggling to get a sorted table in place when using background Tasks to update. In the code here, which can be run standalone, I update a table in background.
What I'd like to do is that this table gets updated, and stays sorted in chronological order, so older train times appear at the top, and later ones at the bottom. The example produces times that are the opposite order on purpose, to see if sorting works.
I run some tests before I added concurrent update to the table, and the way I would do it is by calling:
private final ObservableList<StationBoardLine> data = FXCollections.observableArrayList(
new StationBoardLine("RE", "17:14", "Basel Bad Bf", "Basel SBB", "+3", "RE 5343"));
SortedList<StationBoardLine> sorted = new SortedList<>(data, new DelayComparator());
table.setItems(sorted);
However, now I'm not setting the items, but using the background task together with ReadOnlyObjectProperty and ReadOnlyObjectWrapper to append to it.
So, my question is, how can I make sure that as items are added, the list remains ordered? I've tried to see if I could reorder the list inside the call to Platform.runLater but didn't seem to work.
The link between the task updating the table and the table is set is here:
table.itemsProperty().bind(task.partialResultsProperty());
Thanks for help,
Galder
The way I would do it is by updating an ObservableList by the background task and use it as a "source" to create a SortedList. This SortedList would then act as the source of "items" to the TableView.
A general structure would be :
public class MyClass {
private TableView<T> tableView = new TableView;
private ObservableList<T> sourceList = FXCollections.observableArrayList();
public MyClass() {
...
SortedList<T> sortedList = new SortedList<>(sourceList, new MyComparator());
tableView.setItems(sortedList);
...
new Task<Void> {
protected Void call() {
... // Some background data fetch
Platform.runLater(() -> sourceList.add(data));
return null;
}
};
}
}
For your scenario, I would go with something that you already have. Therefore, instead of creating a new ObservableList to be used as a source for your SortedList, I would use the list returned by Task#getPartialResults().
The DelayComparator uses the value of the delay to compare and show the data in the TableView.
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.SortedList;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.util.Comparator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class App extends Application {
private TableView<StationBoardLine> table = new TableView<>();
private final ExecutorService exec = Executors.newSingleThreadExecutor();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 800, 600);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table.setEditable(true);
TableColumn typeCol = getTableCol("Type", 10, "type");
TableColumn departureCol = getTableCol("Departure", 30, "departure");
TableColumn stationCol = getTableCol("Station", 200, "station");
TableColumn destinationCol = getTableCol("Destination", 200, "destination");
TableColumn delayCol = getTableCol("Delay", 20, "delay");
TableColumn trainName = getTableCol("Train Name", 50, "trainName");
table.getColumns().addAll(
typeCol, departureCol, stationCol, destinationCol, delayCol, trainName);
root.setCenter(table);
PartialResultsTask task = new PartialResultsTask();
SortedList<StationBoardLine> sorted = new SortedList<>(task.getPartialResults(), new DelayComparator());
table.setItems(sorted);
exec.submit(task);
stage.setTitle("Swiss Transport Delays Board");
stage.setScene(scene);
stage.show();
}
private TableColumn getTableCol(String colName, int minWidth, String fieldName) {
TableColumn<StationBoardLine, String> typeCol = new TableColumn<>(colName);
typeCol.setMinWidth(minWidth);
typeCol.setCellValueFactory(new PropertyValueFactory<>(fieldName));
return typeCol;
}
static final class DelayComparator implements Comparator<StationBoardLine> {
#Override
public int compare(StationBoardLine o1, StationBoardLine o2) {
return o1.getDelay().compareTo(o2.getDelay());
}
}
public class PartialResultsTask extends Task<Void> {
private ObservableList<StationBoardLine>partialResults = FXCollections.observableArrayList();
public final ObservableList<StationBoardLine> getPartialResults() {
return partialResults;
}
#Override protected Void call() throws Exception {
System.out.println("Creating station board entries...");
for (int i=5; i >= 1; i--) {
Thread.sleep(1000);
if (isCancelled()) break;
StationBoardLine l = new StationBoardLine(
"ICE", "16:" + i, "Basel Bad Bf", "Chur", String.valueOf(i), "ICE 75");
Platform.runLater(() -> partialResults.add(l));
}
return null;
}
}
public static final class StationBoardLine {
private final SimpleStringProperty type;
private final SimpleStringProperty departure;
private final SimpleStringProperty station;
private final SimpleStringProperty destination;
private final SimpleStringProperty delay;
private final SimpleStringProperty trainName;
StationBoardLine(String type,
String departure,
String station,
String destination,
String delay,
String trainName) {
this.type = new SimpleStringProperty(type);
this.departure = new SimpleStringProperty(departure);
this.station = new SimpleStringProperty(station);
this.destination = new SimpleStringProperty(destination);
this.delay = new SimpleStringProperty(delay);
this.trainName = new SimpleStringProperty(trainName);
}
public String getType() {
return type.get();
}
public SimpleStringProperty typeProperty() {
return type;
}
public void setType(String type) {
this.type.set(type);
}
public String getDeparture() {
return departure.get();
}
public SimpleStringProperty departureProperty() {
return departure;
}
public void setDeparture(String departure) {
this.departure.set(departure);
}
public String getStation() {
return station.get();
}
public SimpleStringProperty stationProperty() {
return station;
}
public void setStation(String station) {
this.station.set(station);
}
public String getDestination() {
return destination.get();
}
public SimpleStringProperty destinationProperty() {
return destination;
}
public void setDestination(String destination) {
this.destination.set(destination);
}
public String getDelay() {
return delay.get();
}
public SimpleStringProperty delayProperty() {
return delay;
}
public void setDelay(String delay) {
this.delay.set(delay);
}
public String getTrainName() {
return trainName.get();
}
public SimpleStringProperty trainNameProperty() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName.set(trainName);
}
}
}

How to fetch value of selected item in choice box from a table view coloumn in javafx

How can i fetch the value of the selected choice from the choce box in the following table.
column3 has 13 choice box nodes populated using following code.I want to fetch the selected item.
final ObservableList LogLevelList=FXCollections.observableArrayList("FATAL", "ERROR", "WARN", "INFO", "INOUT", "DEBUG");
column3.setCellFactory(new Callback<TableColumn<Feature,String>,TableCell<Feature,String>>(){
#Override
public TableCell<Feature,String> call(TableColumn<Feature,String> param) {
TableCell<Feature,String> cell = new TableCell<Feature,String>(){
#Override
public void updateItem(String item, boolean empty) {
System.out.println("Inside UpdateItem");
ChoiceBox choice = new ChoiceBox(LogLevelList);
choice.getSelectionModel().select(LogLevelList.indexOf(item));
//SETTING ALL THE GRAPHICS COMPONENT FOR CELL
setGraphic(choice);
}
};
return cell;
}
});
Does the predefined ChoiceBoxTableCell do what you need?
column3.setCellFactory(ChoiceBoxTableCell.forTableColumn(logLevelList));
See if this helps:
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ChoiceBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TableChoiceBoxTest extends Application {
#Override
public void start(Stage primaryStage) {
final TableView<Feature> table = new TableView<>();
table.setEditable(true);
final TableColumn<Feature, String> nameCol = new TableColumn<>("Name");
nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
final TableColumn<Feature, String> logLevelCol = new TableColumn<>("Log level");
logLevelCol.setCellValueFactory(new PropertyValueFactory<>("logLevel"));
logLevelCol.setPrefWidth(150);
final ObservableList<String> logLevelList = FXCollections.observableArrayList("FATAL", "ERROR", "WARN", "INFO", "INOUT", "DEBUG");
logLevelCol.setCellFactory(ChoiceBoxTableCell.forTableColumn(logLevelList));
table.getColumns().addAll(nameCol, logLevelCol);
table.getItems().setAll(
IntStream.rangeClosed(1, 20)
.mapToObj(i -> new Feature("Item "+i, "FATAL"))
.collect(Collectors.toList())
);
Button showDataButton = new Button("Dump data");
showDataButton.setOnAction(event -> table.getItems().forEach(System.out::println));
BorderPane root = new BorderPane();
root.setCenter(table);
root.setBottom(showDataButton);
Scene scene = new Scene(root, 400, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class Feature {
private final StringProperty name ;
private final StringProperty logLevel ;
public Feature(String name, String logLevel) {
this.name = new SimpleStringProperty(this, "name", name);
this.logLevel = new SimpleStringProperty(this, "logLevel", logLevel);
}
public StringProperty nameProperty() {
return name ;
}
public final String getName() {
return name.get();
}
public final void setName(String name) {
this.name.set(name);
}
public StringProperty logLevelProperty() {
return logLevel ;
}
public final String getLogLevel() {
return logLevel.get();
}
public final void setLogLevel(String logLevel) {
this.logLevel.set(logLevel);
}
#Override
public String toString() {
return getName() + ": " + getLogLevel();
}
}
public static void main(String[] args) {
launch(args);
}
}
The provided ChoiceBoxTableCell updates the property of the associated item for you, so there's never any need to get the value from the ChoiceBox; you can just get the value from your model object.
I think there are mistakes in your code. You do not want to display your Choice box in each and every cell of that column (i.e Emptied Row's Cell) and Also you should call super class function.
Now for getting the selected value of ChoiceBox , instead of just displaying your choicebox with the values you will have to save them in some ArrayList or Map or best options is to save inside your Feature class. So that you can finally use
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item,empty);
if(item != null){
ChoiceBox choice = new ChoiceBox(LogLevelList);
choice.getSelectionModel().select(LogLevelList.indexOf(item));
choice.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> ov, String t, String t1) {
//either use : myMap.put(getIndex(),t1);
//or : item.setChoice(t1);
}
});
//SETTING ALL THE GRAPHICS COMPONENT FOR CELL
setGraphic(choice);
}
}
Also for demo of ChoiceBox in TableView there is one blog post for you :http://blog.ngopal.com.np/2011/10/01/tableview-cell-modifiy-in-javafx/

Get ListCell via ListView

I have a ListView with my own ListCell<MyObject> implementation. Via a network signal, I receive an index of my ListCell that should be changed.
Over listView.getItems().get(index); there is no problem to access the model, but I want to make a layout change to the listCell with the received index and a layout change to the ListCell with the index+1;
How can I access the ListCell via the ListView?
I search for a method like this:
listView.getListCell(index);
Unfortunately right now there is no API to get List Cell by index or to get All children's(listcells) for ListView. One solution can be, define a new StringProperty specialIndicator in your MyObject class.
class MyObject {
....//u r properties
private StringProperty specialIndicator;
When ever you get index from network signal set this specialIndicator property of object and do forcerefresh of ListView
public void onReceivedNetWorkSignalIndex() {
listView.getItems().get(indexFromService).setSpecialIndicator("selected");
listView.getItems().get(indexFromService+1).setSpecialIndicator("selectedplusone");
//force refresh listview (it will trigger cellFactory again so that you can manipulate layout)
listView.setItems(null);
listView.setItems(allObjects);
}
As you already have custom Object ListView , i am assuming you already have custom cellFactory (if not you have to create one ) ,Modify your custom cell factory to handle this special Indicators
listView.setCellFactory(new Callback<ListView<MyObject>, ListCell<MyObject>>() {
#Override
public ListCell<MyObject> call(ListView<MyObject> myObjectListView) {
ListCell<MyObject> cell = new ListCell<MyObject>(){
#Override
protected void updateItem(MyObject myObject, boolean b) {
super.updateItem(myObject, b);
if(myObject != null) {
setText(myObject.getName());
if("selected".equalsIgnoreCase(myObject.getSpecialIndicator())) {
System.out.println("Setting new CSS/graphics for index retun from service." + myObject.getName());
} else if("selectedplusone".equalsIgnoreCase(myObject.getSpecialIndicator())) {
System.out.println("Setting new CSS/Graphics for index+1 returned from service" + myObject.getName());
}
myObject.setSpecialIndicator(""); // reset it back to empty
}
}
};
return cell;
}
});
Here is the whole sample Application ,you can look into it (in case the above explanation is not clear).
public class ListViewTest extends Application {
#Override
public void start(Stage stage) throws Exception {
VBox root = new VBox();
final ObservableList<MyObject> allObjects = FXCollections.observableArrayList(new MyObject("object0"), new MyObject("object1"),new MyObject("object2"),new MyObject("object3"),new MyObject("object4"));
final ListView<MyObject> listView = new ListView<>(allObjects);
listView.setCellFactory(new Callback<ListView<MyObject>, ListCell<MyObject>>() {
#Override
public ListCell<MyObject> call(ListView<MyObject> myObjectListView) {
ListCell<MyObject> cell = new ListCell<MyObject>(){
#Override
protected void updateItem(MyObject myObject, boolean b) {
super.updateItem(myObject, b);
if(myObject != null) {
setText(myObject.getName());
if("selected".equalsIgnoreCase(myObject.getSpecialIndicator())) {
System.out.println("Setting new CSS/graphics for index retun from service." + myObject.getName());
setText("I am selected Index from Service");
} else if("selectedplusone".equalsIgnoreCase(myObject.getSpecialIndicator())) {
System.out.println("Setting new CSS/Graphics for index+1 returned from service" + myObject.getName());
setText("I am selected Index +1 from Service");
}
myObject.setSpecialIndicator(""); // reset it back to empty
}
}
};
return cell;
}
});
Button serviceIndex2 = new Button("ServiceIndex2");
serviceIndex2.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
int indexFromService =2;
listView.getItems().get(indexFromService).setSpecialIndicator("selected");
listView.getItems().get(indexFromService+1).setSpecialIndicator("selectedplusone");
listView.setItems(null);
listView.setItems(allObjects);
}
});
root.getChildren().addAll(listView,serviceIndex2);
Scene scene = new Scene(root,500,500);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
class MyObject {
private StringProperty name;
private StringProperty specialIndicator;
MyObject(String name) {
this.name = new SimpleStringProperty(name);
this.specialIndicator = new SimpleStringProperty();
}
public String getName() {
return name.get();
}
public StringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
public String getSpecialIndicator() {
return specialIndicator.get();
}
public StringProperty specialIndicatorProperty() {
return specialIndicator;
}
public void setSpecialIndicator(String specialIndicator) {
this.specialIndicator.set(specialIndicator);
}
}
}
Here's a relatively simple approach, where there is just one "selected" index. Here I create a property to hold the index that is selected, and the cell factory just observes it, along with the cell's item property and index property, and sets the text via a binding. You could do something similar to set the graphic, if needed.
import java.util.concurrent.Callable;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Callback;
public class ListViewStyleAroundSelection extends Application {
#Override
public void start(Stage primaryStage) {
final ListView<String> listView = new ListView<>();
for (int i=1; i<=20; i++) {
listView.getItems().add("Item "+i);
}
final HBox controls = new HBox(5);
final Button button = new Button("Set selection");
final TextField indexField = new TextField();
final IntegerProperty selectionIndex = new SimpleIntegerProperty();
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
selectionIndex.set(Integer.parseInt(indexField.getText()));
} catch (NumberFormatException nfe) {
indexField.setText("");
}
}
});
controls.getChildren().addAll(new Label("Enter selection index:"), indexField, button);
final BorderPane root = new BorderPane();
root.setCenter(listView);
root.setBottom(controls);
listView.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> lv) {
final ListCell<String> cell = new ListCell<>();
cell.textProperty().bind(Bindings.createStringBinding(new Callable<String>() {
#Override
public String call() throws Exception {
if (cell.getItem() == null) {
return null ;
} else {
switch (cell.getIndex() - selectionIndex.get()) {
case -1: return cell.getItem() + " (selected item below)";
case 0: return cell.getItem() + " (selected)";
case 1: return cell.getItem() + " (selected item above)";
default: return cell.getItem();
}
}
}
}, cell.itemProperty(), cell.indexProperty(), selectionIndex));
return cell;
}
});
final Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
And here's a slightly more complex version. Here I have a custom data type which includes a boolean property. The update sets the boolean property of the specified item to true. The cell factory creates a cell, and observes the selected property both of the current item and of the previous item. Then, as before, it uses a binding to update the text of the cell.
import java.util.concurrent.Callable;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.IntegerBinding;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Callback;
public class ListViewStyleAroundSelection extends Application {
#Override
public void start(Stage primaryStage) {
final ListView<MyDataType> listView = new ListView<>();
for (int i=0; i<=20; i++) {
listView.getItems().add(new MyDataType("Item "+i, false));
}
final HBox controls = new HBox(5);
controls.setPadding(new Insets(5));
final Button button = new Button("Set selection");
final TextField indexField = new TextField();
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
int index = Integer.parseInt(indexField.getText());
if (index >= 0 && index < listView.getItems().size()) {
final MyDataType item = listView.getItems().get(index);
item.setSelected( ! item.isSelected() );
}
} catch (NumberFormatException nfe) {
indexField.setText("");
}
}
});
controls.getChildren().addAll(new Label("Enter selection index:"), indexField, button);
final BorderPane root = new BorderPane();
root.setCenter(listView);
root.setBottom(controls);
listView.setCellFactory(new Callback<ListView<MyDataType>, ListCell<MyDataType>>() {
#Override
public ListCell<MyDataType> call(ListView<MyDataType> lv) {
final ListCell<MyDataType> cell = new ListCell<>();
final IntegerBinding previousIndex = cell.indexProperty().subtract(1);
final ObjectBinding<MyDataType> previousItem = Bindings.valueAt(listView.getItems(), previousIndex);
final BooleanBinding previousItemSelected = Bindings.selectBoolean(previousItem, "selected");
final StringBinding thisItemName = Bindings.selectString(cell.itemProperty(), "name");
final BooleanBinding thisItemSelected = Bindings.selectBoolean(cell.itemProperty(), "selected");
cell.textProperty().bind(Bindings.createStringBinding(new Callable<String>() {
#Override
public String call() throws Exception {
if (cell.getItem() == null) {
return null ;
} else {
String value = cell.getItem().getName();
if (thisItemSelected.get()) {
value = value + " (selected) " ;
} else if (previousItemSelected.get()) {
value = value + " (selected item is above)";
}
return value ;
}
}
}, thisItemName, thisItemSelected, previousItemSelected));
return cell;
}
});
final Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class MyDataType {
private final BooleanProperty selected ;
private final StringProperty name ;
public MyDataType(String name, boolean selected) {
this.name = new SimpleStringProperty(this, "name", name);
this.selected = new SimpleBooleanProperty(this, "selected", selected);
}
public final String getName() {
return name.get();
}
public final void setName(String name) {
this.name.set(name);
}
public final StringProperty nameProperty() {
return name ;
}
public final boolean isSelected() {
return selected.get();
}
public final void setSelected(boolean selected) {
this.selected.set(selected);
}
public final BooleanProperty selectedProperty() {
return selected;
}
}
public static void main(String[] args) {
launch(args);
}
}
Cell has a style class called ".cell"
public Cell getListCell(ListView list, int index){
Object[]cells = list.lookupAll(".cell").toArray();
return (Cell)cells[index];
}
This is the method I used to solve the same problem. Please note that getting the cell view is considered bad practice, and shouldn't be done in a normal context, updating cells should only be done through the model, my special case was that I wanted to fire an event manually as part of a workaround.
private ListCell<?> getListCell(ListView<?> listView, int cellIndex) {
if (cellIndex == -1) {
return null;
}
//Virtual Flow is the container of all list cells
//Each ListView has exactly one VirtualFlow which we are searching for
Optional<VirtualFlow> virtualFlowOptional = listView.getChildrenUnmodifiable()
.stream()
.filter(node -> node instanceof VirtualFlow)
.map(n -> (VirtualFlow) n)
.findFirst();
if (virtualFlowOptional.isEmpty()) {
return null;
}
VirtualFlow<ListCell<?>> virtualFlow = virtualFlowOptional.get();
return virtualFlow.getCell(cellIndex);
}

Resources