bind SelectProperty of RadioButton in TableView - java

I created a RadioButtonCell with this article but now i want to bind the selectedPropeties of my RadioButton with the properties contained in the ObservableList linked to this TableView. The observableList contains object type of "Risk", and the Model is containing:
final BooleanProperty isDefaultRiskProperty;
My own TableCell implementation is:
package utils;
import Model.databaseModels.Risk;
import controllers.risks.ModifyRisksAvailableController;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TableCell;
import javafx.scene.control.ToggleGroup;
public class RadioButtonCell extends TableCell<Risk, Boolean> {
ToggleGroup toggleGroup;
ModifyRisksAvailableController modifyRisksAvailableController;
public RadioButtonCell(ToggleGroup group){
toggleGroup = group;
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
}
}
#Override
protected void updateItem(Boolean item, boolean empty){
super.updateItem(item, empty);
System.out.println(item);
if(!empty && item != null){
RadioButton radioButton = new RadioButton();
radioButton.setToggleGroup(this.toggleGroup);
radioButton.setSelected(item);
setGraphic(radioButton);
}else{
setGraphic(null);
}
}
}
My TableView contains 3 columns:
#FXML
TableColumn<Risk,Boolean> ColumnCheckBox;
#FXML
TableColumn<Risk,Number> ColumnRiskValue;
#FXML
TableColumn<Risk, Boolean> ColumnIsDefaultRisk;
And I initialize the TableView like this:
//Colonne -> Checbkox / sélection pour suppression
ColumnCheckBox.setCellValueFactory(cellData -> cellData.getValue().checkProperty());
ColumnCheckBox.setCellFactory(column -> new CheckBoxTableCell<>());
ColumnCheckBox.setEditable(true);
ColumnCheckBox.setVisible(false);
ColumnCheckBox.setPrefWidth(24.0);
//Colonne -> Checkbox / risque par défaut
ColumnIsDefaultRisk.setCellValueFactory(cellData -> cellData.getValue().isDefaultRiskProperty());
ColumnIsDefaultRisk.setCellFactory(column -> new RadioButtonCell(toggleGroup,this));
ColumnIsDefaultRisk.setEditable(true);
//Colonne -> TextField / % de risque
ColumnRiskValue.setCellValueFactory(cellData -> cellData.getValue().riskValueProperty());
ColumnRiskValue.setCellFactory(TextFieldTableCell.forTableColumn(new NumberStringConverter()));
ColumnRiskValue.setEditable(true);
The property i want to bind with the radioButton is ".isDefaultRiskProperty()" of the "ColumnIsDefaultRisk" column. I giving my datas to the column with setCellValueFactory but i can't get the SimpleBooleanProperty in my CellFactory.
The param "item" that i get in the updateItem's method is a Boolean, (it converting BooleanProperty to Boolean), but i want a ObservableValue.
Thanks you very much.

The problem is that table cells aren’t guaranteed to exist all the time; they are for painting and editing only. So, a ToggleGroup isn’t really of any use here.
But you can do the work of a ToggleGroup yourself fairly easily:
#Override
protected void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (!empty && item != null) {
RadioButton radioButton = new RadioButton();
radioButton.setToggleGroup(this.toggleGroup);
radioButton.setSelected(item);
setGraphic(radioButton);
radioButton.selectedProperty().addListener(
(o, old, selected) -> {
if (selected) {
Risk cellRisk = getTableRow().getItem();
for (Risk risk : getTableView().getItems()) {
risk.setDefaultRisk(risk == cellRisk);
}
}
});
} else {
setGraphic(null);
}
}
If you have a lot of table items (like, thousands), the for-loop could become a performance issue. So, alternatively, you can implement radio-button-like behavior by defining a Risk field or property independent of the RadioButtonCell class which keeps track of the previous selection:
ObjectProperty<Risk> previousDefaultRisk = new SimpleObjectProperty<>();
columnIsDefaultRisk.setCellFactory(
c -> new RadioButtonCell(previousDefaultRisk));
And your RadioButtonCell class would change to look like this:
public class RadioButtonCell extends TableCell<Risk, Boolean> {
private final ObjectProperty<Risk> previousDefaultRisk;
public RadioButtonCell(ObjectProperty<Risk> previousDefaultRisk) {
this.previousDefaultRisk = previousDefaultRisk;
}
#Override
protected void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (!empty && item != null) {
RadioButton radioButton = new RadioButton();
radioButton.setSelected(item);
setGraphic(radioButton);
radioButton.selectedProperty().addListener(
(o, old, selected) -> {
if (selected) {
if (previousDefaultRisk.get() != null) {
previousDefaultRisk.get().setDefaultRisk(false);
}
Risk risk = getTableRow().getItem();
risk.setIsDefaultRisk(true);
previousDefaultRisk.set(risk);
}
});
} else {
setGraphic(null);
}
}
}
Note: It is Java convention that non-static field names should always start with a lowercase letter. Following these conventions will make your code easier for others to read, including Stack Overflow readers.

Related

JavaFX can not clear items from listview

I'm using a ListView in my project and wanted to add a context menu to each list item so that each can be removed individually. When using the following code this appears to work just fine:
postList.setCellFactory(lv -> {
ListCell<Result> cell = new ListCell<>();
ContextMenu contextMenu = new ContextMenu();
StringBinding stringBinding = new StringBinding() {
{
super.bind(cell.itemProperty().asString());
}
#Override
protected String computeValue() {
if (cell.itemProperty().getValue() == null) {
return "";
}
return cell.itemProperty().getValue().getTitle();
}
};
cell.textProperty().bind(stringBinding);
MenuItem deleteItem = new MenuItem();
deleteItem.textProperty().bind(Bindings.format("Delete item"));
deleteItem.setOnAction(event -> postList.getItems().remove(cell.getItem()));
contextMenu.getItems().addAll(openPermalink, openSubreddit, openURL, deleteItem);
cell.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -> {
if (isNowEmpty) {
cell.setContextMenu(null);
} else {
cell.setContextMenu(contextMenu);
}
});
return cell;
});
However, after clearing the post list - although the items appear to be removed - when another is added all of the removed items re-appear and the item to be added is not displayed.
Any items what could be causing this? It only happens when I set the cell factory and is fine otherwise.
I recorded a small gif to help better explain the issue:
Thank you!
Edit: It appears that the issue is mainly to do with this segment
StringBinding stringBinding = new StringBinding() {
{
super.bind(cell.itemProperty().asString());
}
#Override
protected String computeValue() {
if (cell.itemProperty().getValue() == null) {
return "";
}
return cell.itemProperty().getValue().getTitle();
}
};
As is seems that even though the items are there they have an empty display title
If you use ListCell.updateItem() workflow instead of the StringBinding it should work:
ListCell< Result > cell = new ListCell< Result >() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item.getValue());
} else {
setText("");
}
}
};
Your binding workflow seems to create an unnecessary dependency which blocks deletion.
P.S.: why do you use binding for static text in deleteItem? Just assign the value directly:
MenuItem deleteItem = new MenuItem();
deleteItem.setText("Delete item");

NullPointerException in TreeItem.branchExpandedEvent() trying to getGraphic

I'm trying to call event.getSource().getGraphic() in a branch expanded event of a TreeItem so that I can set a different icon, but I keep getting NullPointerException, and I can't figure out why. I can set the icon successfully when setting up the cell factory, but when I listen for the branch expanded event to do the same, it doesn't work. Here's how I'm setting up the tree (from the initialize event in my controller):
tree.setCellFactory(param -> new TreeCell<File>() {
#Override
public void updateItem(File item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText("");
setGraphic(null);
} else {
setText(item.getName());
Image icon = new Image(getClass().getResourceAsStream("folder.png"));
setGraphic(new ImageView(icon));
}
}
});
This works fine and dandy.
Here's my event listener where the ImageView is null for some reason (also being added in the initialize event in my TreeView controller):
File home = new File(System.getProperty("user.home"));
TreeItem<File> root = new TreeItem<>(home);
tree.setRoot(root);
root.addEventHandler(TreeItem.branchExpandedEvent(), event -> {
TreeItem source = event.getSource();
ImageView img = (ImageView)source.getGraphic(); // this is null!
Image icon = Image(getClass().getResourceAsStream("folder-open.png"));
img.setImage(icon);
});
Does anyone have any idea what I'm doing wrong? I'm using Java 1.8.
You're accessing the graphic property of the TreeItem, not the graphic property of the TreeCell that is set to a value != null. You need to handle this in the TreeCell instead. Furthermore you probably should use the disclosureNode property to replace the arrow. Also it's better to reuse the Images:
final Image closedImage = new Image(getClass().getResourceAsStream("folder.png"));
final Image openImage = new Image(getClass().getResourceAsStream("folder-open.png"));
tree.setCellFactory(param -> new TreeCell<File>() {
{
final ImageView imageView = new ImageView();
imageView.setFitWidth(20);
imageView.setFitHeight(20);
final ChangeListener<Boolean> expansionListener = new WeakChangeListener<>((o, oldValue, newValue) -> {
imageView.setImage(newValue ? openImage : closedImage);
});
// add change listener to expanded property of item
treeItemProperty().addListener((o, oldValue, newValue) -> {
if (oldValue != null) {
oldValue.expandedProperty().removeListener(expansionListener);
}
if (newValue != null) {
newValue.expandedProperty().addListener(expansionListener);
expansionListener.changed(null, null, newValue.isExpanded()); // trigger for initial value
}
});
setDisclosureNode(imageView);
}
#Override
public void updateItem(File item, boolean empty) {
super.updateItem(item, empty);
setText((empty || item == null) ? "" : item.getName());
}
});

Javafx: update TableCell

I have a TableView and a custom MyTableCell extends CheckBoxTreeTableCell<MyRow, Boolean>, In this cell is #Overridden the updateItem method:
#Override
public void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if(!empty){
MyRow currentRow = geTableRow().getItem();
Boolean available = currentRow.isAvailable();
if (!available) {
setGraphic(null);
}else{
setGraphic(super.getGraphic())
}
} else {
setText(null);
setGraphic(null);
}
}
I have a ComboBox<String> where I have some items, and when I change the value of that combobox I want to set the visibility of the checkboxes depending on selected value. So I have a listener:
comboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue.equals("A") || newValue.equals("S")) {
data.stream().filter(row -> row.getName().startsWith(newValue)).forEach(row -> row.setAvailable(false));
}
});
The data is an ObservableList<MyRow>
This is just an example and a simplified version of my code
When I change the value in comboBox the table's the chekboxes don't disappear until I scroll or click on that cell. There is a "sollution" to call table.refresh(); but I don't want to refresh the whole table, when I want to refresh just one cell. So I tried to adding some listeners to trigger the updateItem, but I failed at every attempt. Do you have any idea how can I trigger the update mechanism for one cell, not for the whole table?
Bind the cell's graphic, instead of just setting it:
private Binding<Node> graphicBinding ;
#Override
protected void updateItem(Boolean item, boolean empty) {
graphicProperty().unbind();
super.updateItem(item, empty) ;
MyRow currentRow = getTableRow().getItem();
if (empty) {
graphicBinding = null ;
setGraphic(null);
} else {
graphicBinding = Bindings
.when(currentRow.availableProperty())
.then(super.getGraphic())
.otherwise((Node)null);
graphicProperty.bind(graphicBinding);
}
}

java.lang.IllegalArgumentException: argument type mismatch javafx

I am trying to add a ToolTip ui control to TableColumn of a TableView.
I am getting following exception. Please help.
SEVERE: Failed to load skin 'com.sun.javafx.scene.control.skin.TooltipSkin' for control Label[id=null, styleClass=tooltip]'123'
java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
Following is the code.
TableColumn<HomeDraftRequestModel, Long> revenueColId = (TableColumn) getReqForMyActionTableView()
.getColumns().get(8);
revenueColId.setCellFactory(new Callback<TableColumn<HomeDraftRequestModel, Long>, TableCell<HomeDraftRequestModel, Long>>() {
#Override
public TableCell<HomeDraftRequestModel, Long> call(
TableColumn<HomeDraftRequestModel, Long> param) {
Label label = new Label();
return new TableCell<HomeDraftRequestModel, Long>() {
#Override
protected void updateItem(Long item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
label.setText(item + "");
Tooltip toopTip = new Tooltip(item + "");
Tooltip.install(label, toopTip);
label.setUnderline(true);
label.setCursor(Cursor.HAND);
label.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent arg0) {
label.setTooltip(toopTip);
}
});
setGraphic(label);
}
}
};
}
});
All the useful functionality in a Label is also defined directly in a TableCell (they are both subclasses of Labeled). So you can get rid of the label, and just call the methods directly on the TableCell. You also don't need the mouse listener: the tooltip knows when to display itself. Just call setTooltip(...) to enable it.
The following should work:
protected void updateItem(Long item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setTooltip(null);
} else {
setText(item + "");
Tooltip toolTip = new Tooltip(item + "");
setUnderline(true);
setCursor(Cursor.HAND);
setTooltip(toolTip);
}
}
I'm not entirely sure why you were getting the exception you were getting; but it should help to simplify the code and use something more "standard".

TableView With An Embedded ListView

I'm trying to make a TableView with an embedded ListView, but I'm not exactly sure what to do, I've been researching how to embed Buttons into a TableColumn and I've seen that I should create a custom class that extends TableColumn and overrides updateItem().
I have a:
#FXML
private TableColumn<FoodModel, ObservableSet<Food>> storeFood;
for the tableColumn, set by the FXML editor. It's value is set by this.storeFood.setCellValueFactory(val -> val.getValue().getFood); and this.storeFood.setCellFactory(value -> new ListViewCell<>()); upon initialization.
I've been encountering a problem in which the list on screen is not being populated. Can I have a checklist of things to do to embed a list into a TableColumn?
Cell:
private static final class ListViewCell<T, V> extends TableCell<T, V> {
private ListView<T> list;
ListViewCell() {
this.list = new ListView<>();
this.list.setPrefHeight(60);
}
#Override
protected void updateItem(V item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setGraphic(this.list);
}
}
}

Categories