Suppose that I have a map collection:
ObserableHashMap<K,V> map = FXCollections.observableHashMap();
I put 1 record into this map during fxml controller initialization, then wrap it as ObservableList:
ObservableList<ObserableHashMap.Entry<K,V>> list = FXCollections.observableArrayList(map.entrySet());
then setitems for my tableView.setItems(list);
Everything is fine when I run this JavaFX app and 1 record is showing.
Question is that:
When I add more records later to my map, my TableView will not refresh these records.
How could I bind a dynamical map collection into my TableView?
Thanks
If you use an ObservableList of ObservableMaps as your TableView's data structure
ObservableList<ObservableMap> rowMaps = FXCollections.observableArrayList();
tableView.setItems(rowMaps);
and implement your own ObservableMapValueFactory
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableMap;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.util.Callback;
public class ObservableMapValueFactory<V> implements
Callback<TableColumn.CellDataFeatures<ObservableMap, V>, ObservableValue<V>> {
private final Object key;
public ObservableMapValueFactory(Object key) {
this.key = key;
}
#Override
public ObservableValue<V> call(CellDataFeatures<ObservableMap, V> features) {
final ObservableMap map = features.getValue();
final ObjectProperty<V> property = new SimpleObjectProperty<V>((V) map.get(key));
map.addListener(new MapChangeListener<Object, V>() {
public void onChanged(Change<?, ? extends V> change) {
if (key.equals(change.getKey())) {
property.set((V) map.get(key));
}
}
});
return property;
}
}
and then set it as the cell value factory for your column(s)
column.setCellValueFactory(new ObservableMapValueFactory<String>(columnId));
all changes to your data are reflected in the TableView, even changes only affecting the ObservableMaps.
You can bind a map directly to a TableView, consider this example from the JavaFX documentation :
import java.util.HashMap;
import java.util.Map;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Group;
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.control.cell.MapValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class TableViewSample extends Application {
public static final String Column1MapKey = "A";
public static final String Column2MapKey = "B";
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(300);
stage.setHeight(500);
final Label label = new Label("Student IDs");
label.setFont(new Font("Arial", 20));
TableColumn<Map, String> firstDataColumn = new TableColumn<>("Class A");
TableColumn<Map, String> secondDataColumn = new TableColumn<>("Class B");
firstDataColumn.setCellValueFactory(new MapValueFactory(Column1MapKey));
firstDataColumn.setMinWidth(130);
secondDataColumn.setCellValueFactory(new MapValueFactory(Column2MapKey));
secondDataColumn.setMinWidth(130);
TableView table_view = new TableView<>(generateDataInMap());
table_view.setEditable(true);
table_view.getSelectionModel().setCellSelectionEnabled(true);
table_view.getColumns().setAll(firstDataColumn, secondDataColumn);
Callback<TableColumn<Map, String>, TableCell<Map, String>>
cellFactoryForMap = new Callback<TableColumn<Map, String>,
TableCell<Map, String>>() {
#Override
public TableCell call(TableColumn p) {
return new TextFieldTableCell(new StringConverter() {
#Override
public String toString(Object t) {
return t.toString();
}
#Override
public Object fromString(String string) {
return string;
}
});
}
};
firstDataColumn.setCellFactory(cellFactoryForMap);
secondDataColumn.setCellFactory(cellFactoryForMap);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table_view);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
private ObservableList<Map> generateDataInMap() {
int max = 10;
ObservableList<Map> allData = FXCollections.observableArrayList();
for (int i = 1; i < max; i++) {
Map<String, String> dataRow = new HashMap<>();
String value1 = "A" + i;
String value2 = "B" + i;
dataRow.put(Column1MapKey, value1);
dataRow.put(Column2MapKey, value2);
allData.add(dataRow);
}
return allData;
}
}
More information can be found here
The answer from ItachiUchiha use the columns as keys and the rows as individual maps. If you'd like one map with the rows as keys->values, you'll have to add a listener to the map that will change the list when you add or delete. I did something similar here. https://stackoverflow.com/a/21339428/2855515
Related
I just started app developing recently and stumbled upon a problem that I basically can't figure out : https://rubensousa.github.io/2016/08/viewpagercards
He instructed that on CardPagerAdapter.java in instantiateItem, I need to set the data according to the position. But how do I do it?
I want the first card to have a title of "FIRST CARD" while the second "SECOND CARD" and so on.. hope someone could help.
CardPagerAdapter.java
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class CardPagerAdapter extends PagerAdapter implements CardAdapter {
private List<CardView> mViews;
private List<CardItem> mData;
private float mBaseElevation;
public CardPagerAdapter() {
mData = new ArrayList<>();
mViews = new ArrayList<>();
}
public void addCardItem(CardItem item) {
mViews.add(null);
mData.add(item);
}
public float getBaseElevation() {
return mBaseElevation;
}
#Override
public CardView getCardViewAt(int position) {
return mViews.get(position);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View view = LayoutInflater.from(container.getContext())
.inflate(R.layout.fragment_adapter, container, false);
container.addView(view);
bind(mData.get(position), view);
CardView cardView = (CardView) view.findViewById(R.id.cardView);
if (mBaseElevation == 0) {
mBaseElevation = cardView.getCardElevation();
}
cardView.setMaxCardElevation(mBaseElevation * MAX_ELEVATION_FACTOR);
mViews.set(position, cardView);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
mViews.set(position, null);
}
private void bind(CardItem item, View view) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView description = (TextView) view.findViewById(R.id.description);
Button button = (Button) view.findViewById(R.id.button);
title.setText(item.getTitle());
description.setText(item.getText());
button.setText(item.getButton());
}
}
I'm having issues to render a SVG Image in a TableView with a CellFactory.
Im using this code here, but it don't work, the svg image is scaled, but it don't resize.
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
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.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.shape.SVGPath;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
public class SVGTable extends Application {
private ObservableList<SVGExample> examples;
public static void main(String[] args) {
launch(args);
}
public SVGTable() {
examples = FXCollections.observableArrayList();
examples.addAll(new SVGExample(289),
new SVGExample(42),
new SVGExample(120));
}
#Override
public void start(Stage primaryStage) throws Exception {
AnchorPane pane = new AnchorPane();
Scene scene = new Scene(pane);
TableView<SVGExample> tableView = new TableView<>();
tableView.setMinWidth(500);
tableView.setMinHeight(400);
tableView.setItems(examples);
final TableColumn<SVGExample, Integer> ping = new TableColumn<>("Ping");
ping.setCellValueFactory(new PropertyValueFactory<>("ping"));
ping.setCellFactory(param -> new PingCell());
tableView.getColumns().add(ping);
pane.getChildren().add(tableView);
primaryStage.setScene(scene);
primaryStage.show();
}
public class SVGExample {
private final IntegerProperty ping = new SimpleIntegerProperty();
public SVGExample(int ping) {
setPing(ping);
}
public int getPing() {
return ping.get();
}
public IntegerProperty pingProperty() {
return ping;
}
public void setPing(int ping) {
this.ping.set(ping);
}
}
public class PingCell extends TableCell<SVGExample, Integer> {
private HBox hBox = new HBox();
private Label label;
private int oldValue;
private PingCell() {
label = new Label();
hBox.setAlignment(Pos.CENTER_LEFT);
oldValue = Integer.MIN_VALUE;
}
#Override
protected void updateItem(final Integer item, final boolean empty) {
if (item != null) {
label.setText(item + "ms");
int i = (item + 50) / 100;
if (i < 1)
i = 1;
if (4 < i)
i = 4;
if (i != oldValue) {
SVGPath svgPath1 = new SVGPath();
svgPath1.setContent("M149.2,8.3L127-13.9c42.4-42.4,98.7-65.8,158.5-65.8c59.8,0,116.1,23.4,158.5,65.8L421.8,8.3c-36.5-36.5-84.9-56.6-136.3-56.6C234.1-48.2,185.7-28.1,149.2,8.3z");
SVGPath svgPath2 = new SVGPath();
svgPath2.setContent("M190.9,50.1l-22.2-22.2C200-3.4,241.4-20.6,285.5-20.6c44.1,0,85.5,17.2,116.8,48.4l-22.2,22.2c-25.3-25.3-58.9-39.2-94.6-39.2C249.8,10.8,216.2,24.8,190.9,50.1z");
SVGPath svgPath3 = new SVGPath();
svgPath3.setContent("M232.7,91.8l-22.2-22.2c20.1-20.1,46.7-31.1,75-31.1s55,11.1,75,31.1l-22.2,22.2c-14.1-14.1-32.9-21.9-52.8-21.9C265.6,69.9,246.8,77.7,232.7,91.8z");
SVGPath svgPath4 = new SVGPath();
svgPath4.setContent("M285.5,98.1c-12.8,0-24.5,5.2-32.9,13.6l32.9,32.9l32.9-32.9C310,103.3,298.3,98.1,285.5,98.1z");
Shape s = SVGPath.union(SVGPath.union(SVGPath.union(svgPath1, svgPath2), svgPath3), svgPath4);
s.setScaleX(0.1);
s.setScaleY(0.1);
hBox.getChildren().clear();
hBox.getChildren().addAll(s, label);
}
setGraphic(hBox);
}
}
}
}
After run, it's look like this:
You can wrap the Shape in a Group to force re-size of layout bounds.
hBox.getChildren().addAll(new Group(s), label);
Scale is a type of transform and according to Javadocs:
Any transform, effect, or state applied to a Group will be applied to all children of that group. Such transforms and effects will NOT be included in this Group's layout bounds, however if transforms and effects are set directly on children of this Group, those will be included in this Group's layout bounds.
In a GXT Grid I am attempting to use RowEditing and the CheckBoxSelectionModel. The Sencha Explorer Demo has examples of these in the Row Editable Grid and CheckBox Grid samples, but they don't show an example that includes a combination of these features. When I use both features on the same grid I am not getting the behavior that I had expected. If I click on the "selection" checkbox the row is placed into edit mode, where I would have expected the checkbox to just change from checked to unchecked or vice versa. In addition, when the row is placed into edit mode there is corruption on the line. Here is an example of a row from the grid prior to clicking on any of the values in that row:
and here is that row after clicking on one of the values:
Does anyone have any experience with this?
Update
Here's a sample class which demonstrates the issue:
package org.greatlogic.gxtgrid.client;
import java.util.ArrayList;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.sencha.gxt.core.client.IdentityValueProvider;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.grid.CheckBoxSelectionModel;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.grid.GridView;
import com.sencha.gxt.widget.core.client.grid.editing.GridRowEditing;
public class GXTGrid implements EntryPoint {
//-------------------------------------------------------------------------
#Override
public void onModuleLoad() {
ListStore<Pet> listStore = new ListStore<>(new ModelKeyProvider<Pet>() {
#Override
public String getKey(Pet pet) {
return Integer.toString(pet.getPetId());
}
});
IdentityValueProvider<Pet> ivp = new IdentityValueProvider<>();
CheckBoxSelectionModel<Pet> sm = new CheckBoxSelectionModel<>(ivp);
ArrayList<ColumnConfig<Pet, ?>> ccList = new ArrayList<>();
ccList.add(sm.getColumn());
ColumnConfig<Pet, String> cc1;
cc1 = new ColumnConfig<>(Pet.getPetNameValueProvider(), 100, "Name");
ccList.add(cc1);
ColumnModel<Pet> columnModel = new ColumnModel<>(ccList);
Grid<Pet> grid = new Grid<>(listStore, columnModel);
grid.setSelectionModel(sm);
grid.setView(new GridView<Pet>());
GridRowEditing<Pet> gre = new GridRowEditing<>(grid);
gre.addEditor(cc1, new TextField());
listStore.add(new Pet(1, "Lassie"));
listStore.add(new Pet(2, "Scooby"));
listStore.add(new Pet(3, "Snoopy"));
ContentPanel contentPanel = new ContentPanel();
contentPanel.add(grid);
RootLayoutPanel.get().add(contentPanel);
}
//-------------------------------------------------------------------------
private static class Pet {
private int _petId;
private String _petName;
public static ValueProvider<Pet, String> getPetNameValueProvider() {
return new ValueProvider<Pet, String>() {
#Override
public String getPath() {
return "Pet.PetName";
}
#Override
public String getValue(Pet pet) {
return pet._petName;
}
#Override
public void setValue(Pet pet, final String value) {
pet._petName = value;
}
};
}
public Pet(int petId, final String petName) {
_petId = petId;
_petName = petName;
}
public int getPetId() {
return _petId;
}
}
//-------------------------------------------------------------------------
}
This behavior of GridRowEditing with CheckBoxSelectionModel is completely normal.
I have used you code to try some things. I think the best way to use GridRowEditing and CheckBoxSelectionModel is, as I guessed, to start editing on double click, as nothing is provided to do it with just one click yet. To do so just add
gre.setClicksToEdit(ClicksToEdit.TWO);
Otherwise, if you really do not want to use two clicks to start editing, you can also use InlineRowEditing, which will enable you to use CheckBoxSelectionModel as you want.
Eventually, you might be able to override the whole behavior of GridRowEditing to handle CheckBoxSelectionModel properly on one click only, but it would be more complicated and require more specific knowledge of GXT framework that I don't have.
I haven't found a solution to this problem using the CheckBoxSelectionModel, and so I decided to try another approach, namely, adding a column to the grid that contains a checkbox, and handling the state of the selections manually. To do this I found that I needed to respond to a few events, which wasn't too bad. Here's a new version of the sample code, which should provide a starting point for a real implementation:
import java.util.ArrayList;
import java.util.TreeSet;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.sencha.gxt.cell.core.client.form.CheckBoxCell;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.core.client.dom.XElement;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.form.CheckBox;
import com.sencha.gxt.widget.core.client.form.Field;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.grid.CellSelectionModel;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.grid.GridView;
import com.sencha.gxt.widget.core.client.grid.editing.GridRowEditing;
public class GXTGrid implements EntryPoint {
//-------------------------------------------------------------------------
private ListStore<Pet> _listStore;
private TreeSet<Integer> _selectedPetIdSet;
//-------------------------------------------------------------------------
#Override
public void onModuleLoad() {
_selectedPetIdSet = new TreeSet<>();
_listStore = new ListStore<>(new ModelKeyProvider<Pet>() {
#Override
public String getKey(Pet pet) {
return Integer.toString(pet.getPetId());
}
});
final CellSelectionModel<Pet> sm = new CellSelectionModel<>();
ArrayList<ColumnConfig<Pet, ?>> ccList = new ArrayList<>();
ValueProvider<Pet, Boolean> selectValueProvider;
selectValueProvider = new ValueProvider<GXTGrid.Pet, Boolean>() {
#Override
public String getPath() {
return "SelectCheckBox";
}
#Override
public Boolean getValue(Pet pet) {
return _selectedPetIdSet.contains(pet.getPetId());
}
#Override
public void setValue(Pet pet, final Boolean selected) { //
}
};
ColumnConfig<Pet, Boolean> cc0 = new ColumnConfig<>(selectValueProvider, 23, "");
CheckBoxCell checkBoxCell = new CheckBoxCell() {
#Override
protected void onClick(XElement parent, final NativeEvent event) {
super.onClick(parent, event);
Pet pet = sm.getSelectedItem();
if (!_selectedPetIdSet.remove(pet.getPetId())) {
_selectedPetIdSet.add(pet.getPetId());
}
}
};
cc0.setCell(checkBoxCell);
cc0.setFixed(true);
cc0.setHideable(false);
cc0.setMenuDisabled(true);
cc0.setResizable(false);
cc0.setSortable(false);
ccList.add(cc0);
ColumnConfig<Pet, String> cc1;
cc1 = new ColumnConfig<>(Pet.getPetNameValueProvider(), 100, "Name");
ccList.add(cc1);
ColumnModel<Pet> columnModel = new ColumnModel<>(ccList);
Grid<Pet> grid = new Grid<>(_listStore, columnModel);
grid.setSelectionModel(sm);
grid.setView(new GridView<Pet>());
GridRowEditing<Pet> gre = new GridRowEditing<>(grid);
Field<Boolean> checkBox = new CheckBox();
checkBox.setEnabled(false);
gre.addEditor(cc0, checkBox);
gre.addEditor(cc1, new TextField());
_listStore.add(new Pet(1, "Lassie"));
_listStore.add(new Pet(2, "Scooby"));
_listStore.add(new Pet(3, "Snoopy"));
ContentPanel contentPanel = new ContentPanel();
contentPanel.add(grid);
RootLayoutPanel.get().add(contentPanel);
}
//-------------------------------------------------------------------------
private static class Pet {
private int _petId;
private String _petName;
public static ValueProvider<Pet, String> getPetNameValueProvider() {
return new ValueProvider<Pet, String>() {
#Override
public String getPath() {
return "Pet.PetName";
}
#Override
public String getValue(Pet pet) {
return pet._petName;
}
#Override
public void setValue(Pet pet, final String value) {
pet._petName = value;
}
};
}
public Pet(int petId, final String petName) {
_petId = petId;
_petName = petName;
}
public int getPetId() {
return _petId;
}
}
//-------------------------------------------------------------------------
}
is there a way to have panels with different heights in an accordion in JavaFX? I would like to know how to do it. I've googled it but I haven't found what I need.
you can do this with setPrefHeight of pane....
try this.
pane.setPrefHeight(400);
Try this:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.TitledPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class TitledPaneSample extends Application
{
final String[] imageNames = new String[]{
"Apples", "Flowers", "Leaves"};
final Image[] images = new Image[imageNames.length];
final ImageView[] pics = new ImageView[imageNames.length];
final TitledPane[] tps = new TitledPane[imageNames.length];
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(Stage stage)
{
stage.setTitle("TitledPane");
Scene scene = new Scene(new Group(), 380, 380);
scene.setFill(Color.GHOSTWHITE);
final Accordion accordion = new Accordion();
for (int i = 0; i < imageNames.length; i++)
{
images[i] = new Image(getClass().getResourceAsStream(imageNames[i]
+ ".jpg"));
pics[i] = new ImageView(images[i]);
tps[i] = new TitledPane(imageNames[i], pics[i]);
tps[i].setMinHeight(i * 100);
}
accordion.getPanes().addAll(tps);
accordion.setExpandedPane(tps[0]);
Group root = (Group) scene.getRoot();
root.getChildren().add(accordion);
stage.setScene(scene);
stage.show();
}
}
All you need in addition to the above code is to have the three files placed at the correct location.
I need to change the style of arbitrary cells in a TableView which has an variable number of columns. The code below shows the basic problem.
The ExampleRow class is proxy for the real data which comes from a spreadsheet, it's other function is to hold the highlighting information. Since I can't know how many columns there will be I just hold a list of columns that should be highlighted (column re-arrangement won't be supported). The ExampleTableCell class just sets the text for the cell and applies the highlight if needed.
If I set a highlight before the table gets drawn [cell (2,2)] then the cell correctly gets displayed with red text when the application starts. The problem is clicking the button sets cell (1,1) to be highlighted but the table doesn't change. If I resize the application window to nothing then open it back up again the highlighting of cell (1,1) is correctly drawn - presumably because this process forces a full redraw.
What I would like to know is how can I trigger the table to redraw newly highlighted cells (or all visible cells) so the styling is correct?
TIA
package example;
import java.util.HashSet;
import java.util.Set;
import javafx.application.Application;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;
public class CellHighlightExample extends Application {
private final int columnCount = 4;
private final int rowCount = 5;
private TableView<ExampleRow> table = new TableView<>();
#Override
public void start(Stage stage) {
BorderPane root = new BorderPane();
Scene scene = new Scene(root);
Callback<TableColumn.CellDataFeatures<ExampleRow, String>, ObservableValue<String>> cellValueFactory = new Callback<TableColumn.CellDataFeatures<ExampleRow, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<ExampleRow, String> p) {
int row = p.getValue().getRow();
int col = p.getTableView().getColumns().indexOf(p.getTableColumn());
return new SimpleObjectProperty<>("(" + row + ", " + col + ")");
}
};
Callback<TableColumn<ExampleRow, String>, TableCell<ExampleRow, String>> cellFactory = new Callback<TableColumn<ExampleRow, String>, TableCell<ExampleRow, String>>() {
#Override
public TableCell<ExampleRow, String> call(TableColumn<ExampleRow, String> p) {
return new ExampleTableCell<>();
}
};
for (int i = 0, n = columnCount; i < n; i++) {
TableColumn<ExampleRow, String> column = new TableColumn<>();
column.setCellValueFactory(cellValueFactory);
column.setCellFactory(cellFactory);
table.getColumns().add(column);
}
ObservableList<ExampleRow> rows = FXCollections.observableArrayList();
for (int i = 0, n = rowCount; i < n; i++) {
ExampleRow row = new ExampleRow(i);
//Force a cell to be highlighted to show that highlighting works.
if (i == 2) { row.addHighlightedColumn(2); }
rows.add(row);
}
table.setItems(rows);
Button b = new Button("Click to Highlight");
b.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
ExampleRow row = table.getItems().get(1);
row.addHighlightedColumn(1);
//How to trigger a redraw of the table or cell to reflect the new highlighting?
}
});
root.setTop(b);
root.setCenter(table);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
private class ExampleTableCell<S extends ExampleRow, T extends String> extends TableCell<S, T> {
#Override
public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (item == null) {
setText(null);
setGraphic(null);
} else {
setText(item);
int colIndex = getTableView().getColumns().indexOf(getTableColumn());
ExampleRow row = getTableView().getItems().get(getIndex());
if (row.isHighlighted(colIndex)) {
setTextFill(Color.RED);
}
}
}
}
private class ExampleRow {
private SimpleIntegerProperty row;
private Set<Integer> highlightedColumns = new HashSet<>();
public ExampleRow(int row) {
this.row = new SimpleIntegerProperty(row);
}
public int getRow() { return row.get(); }
public void setRow(int row) { this.row.set(row); }
public SimpleIntegerProperty rowProperty() { return row; }
public boolean isHighlighted(int col) {
if (highlightedColumns.contains(col)) {
return true;
}
return false;
}
public void addHighlightedColumn(int col) {
highlightedColumns.add(col);
}
}
}
There are lots of discussions about this problem, namely refreshing tableview after altering the item(s).
See
JavaFX 2.1 TableView refresh items
Issues
http://javafx-jira.kenai.com/browse/RT-21822
http://javafx-jira.kenai.com/browse/RT-22463
http://javafx-jira.kenai.com/browse/RT-22599
The solution is to trigger internal tableview update method. Some suggests to remove tableview items and add them again vs.. but the simplest workaround for your case seems to:
b.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
ExampleRow row = table.getItems().get(1);
row.addHighlightedColumn(1);
//How to trigger a redraw of the table or cell to reflect the new highlighting?
// Workaround
table.getColumns().get(0).setVisible(false);
table.getColumns().get(0).setVisible(true);
}
});
which found in issue comments linked above. Is this a really workaround or illusion of it? You need to dig deeper yourself.