Table View Selected Bind With checkbox - javafx

How to
Table column select check box will select
I have select check box in table view and unfortunately,I will select table column at time all check box is un-select,click table column check box only select
how to rearrange in my code help me.
package tableviewwithaddcheckbox;
import com.sun.javafx.runtime.VersionInfo;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
/**
*
* #author reegan
*/
public class TableViewWithAddCheckBox extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(final Stage stage) {
stage.setTitle("People");
// create a table.
final TableView<Person> table = new TableView<>(
FXCollections.observableArrayList(
new Person("Jacob", "Smith"),
new Person("Isabella", "Johnson"),
new Person("Ethan", "Williams"),
new Person("Emma", "Jones"),
new Person("Michael", "Brown")));
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
// define the table columns.
TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
firstNameCol.setCellValueFactory(new PropertyValueFactory("firstName"));
TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
lastNameCol.setCellValueFactory(new PropertyValueFactory("lastName"));
TableColumn<Person, Boolean> actionCol = new TableColumn<>("Action");
actionCol.setSortable(false);
// define a simple boolean cell value for the action column so that the column will only be shown for non-empty rows.
actionCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person, Boolean>, ObservableValue<Boolean>>() {
#Override
public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Person, Boolean> features) {
return new SimpleBooleanProperty(features.getValue() != null);
}
});
// create a cell value factory with an add button for each row in the table.
actionCol.setCellFactory(new Callback<TableColumn<Person, Boolean>, TableCell<Person, Boolean>>() {
#Override
public TableCell<Person, Boolean> call(TableColumn<Person, Boolean> personBooleanTableColumn) {
return new AddPersonCell(stage, table);
}
});
table.getColumns().setAll(firstNameCol, lastNameCol, actionCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table.getSelectionModel().getSelectedIndices().addListener(new ListChangeListener() {
#Override
public void onChanged(ListChangeListener.Change change) {
System.out.println("-------------------------");
System.out.println(change.getList());
System.out.println("------------------------");
}
});
table.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<Person>() {
#Override
public void onChanged(ListChangeListener.Change<? extends Person> change) {
System.out.println(change.getList());
VersionInfo info = new VersionInfo();
System.out.println(info.getRuntimeVersion());
String version = System.getProperty("java.version");
System.out.println(version);
String vendor = System.getProperty("java.vendor.url");
System.out.println(vendor);
System.out.println(version);
}
});
System.out.println(table.getItems());
stage.setScene(new Scene(table));
stage.show();
}
private class AddPersonCell extends TableCell<Person, Boolean> {
final CheckBox addButton = new CheckBox();
final StackPane paddedButton = new StackPane();
AddPersonCell(final Stage stage, final TableView table) {
paddedButton.setPadding(new Insets(3));
paddedButton.getChildren().add(addButton);
addButton.selectedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
if (t1) {
table.getSelectionModel().select(getTableRow().getIndex());
System.out.println(getTableColumn());
} else {
table.getSelectionModel().clearSelection(getTableRow().getIndex());
}
}
});
}
#Override
protected void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setGraphic(paddedButton);
}
}
}
}
PersonClaa.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tableviewwithaddcheckbox;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*
* #author reegan
*/
public class Person {
private StringProperty firstName;
private StringProperty lastName;
public Person(String firstName, String lastName) {
setFirstName(firstName);
setLastName(lastName);
}
public final void setFirstName(String value) { firstNameProperty().set(value); }
public final void setLastName(String value) { lastNameProperty().set(value); }
public String getFirstName() { return firstNameProperty().get(); }
public String getLastName() { return lastNameProperty().get(); }
public StringProperty firstNameProperty() {
if (firstName == null) firstName = new SimpleStringProperty(this, "firstName");
return firstName;
}
public StringProperty lastNameProperty() {
if (lastName == null) lastName = new SimpleStringProperty(this, "lastName");
return lastName;
}
}

Related

JavaFX tableview Enable and Disable row selection

As a part of my project i want display a tableview which should be disabled for some time(on editting time nb:not table editting).So that i got a working code which will disable the tableview.This is the working code,
table.setSelectionModel(null);
So my problem is after editing process is over when click a button i want to enable it back,but unfortunately i could'nt find any alternative code for that.Any one please suggest me the code which will enable the row selection.Any answer will appreciable.
You can retrieve the default selection model when you create the table:
TableView<T> table = new TableView<>();
TableViewSelectionModel<T> defaultSelectionModel = table.getSelectionModel();
where T is the type for your table. (Of course, if you are using FXML, just put the second line in the controller's initialize() method.)
Then to disable row selection do
table.setSelectionModel(null);
and to enable it again
table.setSelectionModel(defaultSelectionModel);
Here is a SSCCE:
import java.util.function.Function;
import javafx.application.Application;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TableView.TableViewSelectionModel;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TableWithDisabledSelection extends Application {
#Override
public void start(Stage primaryStage) {
TableView<Person> table = new TableView<>();
TableViewSelectionModel<Person> defaultSelectionModel = table.getSelectionModel();
table.getColumns().add(column("First Name", Person::firstNameProperty));
table.getColumns().add(column("Last Name", Person::lastNameProperty));
table.getColumns().add(column("Email", Person::emailProperty));
table.getItems().addAll(
new Person("Jacob", "Smith", "jacob.smith#example.com"),
new Person("Isabella", "Johnson", "isabella.johnson#example.com"),
new Person("Ethan", "Williams", "ethan.williams#example.com"),
new Person("Emma", "Jones", "emma.jones#example.com"),
new Person("Michael", "Brown", "michael.brown#example.com")
);
CheckBox enableSelection = new CheckBox("Enable selection");
enableSelection.setSelected(true);
enableSelection.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
table.setSelectionModel(defaultSelectionModel);
} else {
table.setSelectionModel(null);
}
});
BorderPane root = new BorderPane(table);
BorderPane.setAlignment(enableSelection, Pos.CENTER);
BorderPane.setMargin(enableSelection, new Insets(5));
root.setBottom(enableSelection);
primaryStage.setScene(new Scene(root, 600, 600));
primaryStage.show();
}
private <S,T> TableColumn<S,T> column(String title, Function<S,Property<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);
}
public static class Person {
private final StringProperty firstName = new SimpleStringProperty();
private final StringProperty lastName = new SimpleStringProperty();
private final StringProperty email = new SimpleStringProperty();
public Person(String firstName, String lastName, String email) {
setFirstName(firstName);
setLastName(lastName);
setEmail(email);
}
public final StringProperty firstNameProperty() {
return this.firstName;
}
public final String getFirstName() {
return this.firstNameProperty().get();
}
public final void setFirstName(final String firstName) {
this.firstNameProperty().set(firstName);
}
public final StringProperty lastNameProperty() {
return this.lastName;
}
public final String getLastName() {
return this.lastNameProperty().get();
}
public final void setLastName(final String lastName) {
this.lastNameProperty().set(lastName);
}
public final StringProperty emailProperty() {
return this.email;
}
public final String getEmail() {
return this.emailProperty().get();
}
public final void setEmail(final String email) {
this.emailProperty().set(email);
}
}
}
I handled this situation with rowfactory like this;
tableView.setRowFactory(param -> new TableRow<Model>()
{
#Override
protected void updateItem(Model item, boolean empty)
{
super.updateItem(item, empty);
if (!empty)
{
disableProperty().bind(item.getFocusable().not());
}
}
});
so, you can bind the disableproperty with suitable property of your tableview model.

TableView with different cell values in javafx

In the following code there are 4 columns. In "Particular Value" column different types of data can be added like string, integer, date, etc. But I want to add a button in same column next to value entered in that cell, only if that value is string.
something like this:
First name| Last Name| Age| Particular value
James | Smith | 10 | 10
Jacob | Wisly | 20 | abc (button)
Anna | Samaul | 15 | 45.5
How to do add button in same column only for particular cell i.e containing string value?
package application;
import java.time.LocalDateTime;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
public class Main extends Application {
private final TableView<Person<?>> tableView = new TableView<>();
private Person<Integer> person1 = new Person<>("Jacob", "Smith", 28, 4);
private Person<Integer> person2 = new Person<>("Isabella", "Johnson", 19, 5);
private Person<String> person3 = new Person<>("Bob", "The Sponge", 13, "Say Hi!");
private Person<LocalDateTime> person4 = new Person<>("Time", "Is Money", 45, LocalDateTime.now());
private Person<Double> person5 = new Person<>("John", "Doe", 32, 457.89);
private final ObservableList<Person<?>> data = FXCollections.observableArrayList(person1, person2, person3, person4,
person5);
#SuppressWarnings("unchecked")
#Override
public void start(Stage primaryStage) {
TableColumn<Person<?>, String> firstNameCol = new TableColumn<>("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
TableColumn<Person<?>, String> lastNameCol = new TableColumn<>("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
TableColumn<Person<?>, Integer> ageCol = new TableColumn<>("Age");
ageCol.setMinWidth(50);
ageCol.setCellValueFactory(new PropertyValueFactory<>("age"));
TableColumn<Person<?>, ?> particularValueCol = new TableColumn<>("Particular Value");
particularValueCol.setMinWidth(200);
particularValueCol.setCellValueFactory(new PropertyValueFactory<>("particularValue"));
tableView.setItems(data);
// Type safety: A generic array of Table... is created for a varargs
// parameter
// -> #SuppressWarnings("unchecked") to start method!
tableView.getColumns().addAll(firstNameCol, lastNameCol, ageCol, particularValueCol);
// Output in console the selected table view's cell value/class to check
// that the data type is correct.
SystemOutTableViewSelectedCell.set(tableView);
// To check that table view is correctly refreshed on data changed..
final Button agePlusOneButton = new Button("Age +1");
agePlusOneButton.setOnAction((ActionEvent e) -> {
Person<?> person = tableView.getSelectionModel().getSelectedItem();
try {
person.setAge(person.getAge() + 1);
} catch (NullPointerException npe) {
//
}
});
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(tableView, agePlusOneButton);
Scene scene = new Scene(new Group());
((Group) scene.getRoot()).getChildren().addAll(vbox);
primaryStage.setWidth(600);
primaryStage.setHeight(750);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public static class Person<T> {
private final StringProperty firstName;
private final StringProperty lastName;
private final IntegerProperty age;
private final ObjectProperty<T> particularValue;
private Person(String firstName, String lastName, Integer age, T particularValue) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
this.age = new SimpleIntegerProperty(age);
this.particularValue = new SimpleObjectProperty<T>(particularValue);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public StringProperty firstNameProperty() {
return firstName;
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public StringProperty lastNameProperty() {
return lastName;
}
public Integer getAge() {
return age.get();
}
public void setAge(Integer age) {
this.age.set(age);
}
public IntegerProperty ageProperty() {
return age;
}
public T getParticularValue() {
return particularValue.get();
}
public void setParticularValue(T particularValue) {
this.particularValue.set(particularValue);
}
public ObjectProperty<T> particularValueProperty() {
return particularValue;
}
}
public static final class SystemOutTableViewSelectedCell {
#SuppressWarnings({ "rawtypes", "unchecked" })
public static void set(TableView tableView) {
tableView.getSelectionModel().setCellSelectionEnabled(true);
ObservableList selectedCells = tableView.getSelectionModel().getSelectedCells();
selectedCells.addListener(new ListChangeListener() {
#Override
public void onChanged(Change c) {
TablePosition tablePosition = (TablePosition) selectedCells.get(0);
Object val = tablePosition.getTableColumn().getCellData(tablePosition.getRow());
System.out.println("Selected Cell (Row: " + tablePosition.getRow() + " / Col: "
+ tablePosition.getColumn() + ") Value: " + val + " / " + val.getClass());
}
});
}
}
}
You can do:
TableColumn<Person<?>, Object> particularValueCol = new TableColumn<>("Particular Value");
particularValueCol.setMinWidth(200);
particularValueCol.setCellValueFactory(new PropertyValueFactory<>("particularValue"));
particularValueCol.setCellFactory(tc -> new TableCell<Person<?>, Object>() {
private Button button = new Button("A button");
#Override
protected void updateItem(Object item, boolean empty) {
super.updateItem(item, empty) ;
if (empty || item == null) {
setText(null);
setGraphic(null);
} else {
setText(item.toString());
if (item instanceof String) {
setGraphic(button);
} else {
setGraphic(null);
}
}
}
});

JavaFX getting cell value on hover

I was searching for a solution on how to get cell values by hovering over them, but haven't found any. I was thinking of a similar solution to this:
Can't select different cells in same row of tableview JavaFx , except not selecting, but only hover. How could I do it? Thanks.
Use a custom cell that updates a property when the mouse enters/exits it:
public class HoverCell extends TableCell<Person, String> {
public HoverCell(StringProperty hoverProperty) {
setOnMouseEntered(e -> hoverProperty.set(getItem()));
setOnMouseExited(e -> hoverProperty.set(null));
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : item);
}
}
Complete example:
import java.util.function.Function;
import javafx.application.Application;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class HoverTableCells extends Application {
#Override
public void start(Stage primaryStage) {
TableView<Person> table = new TableView<>();
TableColumn<Person, String> firstNameCol = column("First Name", Person::firstNameProperty);
TableColumn<Person, String> lastNameCol = column("Last Name", Person::lastNameProperty);
TableColumn<Person, String> emailCol = column("Email", Person::emailProperty);
StringProperty hoveredProperty = new SimpleStringProperty();
firstNameCol.setCellFactory(tc -> new HoverCell(hoveredProperty));
lastNameCol.setCellFactory(tc -> new HoverCell(hoveredProperty));
emailCol.setCellFactory(tc -> new HoverCell(hoveredProperty));
Label currentHover = new Label();
currentHover.textProperty().bind(hoveredProperty);
table.getColumns().add(firstNameCol);
table.getColumns().add(lastNameCol);
table.getColumns().add(emailCol);
table.getItems().addAll(
new Person("Jacob", "Smith", "jacob.smith#example.com"),
new Person("Isabella", "Johnson", "isabella.johnson#example.com"),
new Person("Ethan", "Williams", "ethan.williams#example.com"),
new Person("Emma", "Jones", "emma.jones#example.com"),
new Person("Michael", "Brown", "michael.brown#example.com")
);
BorderPane root = new BorderPane(table);
BorderPane.setMargin(currentHover, new Insets(10));
root.setTop(currentHover);
Scene scene = new Scene(root, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
private static <S,T> TableColumn<S,T> column(String title, Function<S, Property<T>> property) {
TableColumn<S, T> col = new TableColumn<>(title);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
return col ;
}
public static class HoverCell extends TableCell<Person, String> {
public HoverCell(StringProperty hoverProperty) {
setOnMouseEntered(e -> hoverProperty.set(getItem()));
setOnMouseExited(e -> hoverProperty.set(null));
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : item);
}
}
public static class Person {
private final StringProperty firstName = new SimpleStringProperty();
private final StringProperty lastName = new SimpleStringProperty();
private final StringProperty email = new SimpleStringProperty();
public Person(String firstName, String lastName, String email) {
setFirstName(firstName);
setLastName(lastName);
setEmail(email);
}
public final StringProperty firstNameProperty() {
return this.firstName;
}
public final String getFirstName() {
return this.firstNameProperty().get();
}
public final void setFirstName(final String firstName) {
this.firstNameProperty().set(firstName);
}
public final StringProperty lastNameProperty() {
return this.lastName;
}
public final String getLastName() {
return this.lastNameProperty().get();
}
public final void setLastName(final String lastName) {
this.lastNameProperty().set(lastName);
}
public final StringProperty emailProperty() {
return this.email;
}
public final String getEmail() {
return this.emailProperty().get();
}
public final void setEmail(final String email) {
this.emailProperty().set(email);
}
}
public static void main(String[] args) {
launch(args);
}
}

How I can change the style of a specific celldata in javafx?

Good Evening,
I would like to know, how i can change the background color to red of all below 18 year, is possible ?
I'm trying solve this since Monday. Could someone give me some website than explain better than oracle documentation ?
I see a lot of people, still using swing, Should I keep learn about javafx or start study swing ?
obs: sorry for my bad english.
Controller
package tableview;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.AnchorPane;
public class LayoutController implements Initializable {
#Override
public void initialize(URL url, ResourceBundle rb) {
getPerson();
columnFName.setCellValueFactory(celldata -> celldata.getValue().getfName());
columnLName.setCellValueFactory(celldata -> celldata.getValue().getlName());
columnAge.setCellValueFactory(celldata -> celldata.getValue().getAge());
tableView.setItems(person);
}
#FXML
private AnchorPane layout;
//TABLE
#FXML
private TableView<Person> tableView;
#FXML
private TableColumn<Person, String> columnLName;
#FXML
private TableColumn<Person, String> columnFName;
#FXML
private TableColumn<Person, Number> columnAge;
//END
ObservableList person = FXCollections.observableArrayList();
ObservableList getPerson() {
person.add(new Person("John", "Smith", 15));
person.add(new Person("May", "Smith", 18));
person.add(new Person("Sam", "Lucca", 21));
person.add(new Person("Homer", "Simpson", 14));
return person;
}
}
Person class
package tableview;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class Person {
private SimpleStringProperty fName, lName;
private SimpleIntegerProperty age;
public Person() {
this("", "", 0);
}
public Person(String fName, String lName, int age) {
this.fName = new SimpleStringProperty(fName);
this.lName = new SimpleStringProperty(lName);
this.age = new SimpleIntegerProperty(age);
}
public SimpleStringProperty getfName() {
return fName;
}
public SimpleStringProperty getlName() {
return lName;
}
public SimpleIntegerProperty getAge() {
return age;
}
}
Set a row factory on your table. You want to observe the itemProperty of the row. The best way to manage the background color is using an external CSS file and setting a CSS pseudoclass if the person represented by the row has age < 18. (You can put this code in your controller's initialize() method.)
PseudoClass minorPseudoClass = PseudoClass.getPseudoClass("minor");
tableView.setRowFactory(tv -> {
TableRow<Person> row = new TableRow<>();
row.itemProperty().addListener((obs, oldPerson, newPerson) -> {
if (newPerson != null) {
row.pseudoClassStateChanged(minorPseudoClass, newPerson.getAge() < 18);
} else {
row.pseudoClassStateChanged(minorPseudoClass, false);
}
});
return row ;
});
Then define an external style sheet with the appropriate style for the pseudoclass you created:
.table-row-cell:minor {
-fx-control-inner-background: red ;
-fx-control-inner-background-alt: #cc0000 ;
}
Note that this assumes the age is fixed for each person in the table. If it has the possibility of changing while the person is displayed, you need to register and deregister listeners with the age property as the row content changes:
tableView.setRowFactory(tv -> {
TableRow<Person> row = new TableRow<>();
ChangeListener<Number> ageListener = (obs, oldValue, newValue) -> {
row.pseudoClassStateChanged(minorPseudoClass, newValue.intValue() < 18);
};
row.itemProperty().addListener((obs, oldPerson, newPerson) -> {
if (oldPerson != null) {
oldPerson.ageProperty().removeListener(ageListener);
}
if (newPerson != null) {
newPerson.ageProperty().addListener(ageListener);
row.pseudoClassStateChanged(minorPseudoClass, newPerson.getAge() < 18);
} else {
row.pseudoClassStateChanged(minorPseudoClass, false);
}
});
return row ;
});
Here is a SSCCE. This doesn't use FXML, but obviously you can do the same thing, creating the rowFactory in the initialize() method in the controller.
import java.util.function.Function;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.css.PseudoClass;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class HighlightYoungPeopleTableExample extends Application {
#Override
public void start(Stage primaryStage) {
TableView<Person> tableView = new TableView<>();
TableColumn<Person, String> firstNameColumn = column("First Name", Person::firstNameProperty, 150);
TableColumn<Person, String> lastNameColumn = column("Last Name", Person::lastNameProperty, 150);
TableColumn<Person, Integer> ageColumn = column("Age", person -> person.ageProperty().asObject(), 50);
PseudoClass minorPseudoClass = PseudoClass.getPseudoClass("minor");
tableView.setRowFactory(tv -> {
TableRow<Person> row = new TableRow<>();
ChangeListener<Number> ageListener = (obs, oldValue, newValue) -> {
row.pseudoClassStateChanged(minorPseudoClass, newValue.intValue() < 18);
};
row.itemProperty().addListener((obs, oldPerson, newPerson) -> {
if (oldPerson != null) {
oldPerson.ageProperty().removeListener(ageListener);
}
if (newPerson != null) {
newPerson.ageProperty().addListener(ageListener);
row.pseudoClassStateChanged(minorPseudoClass, newPerson.getAge() < 18);
} else {
row.pseudoClassStateChanged(minorPseudoClass, false);
}
});
return row ;
});
tableView.getColumns().add(firstNameColumn);
tableView.getColumns().add(lastNameColumn);
tableView.getColumns().add(ageColumn);
tableView.getItems().addAll(
new Person("John", "Smith", 15),
new Person("May", "Smith", 18),
new Person("Sam", "Lucca", 21),
new Person("Homer", "Simpson", 14)
);
Scene scene = new Scene(new BorderPane(tableView), 800, 600);
scene.getStylesheets().add("highlight-young-people-table.css");
primaryStage.setScene(scene);
primaryStage.show();
}
private <S,T> TableColumn<S,T> column(String title, Function<S, ObservableValue<T>> property, double width) {
TableColumn<S,T> col = new TableColumn<>(title);
col.setPrefWidth(width);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
return col ;
}
public static class Person {
private final StringProperty firstName = new SimpleStringProperty() ;
private final StringProperty lastName = new SimpleStringProperty() ;
private final IntegerProperty age = new SimpleIntegerProperty();
public Person(String firstName, String lastName, int age) {
setFirstName(firstName);
setLastName(lastName);
setAge(age);
}
public final StringProperty firstNameProperty() {
return this.firstName;
}
public final String getFirstName() {
return this.firstNameProperty().get();
}
public final void setFirstName(final String firstName) {
this.firstNameProperty().set(firstName);
}
public final StringProperty lastNameProperty() {
return this.lastName;
}
public final String getLastName() {
return this.lastNameProperty().get();
}
public final void setLastName(final String lastName) {
this.lastNameProperty().set(lastName);
}
public final IntegerProperty ageProperty() {
return this.age;
}
public final int getAge() {
return this.ageProperty().get();
}
public final void setAge(final int age) {
this.ageProperty().set(age);
}
}
public static void main(String[] args) {
launch(args);
}
}
highlight-young-people-table.css
.table-row-cell:minor {
-fx-control-inner-background: red ;
-fx-control-inner-background-alt: #cc0000 ;
}

creating RadioButton in TableView Column

I followed the tutorial about TableView in Oracle docs, and I want to do the same thing, but instead of showing a TextField to modified items, I want to show a RadioButton.
(I created the TableView with RadionButton on it)
I used the tutorial at https://docs.oracle.com/javase/8/javafx/user-interface-tutorial/table-view.htm (see Editing Data in the Table) and extended it. As a basis for the values, which should be set by radio buttons I assume an Enumeration.
In my example I extended the Person class with the enum Participation (indicating whether or not the people of the list attending an fictive event) ...
public static enum Participation {
YES,
NO,
MAYBE;
public String toString() {
return super.toString().toLowerCase();
};
}
...
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private final SimpleStringProperty email;
private final SimpleObjectProperty<Participation> participation;
...
I implemented a RadioButtonCell, which takes an arbitraty EnumSet<T>. So you can use it for every Enumeration and every TableColumn, which should contain RadioButtons.
public static class RadioButtonCell<S,T extends Enum<T>> extends TableCell<S,T>{
private EnumSet<T> enumeration;
public RadioButtonCell(EnumSet<T> enumeration) {
this.enumeration = enumeration;
}
#Override
protected void updateItem(T item, boolean empty)
{
super.updateItem(item, empty);
if (!empty)
{
// gui setup
HBox hb = new HBox(7);
hb.setAlignment(Pos.CENTER);
final ToggleGroup group = new ToggleGroup();
// create a radio button for each 'element' of the enumeration
for (Enum<T> enumElement : enumeration) {
RadioButton radioButton = new RadioButton(enumElement.toString());
radioButton.setUserData(enumElement);
radioButton.setToggleGroup(group);
hb.getChildren().add(radioButton);
if (enumElement.equals(item)) {
radioButton.setSelected(true);
}
}
// issue events on change of the selected radio button
group.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
#SuppressWarnings("unchecked")
#Override
public void changed(ObservableValue<? extends Toggle> observable,
Toggle oldValue, Toggle newValue) {
getTableView().edit(getIndex(), getTableColumn());
RadioButtonCell.this.commitEdit((T) newValue.getUserData());
}
});
setGraphic(hb);
}
}
}
You now have to adjust the CellFactory of the particular TableColumn
participationColumn.setCellFactory((param) -> new RadioButtonCell<Person, Participation>(EnumSet.allOf(Participation.class)));
Finally update the actual value of your data on a commit as usual:
participationColumn.setCellValueFactory(new PropertyValueFactory<Person, Participation>("participation"));
participationColumn.setOnEditCommit(
new EventHandler<CellEditEvent<Person, Participation>>() {
#Override
public void handle(CellEditEvent<Person, Participation> t) {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setParticipation(t.getNewValue());
}
}
);
gkri, thank you for the nice code! This is very useful. I have one additional remark: Of course the new SimpleObjectProperty needs its get & set methods. Without the getter the table will not properly update, especially when sorting or, with TreeTableView, when expanding or collapsing nodes:
public void setParticipation(Participation p){
participation.set(p);
}
public Participation getParticipation(){
return participation.get();
}
So the full code sample:
import java.util.EnumSet;
import javafx.application.Application;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class TableViewSample extends Application {
private final TableView<Person> table = new TableView<>();
private final ObservableList<Person> data =
FXCollections.observableArrayList(
new Person("Jacob", "Smith", "jacob.smith#example.com",Participation.MAYBE),
new Person("Isabella", "Johnson", "isabella.johnson#example.com",Participation.MAYBE),
new Person("Ethan", "Williams", "ethan.williams#example.com",Participation.MAYBE),
new Person("Emma", "Jones", "emma.jones#example.com",Participation.MAYBE),
new Person("Michael", "Brown", "michael.brown#example.com",Participation.MAYBE));
final HBox hb = new HBox();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Table View Sample");
stage.setWidth(650);
stage.setHeight(550);
final Label label = new Label("Address Book");
label.setFont(new Font("Arial", 20));
table.setEditable(true);
table.setMinWidth(640);
TableColumn<Person,String> firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(
new PropertyValueFactory<>("firstName"));
TableColumn<Person,String>lastNameCol = new TableColumn("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(
new PropertyValueFactory<>("lastName"));
TableColumn<Person,String> emailCol = new TableColumn("Email");
emailCol.setMinWidth(200);
emailCol.setCellValueFactory(
new PropertyValueFactory<>("email"));
TableColumn<Person,Participation> participationColumn = new TableColumn("Participation");
participationColumn.setCellFactory((param) -> new RadioButtonCell<Person, Participation>(EnumSet.allOf(Participation.class)));
participationColumn.setCellValueFactory(new PropertyValueFactory<Person, Participation>("participation"));
participationColumn.setOnEditCommit(
new EventHandler<CellEditEvent<Person, Participation>>() {
#Override
public void handle(CellEditEvent<Person, Participation> t) {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setParticipation(t.getNewValue());
}
}
);
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol, emailCol, participationColumn );
final TextField addFirstName = new TextField();
addFirstName.setPromptText("First Name");
addFirstName.setMaxWidth(firstNameCol.getPrefWidth());
final TextField addLastName = new TextField();
addLastName.setMaxWidth(lastNameCol.getPrefWidth());
addLastName.setPromptText("Last Name");
final TextField addEmail = new TextField();
addEmail.setMaxWidth(emailCol.getPrefWidth());
addEmail.setPromptText("Email");
final Button addButton = new Button("Add");
addButton.setOnAction((ActionEvent e) -> {
data.add(new Person(
addFirstName.getText(),
addLastName.getText(),
addEmail.getText(),
Participation.NO
));
addFirstName.clear();
addLastName.clear();
addEmail.clear();
});
hb.getChildren().addAll(addFirstName, addLastName, addEmail, addButton);
hb.setSpacing(3);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table, hb);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
public static enum Participation {
YES,
NO,
MAYBE;
public String toString() {
return super.toString().toLowerCase();
};
}
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private final SimpleStringProperty email;
private final SimpleObjectProperty<Participation> participation = new SimpleObjectProperty<Participation>();
private Person(String fName, String lName, String email, Participation p ) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
this.email = new SimpleStringProperty(email);
this.participation.setValue(p);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String fName) {
lastName.set(fName);
}
public String getEmail() {
return email.get();
}
public void setEmail(String fName) {
email.set(fName);
}
public void setParticipation(Participation p){
participation.set(p);
}
public Participation getParticipation(){
return participation.get();
}
}
public static class RadioButtonCell<S,T extends Enum<T>> extends TableCell<S,T>{
private EnumSet<T> enumeration;
public RadioButtonCell(EnumSet<T> enumeration) {
this.enumeration = enumeration;
}
#Override
protected void updateItem(T item, boolean empty)
{
super.updateItem(item, empty);
if (!empty)
{
// gui setup
HBox hb = new HBox(7);
hb.setAlignment(Pos.CENTER);
final ToggleGroup group = new ToggleGroup();
// create a radio button for each 'element' of the enumeration
for (Enum<T> enumElement : enumeration) {
RadioButton radioButton = new RadioButton(enumElement.toString());
radioButton.setUserData(enumElement);
radioButton.setToggleGroup(group);
hb.getChildren().add(radioButton);
if (enumElement.equals(item)) {
radioButton.setSelected(true);
}
}
// issue events on change of the selected radio button
group.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
#SuppressWarnings("unchecked")
#Override
public void changed(ObservableValue<? extends Toggle> observable,
Toggle oldValue, Toggle newValue) {
getTableView().edit(getIndex(), getTableColumn());
RadioButtonCell.this.commitEdit((T) newValue.getUserData());
}
});
setGraphic(hb);
}
}
}
}
Simly do it like in the example 12-8 Editing a Table Cell.
Define a EditingCell like there(at the bottom) but simply replace the TextField with a RadioButton.
If you need further assistance, write a comment under this answer.
Happy Coding,
Kalasch

Resources