How to make a columns in JTable Invisible for Swing Java
Asked Answered
L

8

51

I have designed one GUI in which I have used one JTable from which I have to make 2 columns invisible . How should I do that ?

Lasting answered 29/9, 2009 at 12:23 Comment(0)
S
75

Remove the TableColumn from the TableColumnModel.

TableColumnModel tcm = table.getColumnModel();
tcm.removeColumn( tcm.getColumn(...) );

If you need access to the data then you use table.getModel().getValueAt(...).

For a more complex solution that allows the user to hide/show columns as they wish check out the Table Column Manager.

Shiism answered 29/9, 2009 at 15:16 Comment(6)
this is the real right way to do this - setting the width to 0 is kind of bogus. This way you still have the data in your model; you're just hiding part of the view.Coleencolella
Even with the above approach the data is still in the model which is why you can access it as demonstrated above. This is how MVC works. All we are doing is changing the view. When you set the width to 0, try tabbing, when you hit the hidden column focus disappears until you tab again. This will confuse users.Shiism
This works except one thing which makes this approach useless. When you want to know which is your selected column you will get the wrong (shifted) index of the column. In other words, doing table.getColumnModel().getSelectedColumns() will give you a wrong column.Acey
Actually I was wrong... Doing column.getModelIndex() give the correct position in the model. Just don't use table.getSelectedColumn() - this will give wrong index.Acey
@Acey you need to understand the difference between the view and the model. Table methods always refer to the view. The JTable API has a bunch of convertXXX methods you can use. So you could have used the convertColumnIndexToModel(...)Shiism
@xmedeko a really complete solution is to use SwingX :-)Spragens
C
40

First remove the column from the view

 table.removeColumn(table.getColumnModel().getColumn(4));

Then retrieve the data from the model.

table.getModel().getValueAt(table.getSelectedRow(),4);

One thing to note is that when retrieving the data, it must be retrieve from model not from the table.

Caiman answered 21/3, 2013 at 5:38 Comment(1)
How to remove from model?Neolithic
D
22

I tried 2 possible solutions that both work, but got some issue with the 1st solution.

   table.removeColumn(table.getColumnModel().getColumn(4));

or

   table.getColumnModel().getColumn(4).setMinWidth(0);
   table.getColumnModel().getColumn(4).setMaxWidth(0);
   table.getColumnModel().getColumn(4).setWidth(0);

In my recent case, I preferred the 2nd solution because I added a TableRowSorter.

   TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
   table.setRowSorter(sorter);

When using table.removeColumn(table.getColumnModel().getColumn(4)), it will physically remove the column from the view/table so you cannot use table.getValueAt(row, 4) - it returns ArrayIndexOutOfBounds. The only way to get the value of the removed column is by calling table.getModel().getValueAt(table.getSelectedRow(),4). Since TableRowSorter sorts only what's on the table but not the data in the DefaultTableModel object, the problem is when you get the value after sorting the records - it will retrieve the data from DefaultModelObject, which is not sorted.

So I used the 2nd solution then used table.getValueAt(table.getSelectedRow(),4);

The only issue I see with the 2nd approach was mentioned by @camickr: "When you set the width to 0, try tabbing, when you hit the hidden column focus disappears until you tab again. This will confuse users."

Duane answered 3/5, 2012 at 6:31 Comment(1)
Use `table.getModel().getValueAt(table.convertRowIndexToModel(row), 4).Barley
L
9

Set the min, max and "normal" width to 0:

jTable.getColumn("ABC").setMinWidth(0); // Must be set before maxWidth!!
jTable.getColumn("ABC").setMaxWidth(0);
jTable.getColumn("ABC").setWidth(0);

Note: Since you can't set a maxWidth < minWidth, you need to change minWidth, first (javadoc). Same is true for width.

The second approach is to extend TableColumnModel and override all the methods to create the illusion (for the JTable) that your model doesn't have those two columns.

So when you hide a column, you must return one less when the table asks for the number of columns and when it asks for the column X, you may have to add +1 to the column index (depending on whether it is to the left or right of the hidden column), etc.

Let your new table model forward all method calls (with the corrected indexes, etc) to the actual column model and use the new table model in the JTable.

Lunsford answered 29/9, 2009 at 12:29 Comment(4)
You must also set min and max width.Lunsford
Why the order is important, i tried it first and i didnt use the same order so it doesn't work, oec i used the same order (width, min, max) it works, so WHY?Frankenstein
@MohammedHousseynTaleb Interesting. It seems that those aren't simple setters. My guess is that listeners are installed to update the layout and layout in Swing is <s>sometimes</s>usually surprising.Lunsford
@MohammedHousseynTaleb ty for comment. I also did it in the wrong order and now had a look in the code: this.maxWidth = Math.max(minWidth, maxWidth); Now it should be clear. If minWidth is set to 10 and you want to set maxWidth to 0 then it will take minWidth ... Actually it is also mentioned in the javadoc (but I also didn't read)Tole
D
8

i had the same problem and because of i am using TableColumnModel removColumn(); does'not help me so i used this

table.getColumnModel().getColumn(0).setWidth(0);
table.getColumnModel().getColumn(0).setMinWidth(0);
table.getColumnModel().getColumn(0).setMaxWidth(0); 

and worked fine for me it hide a column 0 and i still able to get value from it

Dayton answered 26/1, 2016 at 23:3 Comment(1)
(1-) not sure why these suggestions are repeated multiple times. It was first suggested 7 years earlier and frankly was a poor suggestion then. Setting the column width does NOT remove the column from the table it only hides the data. The user will still need to tab through this column which is confusing. Don't do this.Shiism
S
-1

If you remove the column from the JTable the column is still present in the TableModel.

For example to remove the first ID column:

TableColumnModel tcm = table.getColumnModel();
tcm.removeColumn(tcm.getColumn(0));

If you want to access the value of the removed column, you have to access it through the getValueAt function of the TableModel, not the JTable. But you have to convert to rowIndex back to rowIndex in the model.

For example if you want to access the first column of the selected row:

int modelRow = table.convertRowIndexToModel(table.getSelectedRow());
int value = (Integer)table.getModel().getValueAt(modelRow,0);
Sorcim answered 6/4, 2019 at 8:22 Comment(1)
(1-) `) it was already stated you need to get the data from the model, not the table. 2) the row index has nothing to do with the column. You would still need to convert the row index even if the column was not removed.Shiism
P
-3

I have tried them all: they don't help. The BEST way ever is to make a new table model without the column you want to delete. This is how you do it:

table = (DefaultTableModel) <table name>.getModel();
DefaultTableModel table1 = new DefaultTableModel();
Vector v = table.getDataVector();
Vector v1 = newvector(v,<column index you want to delete>);

Vector newvector(Vector v,int j){
    Vector v1= new Vector();
    try{
        Vector v2;
        Object[] o = v.toArray();
        int i =0;
        while(i<o.length){
            v2 = (Vector) o[i];
            v2.remove(j);
            v1.add(v2);
            i++;
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null,"Error in newvector \n"+e);
    }
    return v1;
}

Vector getColumnIdentifiers(int i) {
    Vector columnIdentifiers = new Vector();
    int j=0;
    while(j<i){
        columnIdentifiers.add(("c"+(j+1)));
        j++;
    }
    return columnIdentifiers;
}
table1.setDataVector(v1,getColumnIdentifiers((<column count>-1)));
<table name>.setModel(table1);
Postliminy answered 18/8, 2012 at 17:17 Comment(0)
A
-4

You could create a subclass of the model, and override TableModel.getColumnCount as follows:

int getColumnCount() {
    return super.getColumnCount()-2;
}

The last two columns would then not be displayed in the JTable.

Adjectival answered 29/9, 2009 at 12:30 Comment(5)
but can I get the data from them ?Lasting
you're only creating the illusion that the columns aren't there, but the are still there and should thus be able to get the data stillConstituent
But how should I hide them from GUI.Lasting
Not sure I understand what you mean by that. Do you mean that the user of you application should be able to hide or show?Adjectival
Hey I solved that issue by using following code jtable.removeColumn(jtable.getColumnModel().getColumn()); Column gets hide from GUI and we can also get the stored value from it.Lasting

© 2022 - 2024 — McMap. All rights reserved.