I have 5 JTables on different forms with arbitrary numbers of rows and I would like to have a label for each one that will show me the total number of rows in that table and also change color for 3 seconds when the row count changes. The color should go green if incrementing and red if decrementing. What would be the best way to implement this such that I do not need to duplicate too much code in each of my forms?
basically, you add a TableModelListener to the JTable's model and on receiving change events, update the corresponding labels as appropriate
some code:
public class TableModelRowStorage
// extends AbstractBean // this is a bean convenience lass of several binding frameworks
// but simple to implement directly
implements TableModelListener {
private int rowCount;
public TableModelRowStorage(TableModel model) {
model.addTableModelListener(this);
this.rowCount = model.getRowCount();
}
#Override
public void tableChanged(TableModelEvent e) {
if (((TableModel) e.getSource()).getRowCount() != rowCount) {
int old = rowCount;
rowCount = ((TableModel) e.getSource()).getRowCount();
doStuff(old, rowCount);
}
}
protected void doStuff(int oldRowCount, int newRowCount) {
// here goes what you want to do - all in pseudo-code
// either directly configuring a label/start timer
label.setText("RowCount: " + newRowCount);
label.setForeground(newRowCount - oldRowCount > 0 ? Color.GREEN : Color.RED);
timer.start();
// or indirectly by firing a propertyChange
firePropertyChange("rowCount", oldRowCount, newRowCount);
}
}
Related
I have a column 'Lifecycle' in my NAT Table based on which i have to set respective color to each row.
Adding color to row works fine. The problem is when i use the scroll bar to scroll either left or right, the color disappears. I am not aware what i am missing. Kindly help me if you have any idea of how it can be resolved
My code looks like:
IConfigLabelAccumulator cellLabelAccumulator = new IConfigLabelAccumulator() {
#Override
public void accumulateConfigLabels(final LabelStack configLabels, final int columnPosition,
final int rowPosition) {
Object dataValueByPosition = PhysicalDimensionNatTable.this.bodyLayer.getDataValueByPosition(10, rowPosition);
if ((dataValueByPosition != null) && dataValueByPosition.equals("Valid")) {
configLabels.addLabel("VALID");
}
if ((dataValueByPosition != null) && dataValueByPosition.equals("Invalid")) {
configLabels.addLabel("INVALID");
}
if ((dataValueByPosition != null) && dataValueByPosition.equals("Obsolete")) {
configLabels.addLabel("OBSOLETE");
}
}
};
this.bodyLayer.setConfigLabelAccumulator(cellLabelAccumulator);
this.natTable.addConfiguration(new AbstractRegistryConfiguration() {
#Override
public void configureRegistry(final IConfigRegistry configRegistry) {
Style cellStyle = new Style();
cellStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR, GUIHelper.COLOR_GREEN);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle, DisplayMode.NORMAL, "VALID");
cellStyle = new Style();
cellStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR, GUIHelper.COLOR_RED);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle, DisplayMode.NORMAL,
"INVALID");
cellStyle = new Style();
cellStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR, GUIHelper.COLOR_YELLOW);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle, DisplayMode.NORMAL,
"OBSOLETE");
}
});
The issue that you are facing is that the IConfigLabelAccumulator is registered on the bodyLayer, and I assume that is a stack where the top most layer is the ViewportLayer. bodyLayer.getDataValueByPosition(10, rowPosition); is returning the data value of the column position 10. And the underlying cell changes on scrolling as for example the column with index 11 becomes the column at position 10 if the first column moves out of the visible range. That is the index-position-transformation which is a basic concept in NatTable.
Either you need to perform a transformation calculation e.g. via LayerUtil to get the index, or operate on the DataLayer of the body directly instead of the bodylayer stack. Then you don't need to consider the index-position-transformation. I typically suggest to use the later.
As the index-position-transformation handling is too abstract for several people, another option is to operate on the object on the DataLayer. For this the IConfigLabelAccumulator needs to know the IRowDataProvider to be able to access the row object. And then register it on the DataLayer.
An example would look like the following snippet. Of course it should be transferred to your solution with better class separation.
IRowDataProvider<PersonWithAddress> bodyDataProvider = new ListDataProvider<>(data, accessor);
DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
bodyDataLayer.setConfigLabelAccumulator(new IConfigLabelAccumulator() {
#Override
public void accumulateConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) {
PersonWithAddress person = bodyDataProvider.getRowObject(rowPosition);
if ("Simpson".equals(person.getLastName())) {
configLabels.addLabel("YELLOW");
}
}
});
I have a JTable. When a user clicks on a cell another JTable is created that shows the data for the whole row of that cell, in a column format (ie the row is converted to a column).
This happens when the user clicks but its a bit irritating to happen every time so I want to make it only on a double click.
The problem is that the getSelection method of the table only takes a addListSelectionListener method and not a MouseListener. How can I do what I want?
Here is the code:
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
int selectedRow = table.getSelectedRow();
DefaultTableModel newModel = new DefaultTableModel();
String rowName = "Row: " + selectedRow;
newModel.setColumnIdentifiers(new Object[]{rowName});
for (int i = 0; i < table.getModel().getColumnCount(); i++) {
newModel.addRow(new Object[]{table.getModel().getValueAt(selectedRow, i)});
}
JTable newTable = new JTable(newModel) {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(140, 240);
}
};
// Apply any custom renderers and editors
JOptionPane.showMessageDialog(frame, new JScrollPane(newTable),
rowName, JOptionPane.PLAIN_MESSAGE);
}
}
});
This happens when the user clicks but its a bit irritating to happen every time so I want to make it only on a double click
You use a MouseListener, not a ListSelectionListener. You would check the Mouse event for a click count of 2.
Read the section from the Swing tutorial on How to Write a MouseLister for more information and working examples.
Also, a double click will start the editor by default so you want to make sure the cell is not editable. So you may need to override the isCellEditable(...) method of the table.
I created a class that can dynamically to lock and unlock columns .
In my program i create two tables with the same tablemodel.
One is in the Jviewport of the scrollpane, the other in the RowHeaderView.
The problem is when you unlock all the locked columns
and you want to start to lock again, doesn't work. There are no errors but it's like the event doesn't answer.
Steps to produce the problem:
Try the code,
put all the columns in the fixed table,
then unlock with right double click,
then start again to lock, and unlock
Do this procedure and you can see that the mouse event doesnt answer anymore
public class Prova extends JFrame{
private JTable mainTable,fixedTable;
private JScrollPane scrollPane;
private JTableHeader mainTableHeader;
private TableColumnModel originalColumnModel,mainColumnModel,fixedColumnModel;
private TableColumn[] columns;
private int ncols,counter;
public Prova(){
counter = 0;
TableModel mainTableModel = new DefaultTableModel(5, 10);
scrollPane = new JScrollPane();
mainTable = new JTable(mainTableModel);
mainColumnModel = mainTable.getColumnModel();
fixedTable = new JTable();
fixedTable.setAutoCreateColumnsFromModel(false);
fixedTable.setModel(mainTable.getModel() );
ncols = mainTableModel.getColumnCount();
columns = new TableColumn[ncols];
for (int i=0;i<ncols;i++){
columns[i] = mainColumnModel.getColumn(i);
}
mainColumnModel = mainTable.getColumnModel();
fixedColumnModel = fixedTable.getColumnModel();
mainTableHeader = mainTable.getTableHeader();
mainTableHeader.addMouseListener( new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent me){
if (SwingUtilities.isRightMouseButton(me)){
if (ncols - counter>1){
counter ++;
int col = mainTable.columnAtPoint(me.getPoint());
TableColumn column = mainColumnModel.getColumn(col);
mainColumnModel.removeColumn(column);
fixedTable.getColumnModel().addColumn(column);
scrollPane.setRowHeaderView(fixedTable);
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTable.getTableHeader());
}
}
}
});
fixedTable.getTableHeader().addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent me){
if (SwingUtilities.isRightMouseButton(me) && me.getClickCount()== 2 ){
while (mainColumnModel.getColumnCount() > 0){
mainColumnModel.removeColumn(mainColumnModel.getColumn(0));
}
while (fixedColumnModel.getColumnCount() > 0){
fixedColumnModel.removeColumn(fixedColumnModel.getColumn(0));
}
for(int i=0;i<ncols;i++){
mainColumnModel.addColumn(columns[i]);
}
scrollPane.setRowHeaderView(null);
}
}
});
scrollPane.setViewportView(mainTable);
add(scrollPane, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Prova().setVisible(true);
}
});
}
}
A few pointers when posting a SSCCE:
for (int i=0;i<ncols;i++){
Don't be afraid to use whitespace in you code to make it more readable be separating the 3 statements of the for statement.
for (int i = 0; i < ncols; i++){
Keep the code simple and directly related to the problem:
TableModel mainTableModel = new EmployeeTableModel(listEmployees);
You question is about "moving columns", not about the data in the table so there is no need for a special TableModel and the Employee class. Just use the DefaultTableModel:
TableModel mainTableModel = new DefaultTableModel(5, 10);
Your current code won't compile because you didn't include the Employee class. By using JDK classes the code is smaller and easier to read.
The problem is when you unlock all the locked columns and you want to start to lock again, doesnt work
Your looping code is wrong. I didn't bother to figure out what was wrong. Instead I made the code simpler:
//for(int i=0;i<(ncols-counter);i++){
while (mainColumnModel.getColumnCount() > 0)
{
mainColumnModel.removeColumn(mainColumnModel.getColumn(0));
}
//for(int i=0;i<counter;i++){
while (fixedColumnModel.getColumnCount() > 0)
{
fixedColumnModel.removeColumn(fixedColumnModel.getColumn(0));
}
Another problem is your fixed table doesn't have a header so you don't know what the columns are. This is fixed by using:
scrollPane.setRowHeaderView(fixedTable);
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTable.getTableHeader());
Now that you have a header you need to add the MouseListener to the header, not the scrollpane:
//scrollPane.addMouseListener(new MouseAdapter() {
fixedTable.getTableHeader().addMouseListener(new MouseAdapter() {
Edit:
You have a similar problem to what I fixed above. That is don't keep using variable to track values when you can use the component itself.
if (ncols - counter>1){
You never reset the value of the counter so the if condition won't be true the second time.
As I did above just use the value from the column model:
//if (ncols - counter>1){
if (mainColumnModel.getColumnCount() > 1) {
This is just basic problem solving. Put a display statement in the block of code to see if it executes when you have problems.
I have two tables, and i want to select appropriate row in first table when i select row in second table. I've done this as following
for (DataRow<Cell> row : formDataTable.getVisibleItems()) {
if (row.getIndex().equals(rowIndex.intValue())) {
formDataTable.getSelectionModel().setSelected(row, true);
}
}
But i don't see it as visual selected row. I see selected row from second table, but i should see it on first.
It done through a setSelected.
Make sure that you use a right selectionModel for yours dataGrid.
Use setSelected method of dataGrid
If you want to have opportunity selecting row on other pages you should use ProvidesKey and manualy set necessary page
My code below
// variables
#UiField
DataGrid<DataRow<Cell>> formDataTable;
public static final ProvidesKey<DataRow<Cell>> KEY_PROVIDER = new ProvidesKey<DataRow<Cell>>() {
#Override
public Object getKey(DataRow<Cell> item) {
return item.getIndex();
}
};
private SingleSelectionModel<DataRow<Cell>> selectionModel;
// this code must be within constructor
selectionModel = new SingleSelectionModel<DataRow<Cell>>(KEY_PROVIDER);
formDataTable.setSelectionModel(selectionModel);
// method to select should view as
#Override
public void setFocus(final Long rowIndex) {
DataRow<Cell> row = new DataRow<Cell>();
row.setIndex(rowIndex.intValue());
selectionModel.setSelected(row, true);
// go to essential page
Long page = rowIndex / pager.getPageSize() + (rowIndex % pager.getPageSize() > 0 ? 1:0);
pager.setPage(page.intValue() - 1);
}
I have a JTable and a button next to it that calls deleteSelectedRows(), which does exactly what it sounds like:
public void deleteSelectedRows() {
int[] selected = jTable.getSelectedRows();
for(int i = selected.length - 1; i >= 0; i--) {
model.removeRow(selected[i]);
}
if(model.getRowCount() < 1) {
addEmptyRow();
}
}
But if a cell was in the act of being edited when it (and/or cells above it) were deleted, the edited cell stayed while the rest left, like this:
And then trying to exit out of the editing threw an ArrayIndexOutOfBoundsException since row 5 was trying to be accessed and there was only one row left in the table.
I then tried all sorts of fun and games with jTable.getEditingRow(). At first, adding an if(selected[i] != editing) before the removal seemed to work, but then removing rows above the edited cell caused problems.
Then I tried this:
public void deleteSelectedRows() {
int[] selected = jTable.getSelectedRows();
int editing = jTable.getEditingRow();
for(int s : selected) { //PS: Is there a better way of doing a linear search?
if(s == editing) {
return;
}
}
for(int i = selected.length - 1; i >= 0; i--) {
model.removeRow(selected[i]);
}
if(model.getRowCount() < 1) {
addEmptyRow();
}
}
But that doesn't delete anything, ever. Judging from printlns I sprinkled around, the last cell to be highlighted (that has the special border seen here on spam) is considered part of the editing row, and thus triggers my early return.
So I don't really care whether the solution involves fixing the original problem--that of the wacky results when a cell being edited is deleted--or this new problem--that of getEditingRow() not behaving as I expected, it's just that I need at least one of those to happen. That said, I would be interested to hear both solutions just out of academic curiosity. Thanks in advance.
Try to include the following lines before removing any rows from your model:
if (table.isEditing()) {
table.getCellEditor().stopCellEditing();
}
As Howard stated, it is necessary to stop the cell editing before modifying the model. But it is also necessary to check if the cell is actually being modified to avoid null pointer exceptions.
This is because the getCellEditor() method will return null if the table isn't being edited at the moment:
if (myTable.isEditing()) // Only if it's is being edited
myTable.getCellEditor().stopCellEditing();
...
there are cases where the cell editor may refuse to stop editing,
that can happen i.e. if you are using some complex editor that is waiting for user input on a dialog. In that case you should add an extra check:
if (myTable.isEditing())
if (!myTable.getCellEditor().stopCellEditing()) {
// If your update is user-generated:
JOptionPane.showMessageDialog(null, "Please complete cell edition first.");
// Either way return without doing the update.
return;
}
In your code, you are trying to delete only the rows that are not being edited, but that would also throw an ArrayOutOfBounds Exception when the cell editor stops editing. The best is to stop it before the refresh.
Finally, there seems to be also a property you can set in your table:
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
as explained here.
Whilst stopping any and all cells from editing before applying any changes works, it's a bit like using a sledge hammer to crack a nut. What happens, for example, if the cell that is editing is not the one being deleted? This is the next problem you'll encounter. For that reason and others there is a better way.
Firstly, use the framework to do the heavy lifting for you. Attach a TableModelListener to your table model table.getModel().addTableModelListener()... then in your listeners implementation catch the delete event and process as follows:
/**
* Implements {#link TableModelListener}. This fine grain notification tells listeners
* the exact range of cells, rows, or columns that changed.
*
* #param e the event, containing the location of the changed model.
*/
#Override
public void tableChanged(TableModelEvent e) {
if (TableModelEvent.DELETE == e.getType()) {
// If the cell or cells beng edited are within the range of the cells that have
// been been changed, as declared in the table event, then editing must either
// be cancelled or stopped.
if (table.isEditing()) {
TableCellEditor editor = table.getDefaultEditor(ViewHolder.class);
if (editor != null) {
// the coordinate of the cell being edited.
int editingColumn = table.getEditingColumn();
int editingRow = table.getEditingRow();
// the inclusive coordinates of the cells that have changed.
int changedColumn = e.getColumn();
int firstRowChanged = e.getFirstRow();
int lastRowChanged = e.getLastRow();
// true, if the cell being edited is in the range of cells changed
boolean editingCellInRangeOfChangedCells =
(TableModelEvent.ALL_COLUMNS == changedColumn ||
changedColumn == editingColumn) &&
editingRow >= firstRowChanged &&
editingRow <= lastRowChanged;
if (editingCellInRangeOfChangedCells) {
editor.cancelCellEditing();
}
}
}
}
}
In the example above I've assigned my own editor as the default editor for the table table.setDefaultRenderer(ViewHolder.class, new Renderer()); table.setDefaultEditor(ViewHolder.class, new Editor());.
Additionally instead of using a specific view I use a ViewHolder. The reason for this is to make the table generic in terms of the views it displays. Here is the generic ViewHolder.class:
/**
* Holds the view in a table cell. It is used by both the {#link Renderer}
* and {#link Editor} as a generic wrapper for the view.
*/
public static abstract class ViewHolder {
private static final String TAG = "ViewHolder" + ": ";
// the position (index) of the model data in the model list
protected final int position;
// the model
protected Object model;
// the view to be rendered
protected final Component view;
// the views controller
protected final Object controller;
/**
* #param view the view to be rendered
* #param position the position (index) of the data
*/
public ViewHolder(int position,
Object model,
Component view,
Object controller) {
this.position = position;
if (view == null) {
throw new IllegalArgumentException("item view may not be null");
}
if (model == null) {
throw new IllegalArgumentException("model may not be null");
}
this.controller = controller;
this.model = model;
this.view = view;
}
Now, each time your renderer or editor is called, construct a ViewHolder class and pass in your view / controller / position etc, and you're done.
The important thing to note here is that you do not have to catch the delete or change event before it happens. You should, in fact, catch it after the model changes. Why? Well after a change you know what has changed, because the TableModelListener tells you, helping you determine as to what to do next.