How to insert a column at a specific position in JTable - java

I have a JTable with a predefined model
how to ask the model to insert a specific column in a specific position ?
so i want something like : DefaultTableModel.insertRow(int,Object[]) for columns

There is no insertColumn method like DefaultTableModel.insertRow() for inserting rows. In order to insert a column at a particular position, you must append the column using DefaultTable.addColumn() and then move the new column into the desired position.
JTable table = new JTable(rows, cols);
table.setAutoCreateColumnsFromModel(false);
DefaultTableModel model = (DefaultTableModel)table.getModel();
TableColumn col = new TableColumn(model.getColumnCount());
col.setHeaderValue(headerLabel);
table.addColumn(col);
model.addColumn(headerLabel.toString(), values);
table.moveColumn(table.getColumnCount()-1, vColIndex);

Is it really necessary to add the column in your TableModel at a specific index ? You can more easily adjust the column order in the view (the JTable) as documented in the class javadoc of JTable
By default, columns may be rearranged in the JTable so that the view's columns appear in a different order to the columns in the model. This does not affect the implementation of the model at all: when the columns are reordered, the JTable maintains the new order of the columns internally and converts its column indices before querying the model.
This is achieved by using the JTable#moveColumn method.
Adding a column to your DefaultTableModel is done calling the DefaultTableModel#addColumn method

With DefaultTableModel:
At the end one has to call fireDataChanged. There is only an addColumn with several overloads. This is no hindrance as the order of display is independent. One may move a column to another position, and has to take care of view index != column index. To get the correct view index immediately after adding the column, one has to access the JTable and call moveColumn.
I found it at times easier to create a new TableModel and assign that. Or not use the DefaultTableModel.

this link may help
http://www.roseindia.net/java/example/java/swing/InsertColumn.shtml
public void positionColumn(JTable table,int col_Index) {
table.moveColumn(table.getColumnCount()-1, col_Index);
}

Related

How to add checkboxes to a JTable which uses a model with values from a database?

I have a model(AbstracTableModel) which I use to build a JTable.
The thing is that the table cell values seen in the GUI are displayed from a database.
How can I add a new column with checboxes for each row of the table?
Is there a concrete answer to this?
The thing is that the table cell values seen in the GUI are displayed from a database.
Use a DefaultTableModel to store the data from the database.
See the TableFromDatabaseExample.java code found in Table From Database for simple code to load the DefaultTableModel.
How can I add a new column with checboxes for each row of the table?
You can modify the above code to add an extra column to the "columnNames" Vector. Then in the looping code you add a Boolean.FALSE object to the "row" Vector.
Or, after creating the DefaultTableModel with the data from the database you can use the addColumn(...) method of the DefualtTableModel to create your column of check boxes.

How to hide the Jtable column data?

I want to hide data of a column of Jtable, but not hide the column view,just its data.
The column contain data about profit and the customer doesn't want to show the profit but in my code I use the values of this column and get it when the user select specified row.
How do I achieve the customer need and still be able to get the values of this column when selecting it after hiding its data(displaying column as empty but still has its values)?
You need to remove the TableColumn from the TableColumnModel of the JTable. For example:
table.removeColumn( table.getColumn(...) );
Now the column will not display in the table, but the data is still available in the TableModel. to access the data you use:
table.getModel().getValueAt(...);
You could try a subclassing DefaultTableCellRenderer, and call setCellRenderer. When the relevant column number is passed to getTableCellRendererComponent, return a blank JLabel, otherwise call the default super.getTableCellRendererComponent.
This should mean the column is still visible, but each cell will be blank.
If you want to display the data when a row is selected, you will need add a listener to the selection model (from getSelectionModel) to store the selected row in a variable, and call a repaint. You can then use this value in your CellRenderer.
Why don't you just let the dataModel control what is shown? I'm assuming you are using a tableModel.
All you have to do is change the getValueAt(..) method so that it does not return a value for the column you do not want to show. Make sure that getColumnCount() method is reduced by one as well.

Column index not changing after dragging columns in Jtable

I am using JTable for displaying the information. After rendering the information if I drag the columns to reorder them, the information is displayed in the same fashion in the session. But when I try to capture the changes by checking the column names by iterating the column names, the sequence is same as the older one. Why is the latest view not available from the API?
As commented by Hovercraft Full Of Eels, the column indices in the view change independently of the column indices in the model. JTable's JavaDoc has this to say about it:
By default, columns may be rearranged in the JTable so that the view's columns appear in a different order to the columns in the model. This does not affect the implementation of the model at all: when the columns are reordered, the JTable maintains the new order of the columns internally and converts its column indices before querying the model.
JTable offers the methods convertColumnIndexToModel() and convertColumnIndexToView() that you can use to translate column numbers from one to the other. You can use these to figure out if (and how) the columns were rearranged.
To be notified of column changes as they happen, use a TableColumnModelListener:
myTable.getColumnModel().addColumnModelListener( new TableColumnModelListener() {
//etc.
} );

JTable removeRow(), removing wrong row

I have a JTable and I need to remove a row, namely, the selected row.
So first, I get the the table model :
DefaultTableModel model = (DefaultTableModel) table.getModel();
Then the selected row (if the second row is selected, this returns 1, which is understandable because rows start from zero):
int selectedRow = table.getSelectedRow();
Then I try to remove the row:
model.removeRow(selectedRow);
Then I set the table model again:
table.setModel(model);
What this achieves is removing a completely random row. I simply can't understand why. I have sorted the table at some point, using table.setRowSorter(sorter), but I don't know why that should be a problem. If an SSCCE is absolutely needed please let me know, because I have a lot of code to modify before I can produce one.
NOTE: The values returned by these two lines differ:
System.out.println(table.getValueAt(selectedRow, 1));
System.out.println(model.getValueAt(selectedRow, 1));
If is JTable filtered or sorted then you can convert
int modelRow = convertRowIndexToModel(row);
The index returned by JTable.getSelectedRow is a view index : it's the index of the row as seen by the end-user in the table. It's not the same as the model index, because if you sort the table, the indices in the model don't change, but the indices in the view do change. So, you must always use JTable.convertRowIndexToModel to get the model index from the view index.
Note that the same must be done for columns, because the user might choose to reorder columns to its taste.
Also, you shouldn't have to set the model again each time you remove a row. Instead, your model should fire a TableModelEvent to inform the view about the removal. See AbstractTableModel.fireTableRowsDeleted.

getting selected row through AbstractTableModel

Is it possible to get the selected row index from my table model?
My object already knows about the table model. Instead of passing a reference to the table it self can i get the selected index using the model?
Like MrWiggles said you can get it from the ListSelectionModel which you is accessible from the table itself. However there are convenience methods in JTable to get the selected rows as well. If your table is sortable etc you will also need to go through the convertRowIndexToModel method :)
From the JTable JavaDoc:
int[] selection = table.getSelectedRows();
for (int i = 0; i < selection.length; i++) {
selection[i] = table.convertRowIndexToModel(selection[i]);
}
// selection is now in terms of the underlying TableModel
The TableModel only concerns itself with the data, the ListSelectionModel concerns itself with what is currently selected, so, no you can't get the selected row from the TableModel.
If you let your model class implement ListSelectionModel as well as TableModel, you will be able to get selection from one model... but you cannot extend two abstract model classes :-( (It also isn't very good idea anyway as your class will have too many responsibilities).
You can get the index from the bound Table and then you can use it to manipulate the table model. For example, if I want to delete a Row in my table model:
myTableModel.removeValueAt(myTable.getSelectedRow());

Categories