I want to completely view updates when a row is selected in a CellTable. How can this be done? In the following test case, using NoSelectionModel, the view is still updated: clicking on a row changes the background and border colors of the row until another row is clicked.
CellTable<String> table = new CellTable<String>();
TextColumn<String> column = new TextColumn<String>()
{
#Override
public String getValue(String string)
{
return string;
}
};
table.addColumn(column);
List<String> sampleData = Arrays.asList("foo", "bar", "baz");
table.setRowData(sampleData);
final NoSelectionModel<String> selectionModel = new NoSelectionModel<String>();
table.setSelectionModel(selectionModel);
RootPanel.get().add(table);
I've also attempted to subclass SingleSelectionModel with empty override methods, without success.
I can fake the behavior I want by providing empty CSS stylings for selected rows, but that method seems hack-ish.
What you're seeing is the keyboard-selection highlighting (really useful when you're not using the mouse to interact with the table).
You can disable it using setKeyboardSelectionPolicy(KeyboardSelectionPolicy.DISABLED)
Related
I'm writing a seating chart program using JavaFX. I have a table that keeps a list of students together that holds their name, grade, and whether they are present or absent (using a checkbox). I have a delete button that allows me to delete the students from the list. This works fine, however, whenever I delete the student object, the checkbox does not go along with it. I'm not sure what I would need to add to get that to work. Here is a snippet of the delete code. There are also two images below that show my problem. This is my first post so please let me know if I missed something. Please help! Thanks!
ObservableList<Student> items, sel;
items = currentTable.getItems();
sel = currentTable.getSelectionModel().getSelectedItems();
Student s = new Student("", "", 0, "");
for (Student p : sel) {
items.remove(p);
s = p;
}
Before Delete
After Delete
This has nothing to do with the delete or remove method. It has to do with what you did in TableColumn.setCellFactory().
To get the checkbox you shown, you should have used (in general) one of the two methods:
Overriding updateItem() in TableCell while setting Cell Factory
There is this empty parameter in updateItem() which indicates whether the row is empty or not. You need to use that to determine when not to show the checkbox.
column.setCellFactory(col -> {
return new TableCell<Foo, Boolean>() {
final CheckBox checkBox = new CheckBox();
#Override
public void updateItem(final Boolean selected, final boolean empty) {
super.updateItem(selected, empty);
if (!this.isEmpty()) {
setGraphic(checkBox);
setText("");
}
else {
setGraphic(null); // Remove checkbox if row is empty
setText("");
}
}
}
}
Using CheckBoxTableCell
JavaFX API has this convenient class CheckBoxTableCell that would do all these for you. Most people find this class hard to use because there are 2 things that you need to ensure to use it correctly:
The TableView that the column belongs to must be editable.
The TableColumn itself must be editable.
Example:
tableView.setEditable(true);
tableColumnSelected.setCellFactory(CheckBoxTableCell.forTableColumn(tableColumnSelected));
tableColumnSelected.setEditable(true);
As for whether which entry you want to be removed with the delete button, you just need to remove the correct items from the TableView.
How can I wrap the text in JFXTreeTableView cells?
My JFoenix TableTreeView column cell factory is created as shown below.
// Set column cell factories and width preference
for (JFXTreeTableColumn<LogEntry, String> column : columnList) {
column.setCellFactory(param ->
new GenericEditableTreeTableCell<>(new TextFieldEditorBuilder()));
column.setPrefWidth(100);
}
After hours of searching, I can't figure out how to get the cells in the tree table to wrap text. I even tried to set the wrap text value for every GenericEditableTreeTableCell to true, but I think I'm also supposed to call the setWrappingWidth() method on something. I tried the following block of code, but I ended up getting a NullPointerException.
// Set column cell factories and width preference
for (JFXTreeTableColumn<LogEntry, String> column : columnList) {
column.setCellFactory(param -> {
GenericEditableTreeTableCell<LogEntry, String> cell =
new GenericEditableTreeTableCell<>(new TextFieldEditorBuilder());
Text text = (Text) cell.getGraphic();
text.setWrappingWidth(1); //null pointer exception
cell.setWrapText(true);
return cell;
});
column.setPrefWidth(100);
}
So, I'm left with the following block of code which runs perfectly fine and displays the table, but the cells do not wrap text.
// Set column cell factories and width preference
for (JFXTreeTableColumn<LogEntry, String> column : columnList) {
column.setCellFactory(param -> {
GenericEditableTreeTableCell<LogEntry, String> cell =
new GenericEditableTreeTableCell<>(new TextFieldEditorBuilder());
// I think I should call setWrappingWidth() on some object here
// but I don't know what object
cell.setWrapText(true);
return cell;
});
column.setPrefWidth(100);
}
The documentation for setting up a JFXTreeTableView can be found here. It doesn't seem to mention anything about wrapping cell text.
Edit: I tried doing it with CSS, but didn't get any results. In fact, the cell.isWrapText() returned false after using this CSS code - meaning that it didn't event set the value to true. I know the block of CSS is working correctly because I can change every element's text fill color with it.
* {
-fx-wrap-text: true;
}
Edit 2: Some people said on other semi-related posts that a scroll pane can cause a Node to think it has a much larger width than what is shown to the user. Since a JavaFX TreeTableView uses a scroll bar when the table is too large, I figured I'd try their solutions. I tried setting the preferred width of the cell - still no results.
cell.setWrapText(true);
cell.setPrefWidth(100);
//cell.setMaxWidth(100); doing this too made no difference
//cell.setMinWidth(100); doing this too made no difference
Edit 3: I think I know the problem! It seems that the row height refuses to let the cell wrap text. If I set the rows minimum height to a large enough value, the cell wraps its text! Now I just need to know how to make the row height adjust dynamically to accommodate the cell when it wants to wrap text.
Edit 4: It appears that the row doesn't allow line breaks which may be the cause of the cell failing to wrap text. It can't wrap the text because the new lines it creates are chomped.
I have used one of your approaches, but also made custom EditorBuilder which has JFXTextArea instead of JFXTextField.
The custom TextAreaEditorBuilder is the following:
public class TextAreaEditorBuilder implements EditorNodeBuilder<String> {
private JFXTextArea textArea;
#Override
public void startEdit() {
Platform.runLater(() -> {
textArea.selectAll();
});
}
#Override
public void cancelEdit() {
}
#Override
public void updateItem(String s, boolean isEmpty) {
Platform.runLater(() -> {
textArea.selectAll();
textArea.requestFocus();
});
}
#Override
public Region createNode(
String value,
DoubleBinding minWidthBinding,
EventHandler<KeyEvent> keyEventsHandler,
ChangeListener<Boolean> focusChangeListener) {
StackPane pane = new StackPane();
pane.setStyle("-fx-padding:-10 0 -10 0");
textArea = new JFXTextArea(value);
textArea.setPrefRowCount(4);
textArea.setWrapText(true);
textArea.minWidthProperty().bind(minWidthBinding.subtract(10));
textArea.setOnKeyPressed(keyEventsHandler);
textArea.focusedProperty().addListener(focusChangeListener);
pane.getChildren().add(textArea);
return ControlUtil.styleNodeWithPadding(pane);
}
#Override
public void setValue(String s) {
textArea.setText(s);
}
#Override
public String getValue() {
return textArea.getText();
}
#Override
public void validateValue() throws Exception {
}
}
and then the configuration for your column goes something like this:
negativeCasingColumn.setCellFactory(param -> {
TextAreaEditorBuilder textAreaEditorBuilder = new TextAreaEditorBuilder();
GenericEditableTreeTableCell<DiagnosticMethodFX, String> cell
= new GenericEditableTreeTableCell<>(textAreaEditorBuilder);
cell.setWrapText(true);
return cell;
});
So basically I'm wrapping the cell, but making sure I use TextArea as editing field. For me this works just fine, but if you want more elegant solution maybe you can check the cancelEdit() method in GenericEditableTreeTableCell, where it sets the content display to text only: setContentDisplay(ContentDisplay.TEXT_ONLY) which is setting of content property in the abstract class Labeled, where the text wrap is set to false. I didn't dig too deep into it, but some workaround can be made for sure.
Background
I have a JTable called table, and I have a column that is not part of the DefaultTableModel so its invisible:
final JTable table = new JTable(new DefaultTableModel(new Object[]{"Title", "Artist",
"Album", "Time"}, 0)
I add the respective rows like this:
int upTo = songList.size();
int idx = 0;
while (idx < upTo) {
SongObject curSong = songList.get(idx);
model.addRow(new Object[]{
curSong.toString(),
curSong.getArtist(),
"-",
curSong.getDuration(),
curSong});
idx++;
}
Where curSong is the the current song object that it is adding, the SongObject contains all data about the song. The toString() returns the title of the song.
Problem:
The problem is that when I try to access the column like this:
SongObject songToPlay = (SongObject) table.getModel().getValueAt(table.getSelectedRow(), 4);
It throws a java.lang.ArrayIndexOutOfBoundsException: 4 >= 4 exception.
Can anyone explain why and propose a solution?
Thanks in advance :)
DefaultTableModel.addRow() somewhere down the chain executes private justifyRows() method, which trims the unused columns from the row to the size equal to getColumnCount(). So the fifth column is never added to the model. As a result, you get ArrayIndexOutOfBoundsException when you're attempting to access this column.
If you need access to the actual SongObject then you can have a custom model that would return SongObject for a given row index. Make an extension of AbstractTableModel. See How to Use Tables tutorial for examples.
As an alternative, you can still use SongObject in a visible column. Just use a custom renderder that would renderer SongObject as a string for example. See Using Custom Renderers for details. You can reuse DefaultTableModel in this case.
Thanks to Aqua I overrode the following:
final JTable table = new JTable(new DefaultTableModel(new Object[]{"Title", "Artist", "Album", "Time"}, 0) {
#Override
public void addRow(Object[] rowData) {
Vector blah = DefaultTableModel.convertToVector(rowData);
insertRow(super.getRowCount(), blah);
}
#Override
public void insertRow(int row, Vector data) {
super.dataVector.insertElementAt(data, row);
super.fireTableRowsInserted(row, row);
}
});
Then I accessed the item in the fifth column (which is not part of the model!) like this:
SongObject songToPlay = (SongObject) table.getModel().getValueAt(table.convertRowIndexToModel(
table.getSelectedRow()), 4); //get the value at the VIEW location NOT THE MODEL collection
Sorry for the messy code but it worked. Home I could help someone with a similar problem. The solution just misses the justifyRows() method found in DefaultTableModel
I have a Cell Table that I am using to output some search results. The cell table uses a list data provider to update info. I want to separate different sections so I am attempting to add a custom row in between different sections that has one cell that spans all of the columns. I am extending AbstractCellTableBuilder to do this, but my issue comes when I use TableRowBuilder and startRow(), calling startRow() returns a null pointer exception, to AbstractCellTableBuilder.java:243, which refers to tbody. So this is leading me to believe that my cell table is not getting passed into AbstractCellTableBuilder properly. My understanding of gwt and java is pretty basic, so I might just not be understanding how exactly this is supposed to work, and the showcase example is pretty complicated for me to understand. If anyone can tell where I'm messing up or has any simpler examples of this that might help me I would appreciate it!
I had found a similar answer and tried to implement it, and that is how I came up with what I have, but it answer wasn't quite detailed enough for me to fully understand how it works. Here is what I referenced:
Building a custom row on demand with GWT CellTableBuilder
EDITED:
Basic format of how I add normal rows to the cell table
searchProvider = new ListDataProvider<SearchColumn>();
cellTable_2 = new CellTable<SearchColumn>();
//Add columns to the cellTable
searchProvider.addDataDisplay(cellTable_2);
//What I call when adding a row to the cellTable using the ListDataProvider
searchProvider.getList().add(new SearchColumn("",label,"","","","","","",""));
Adding the CustomCellTableBuilder to the cell table:
//Passing the CustomCellTableBuilder to the cell table
CustomCellTableBuilder buildRow = new CustomCellTableBuilder();
cellTable_2.setTableBuilder(buildRow);
The CustomCellTableBuilder for adding custom rows:
public class CustomCellTableBuilder extends AbstractCellTableBuilder<SearchColumn>{
public CustomCellTableBuilder() {
super(cellTable_2);
}
#Override
protected void buildRowImpl(SearchColumn rowValue, int absRowIndex){
//building main rows logic
if (labelrow == 1){
System.out.println("Going to build extra row if");
buildExtraRow(absRowIndex, rowValue);
}
else {
System.out.println("Getting into normal buildRow");
buildRow(rowValue,absRowIndex);
}
}
private void buildExtraRow(int absRowIndex, SearchColumn rowValue){
start(true);
TableRowBuilder row = startRow();
TableCellBuilder td = row.startTD().colSpan(getColumns().size());
td.text("Testing this out").endTD();
row.endTR();
}}
I think you should call start(true) before calling startRow() because tbody is initialized to null. Start() call will initialize tbody to HtmlBuilderFactory.get().createTBodyBuilder().
The source doesn't lie.
Just like that:
private void buildExtraRow(int absRowIndex, SearchColumn rowValue) {
start(true); // true makes builder to rebuild all rows
TableRowBuilder row = startRow();
// whatever
}
I'm using JXTable and I know how to do this based on DefaultRenderers for JTable, but I want to know how to do it in a way that's JXTable-friendly based on HighlighterPipeline.
I have a list of objects displayed in a table, and each row represents one object. I would like to color the rows displaying objects of a certain type a different color.
It looks like I should be using ColorHighlighter. But I can't find examples for this, other than the simple highlighters like "color every other row" or some such thing.
I need the row number since there's no such thing as a "row object" in the JTable/TableModel paradigm, but if I can do that, I can easily test a predicate and return true/false to tell the highlighter to kick in or not.
Can someone help me figure out the right direction to get this to work?
never mind, I figured it out. It was just hard to figure out the way to use ComponentAdapter propertly.
JXTable table = ...
final List<Item> itemList = ...
final HighlightPredicate myPredicate = new HighlightPredicate() {
#Override
public boolean isHighlighted(
Component renderer,
ComponentAdapter adapter) {
Item item = itemList.get(adapter.row);
return testItem(item);
}
public boolean testItem(Item item) { ... }
}
ColorHighlighter highlighter = new ColorHighlighter(
myPredicate,
Color.RED, // background color
null); // no change in foreground color
table.addHighlighter(highlighter);