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);
}
}
Related
i am trying to put elements on a listview and treeview with javafx, but both controls wont refresh theyre content. i am using an obvservable list to control the items and every time i delete one item, the listview or treeview removes it from the datasource. but the view is not updating. i am still seeing all the items. the only difference is, the removed item can not be selected any more. for example link 2 shows the collaped item list. image 1 shows the items before they are collaped. the items are collapsed but the old entry is still visible. does anybody know a solution for this problem. thank you all for helping me
link 1: treeview is not collapsed
link 2: treeview is collapsed but not updating old view
this is the custom cell factory i use to display a listview:
public ListCell<T> call(final ListView<T> param) {
ListCell<T> cell = new ListCell<T>(){
#Override
protected void updateItem(final T persistentObject, final boolean empty) {
super.updateItem(persistentObject, empty);
if(persistentObject instanceof POProcessStep){
POProcessStep poProcessStep = (POProcessStep) persistentObject;
if (persistentObject != null) {
super.setText(poProcessStep.getId() + " - " + poProcessStep.getTitle());
}
}else if(persistentObject instanceof POProcess){
POProcess poProcess = (POProcess) persistentObject;
if (persistentObject != null) {
super.setText(poProcess.getId() + " - " + poProcess.getTitle());
}
}else if(persistentObject instanceof POCategory){
POCategory poCategory = (POCategory) persistentObject;
if(persistentObject != null){
super.setText(poCategory.getId() + " - " + poCategory.getTitle());
}
}else if(persistentObject instanceof String){
if(persistentObject != null){
super.setText(String.valueOf(persistentObject));
}
}
super.setGraphic(null);
}
};
return cell;
}
Your cell factory's updateItem(...) needs to handle the case where the cell is empty. This will be exactly the scenario when an item is removed (or becomes empty because a node in the TreeView was collapsed) and the cell that previously showed an item is reused as an empty cell:
public ListCell<T> call(final ListView<T> param) {
ListCell<T> cell = new ListCell<T>(){
#Override
protected void updateItem(final T persistentObject, final boolean empty) {
super.updateItem(persistentObject, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
// ... rest of your code.
}
}
}
return cell ;
}
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.
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());
}
});
I am building a JavaFX app with a TableView, and I want to it dynamically change color depending on different user selections. I can get it to initially populate with colored data, but refreshing it keeps original colors.
This is the basic functionality of my method that is called dynamically each time the user changes something:
SessionsTableView.getItems().clear();
ObservableList<SessionItem> newsessionitems = FXCollections.observableArrayList();
for (SessionPart x : AllSessionParts) {
tableitems.add(new SessionItem(count, x.name, x.getdurationasString(true, 150.0), getambiencetext(x), x.goals_getCurrentAsString(true, 150.0)));
newsessionitems.add(x);
count++;
}
SessionsTableView.setItems(newsessionitems);
Methods return different String values which are tested in my cell value factory to determine color:
DurationColumn.setCellFactory(new Callback<TableColumn<SessionItem, String>, TableCell<SessionItem, String>>() {
#Override
public TableCell<SessionItem, String> call(TableColumn<SessionItem, String> param) {
return new TableCell<SessionItem, String>() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (! isEmpty()) {
switch (item) {
case "No Duration Set":
setTextFill(Color.RED);
break;
case "Short Duration Set":
setTextFill(Color.YELLOW);
break;
default:
setTextFill(Color.BLACK);
break;
}
setText(item);
}
}
};
}
});
JavaFX colors the text based on the String values provided when initialially populated, but not when called again. My override of the updateitem(String, boolean) method is called, and the text values are changed, but the colors of even the changed text are not updated/refreshed.
How do I get the colors to change dynamically?
I figured it out. Instead of using the setTextFill() method which didn't work for me, I used setStyle("-fx-text-fill:"). This seemed to solve the problem. The table now dynamically refreshes as I intended it to.
DurationColumn.setCellFactory(new Callback<TableColumn<SessionItem, String>, TableCell<SessionItem, String>>() {
#Override
public TableCell<SessionItem, String> call(TableColumn<SessionItem, String> param) {
return new TableCell<SessionItem, String>() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (! isEmpty()) {
switch (item) {
case "No Duration Set":
setTextFill(Color.RED); // Doesn't Work
setStyle("-fx-text-fill: red") // Does Work
break;
}
setText(item);
}
}
};
}
});
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".