Hide a column in a JTable

Hi All, hope you can help,
I want to hide the last column of my table, but still access its data. Inside the last column certain information is present, the cell tooltips.
In my extended JTable class my method getToolTipText looks like this:
        // implement table cell tool tip.
        public String getToolTipText(MouseEvent e) {
            String tip             = null;
            Point  p               = e.getPoint();
            int    rowIndex        = rowAtPoint(p);
            int    colIndex        = columnAtPoint(p);
            int    realColumnIndex = convertColumnIndexToModel(colIndex);
            if(rowIndex>=0 && rowIndex<=lastRow) {
                if(realColumnIndex==0) {
                    MiniModel mml = (MiniModel)getValueAt(rowIndex, 5); // exception here
                    tip = "<html>" + replaceCRLFtoBR(mml.getComment()) + "</html>"; // replaceCRLFtoBR = custom method to replace \n by <br>
                } else {
                    tip = columnTips[realColumnIndex]; // constant
            return tip;
        }As you can see at column 5 an object MiniModel is present containing the tooltip for column 0.
When I use the method removeColumn on column 5 on my extended JTable variable, I get an java.lang.ArrayIndexOutOfBoundsException at the marked position and in more detail on getValueAt.
As I read everywhere the actual data is not removed (only from the view) I wonder what I'm doing wrong...
Michiel

Thanks for the advice, I will prepare better next time, here is my sscce :
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
public class TableHide extends JFrame {
    private static final String[] colNames    = {"Column 1", "Column 2", "Column 3"};
    private static final String[] colHeadTips = {"Header tip 1", "Header tip 2", "Header tip 3"};
    private ExtTableModel    myTableModel;
    private ExtTable         myTable;
    private JScrollPane      myScrollPane;
    private int              lastRow = 0;
    // for example
    private MiniModel mmlRow1 = new MiniModel(1, "cell comment");
    private MiniModel mmlRow2 = new MiniModel(2, "other cell comment");
    // constructor
    public TableHide() {
        this.setTitle("Table column hide test");
        this.setResizable(true);
        this.setLayout(new BorderLayout());
        // build table containing all extended Model's id and name
        myTableModel = new ExtTableModel(null, colNames);
        myTable      = new ExtTable(myTableModel);
        myTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
        myTable.setPreferredScrollableViewportSize(new Dimension(500, 130));
        myTable.setFillsViewportHeight(true);
        myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        myTable.getTableHeader().setReorderingAllowed(false);
        myScrollPane = new JScrollPane(myTable);
        this.add(myScrollPane, BorderLayout.CENTER);
        // add some rows, in real application this is more complex
        myTableModel.insertRow(0, new Object[]{ "Basic string", new Boolean(false), mmlRow1 }); lastRow++;
        myTableModel.insertRow(0, new Object[]{ "Other string", new Boolean(true) , mmlRow2 }); lastRow++;
        myTable.setAutoCreateRowSorter(true);
        myTable.getRowSorter().toggleSortOrder(0);
        // this causes the exception
        myTable.removeColumn(myTable.getColumnModel().getColumn(2));
        this.setSize(new Dimension(500,200));
    // inner class to provide an own table model for the extended Models showed on screen. used for booleans
    class ExtTableModel extends DefaultTableModel {
        public ExtTableModel(Object[][] tableData, String[] columnNames) {
            super(tableData, columnNames);
        public boolean isCellEditable(int row, int col) {
            return false;
        public Class getColumnClass(int column){
            Object value=this.getValueAt(0,column);
            return (value==null?Object.class:value.getClass());
    // inner class to privide column header tooltips and cell tooltips
    class ExtTable extends JTable {
        public ExtTable(ExtTableModel extModel) {
            super(extModel);
        // implement table cell tool tip.
        public String getToolTipText(MouseEvent e) {
            String tip             = null;
            Point  p               = e.getPoint();
            int    rowIndex        = rowAtPoint(p);
            int    colIndex        = columnAtPoint(p);
            int    realColumnIndex = convertColumnIndexToModel(colIndex);
            if(rowIndex>=0 && rowIndex<=lastRow) {
                if(realColumnIndex==0) {
                    MiniModel mml = (MiniModel)getValueAt(rowIndex, 2);
                    tip = mml.getMml_comment();
                } else {
                    tip = "Some other tooltip function";
            return tip;
        // implement table header tool tip.
        protected JTableHeader createDefaultTableHeader() {
            return new JTableHeader(columnModel) {
                public String getToolTipText(MouseEvent e) {
                    Point  p         = e.getPoint();
                    int    index     = columnModel.getColumnIndexAtX(p.x);
                    int    realIndex = columnModel.getColumn(index).getModelIndex();
                    return colHeadTips[realIndex];
    // simplified class for usage inside a cell
    public class MiniModel {
        private int        mml_id;
        private String     mml_comment;
        public MiniModel(int mml_id, String mml_comment) {
            this.mml_id      = mml_id;
            this.mml_comment = mml_comment;
        public String getMml_comment() {
            return mml_comment;
        public String toString() {
            return Integer.toString(mml_id); // called when object is displayed
    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception ex) {
                    ex.printStackTrace();
                new TableHide().setVisible(true);
}When you show the last column the program works fine. Goal is to have the last column available since it contains extra information about the row, but not to show it.

Similar Messages

  • How to hide a column in a JTable?

    Hi,
    Is it possibile to hide a column in a JTable?
    I mean not to remove, but just to hide the column (I need its values).
    Thanks
    LuKe

    Yup, just set the maximum width to zero:
    TableColumn result = getColumnModel().getColumn(index);
                result.setMinWidth(0);
                result.setPreferredWidth(0);
                result.setWidth(0);
                result.setMaxWidth(0);

  • How to hide the column in JTable

    Hi
    I want to hide a column . But I would be needing the data in that column. ( I have 4 columns )
    I want to hide 4th column
    I have done these steps
    MyTableModel  myTableModel= new  MytableModel(t);
    myTable  = new JTable(myTableModell);                 
    mTable.getColumnModel().removeColumn(myTable.getColumnModel().getColumn(3));When I trying to read the column 1 value it is giving the exception
    myTable.getValueAt(row,3).toString();It is giving the arrayboundexception
    Can anybody tell me what is the correct method to do ?
    Thanks and regards
    Anshuman

    Thanks for reply .
    I have taken the value as the convertRowToModel
    WalterLaan wrote:
    You get an exception because the table doesn't have a column at index anymore, but you can still ask the model.
    table.getModel().getValueAt(table.convertRowToModel(row), 3);
    But it is giving the same error
    java.lang.ArrayIndexOutOfBoundsException: 4 >= 4
         at java.util.Vector.elementAt(Unknown Source)
         at javax.swing.table.DefaultTableColumnModel.getColumn(Unknown Source)
         at javax.swing.JTable.convertColumnIndexToModel(Unknown Source)
         at javax.swing.JTable.getValueAt(Unknown Source)Edited by: techie_india on Jul 6, 2009 10:38 PM

  • Hide a column in JTable

    Dear all,
    I want to hide a column in JTable object, I already tried resize it to 0 but the effect is not good, I also cannot remove the column, since I need this column for other process.
    So, any other good idea besides resizes and remove?
    Thank you very much!

    I have tried that too, but the column isn't hide, the size is not actually come to 0,...That's because JTable has a default minimum width of 15.... if you want to hide the column, you must set the minwidth as well. For example:
    myTable.getColumnModel().getColumn(column_to_hide).setMinWidth(0);
    myTable.getColumnModel().getColumn(column_to_hide).setPreferredWidth(0);;o)
    V.V.

  • Hiding Columns in a JTable

    Hi folks,
    I'm developing a program, one part of which should show in a table the information it got from the DB. It works just fine. The problem is - the user doesn't need to see all the columns (some of them are even unknown and are for intern use only). How could I hide those columns? Or should I create another TableModel and show it instead?
    Thanks in advance

    As a new member you should learn how to search the forum before asking a question.
    A simple search would use "hiding column jtable" as the keywords as an example.

  • How can I add custom right-click-menu to column headers in JTable?

    Can anyone point me to a topic on how to customize a popup menu for column headers in JTable? Specifically, I want to add things like "auto-size column" and "hide column".
    Thanks,
    Matt

    Right-click on your table.  Then go to Advanced->Runtime Shortcut Menu->Edit.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Is it possible to hide the inbetween rows in jTable

    I want to Hide the particular Rows within a jTable. For example the first column of the jTable contains the Values are,
    1
    2
    3
    4
    5
    6
    7
    etc.,
    in an ascending order.
    I want to Hide the Even numher rows like 2,4,6,...etc.,
    Is it possible?

    Look at some of these they may help.
    Searched on "filter jtable"
    http://onesearch.sun.com/search/onesearch/index.jsp?qt=filter+jtable&subCat=&site=dev&dftab=&chooseCat=javaall&col=developer-forums
    rykk

  • Show hidden columns in a JTable

    Hi,
    I have a requirement for hiding some columns of a JTable and showing them back based on user actions.
    I have gone through some topics about hiding columns. which can be done by table.removeColumn();
    But when I use table.addColumn(); it adds the column at the end of the table.It should add in the same location as the previous column.
    How to show /reveal the hidden column back?.

    * Hide_Columns.java
    * This code contains a table model that allows you to
    * specify the columns to be hidden in a boolean array.
    * To use the model:
    *       model = new MyTableModel(data, columnNames);
    *       table.setModel(model);
    * The most important method in the model is "getNumber()", which converts a column number
    * into the number corresponding to the data to be displayed.
    * Visible columns can be dynamically changed with
    * model.setVisibleColumns(0, column0.isSelected());
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Hide_Columns extends JFrame {
        public Hide_Columns() {
            setTitle("Hide columns");
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            model = new MyTableModel(data, columnNames);
            table.setModel(model);
            getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
            for( int i=0; i<4; i++ ){
                final JCheckBox columnX = new JCheckBox("Column "+i);
                columnX.setSelected(true);
                final int col = i;
                columnX.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        model.setVisibleColumns(col, columnX.isSelected());
                toolBar.add(columnX);
            getContentPane().add(toolBar, BorderLayout.NORTH);
            setSize(400,300);
            setLocationRelativeTo(null);
            model.addRow(new Object[]{null,null,null,null});
            model.setValueAt("test0",0,0);
            model.setValueAt("test1",0,1);
            model.setValueAt("test2",0,2);
            model.setValueAt("test3",0,3);
        public static void main(String args[]) { new Hide_Columns().setVisible(true); }
        private JTable table = new JTable();
        private  JToolBar toolBar = new JToolBar();
        private   MyTableModel model;
        /** This is the data of the table*/
        private  Vector<Object> data = new Vector<Object>();
        /** Column names */
        Vector<String> columnNames = new Vector<String>();{
            columnNames.addElement("0");
            columnNames.addElement("1");
            columnNames.addElement("2");
            columnNames.addElement("3");
    class MyTableModel extends DefaultTableModel {
        /** Shows which columns are visible */
        private   boolean[] visibleColumns = new boolean[4];{
            visibleColumns[0] = true;
            visibleColumns[1] = true;
            visibleColumns[2] = true;
            visibleColumns[3] = true;
        public MyTableModel(Vector<Object> data, Vector<String> columnNames){
            super(data, columnNames);
        protected void setVisibleColumns(int col, boolean selection){
            visibleColumns[col] = selection;
            fireTableStructureChanged();
         * This function converts a column number of the table into
         * the right number of the data.
        protected int getNumber(int column) {
            int n = column;    // right number
            int i = 0;
            do {
                if (!(visibleColumns)) n++;
    i++;
    } while (i < n);
    // When we are on an invisible column,
    // we must go on one step
    while (!(visibleColumns[n])) n++;
    return n;
    // *** METHODS OF THE TABLE MODEL ***
    public int getColumnCount() {
    int n = 0;
    for (int i = 0; i < 4; i++)
    if (visibleColumns[i]) n++;
    return n;
    public Object getValueAt(int row, int column) {
    return super.getValueAt(row, getNumber(column));
    public void setValueAt(Object obj, int row, int column) {
    super.setValueAt(obj, row, getNumber(column));
    public String getColumnName(int column) {
    return super.getColumnName(getNumber(column));

  • JTextFields above column headers in JTable

    I am looking for a way to put a single row above (for filtering purposes) the table header in a JTable. Right now I am using JTextFields above my table for the filters, but as the columns are resized or moved so would the text fields have to be. So I am thinking putting a row above the table header would be appropriate.
    Any suggestions or examples in this area?

    Hello
    I've been working on something similar (filters above a JXTable) and i managed to get it working. So i'm putting it on this thread if someone find it with google :)
    The code for moving / resizing columns works fine, but the code for removing/adding columns doesn't work very well because it only allows one removed column at a time, or that you add the columns in the correct order.
    My solution is a bit different. I put a listener on the column property "visible", associated with the filter component above the column. That way, when i remove (hide) a column, the filter component removes itself from the panel, and when i reactivate the column, the component adds itself to the panel.
    Because the property change event is fired after the columnadded / columnmoved event, i have to use invokeLater thread to actually move the component at its right position.
    Here's the code for the moved/resized listener:
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.TableColumnModelEvent;
    import javax.swing.event.TableColumnModelListener;
    import javax.swing.table.TableColumnModel;
    import fr.dga.gesma.catalyse.ihm.beans.FilterPanel;
    public class ExternalHeaderColumnModelListener implements TableColumnModelListener {
        private JPanel filterRow;
        private JTable table;
        public ExternalHeaderColumnModelListener(JPanel header, JTable table) {
            filterRow = header;
            this.table = table;
        public void columnAdded(TableColumnModelEvent e) {
        public void columnRemoved(TableColumnModelEvent e) {
        public void columnMarginChanged(ChangeEvent e)
            TableColumnModel tcm = table.getColumnModel();
            int columns = tcm.getColumnCount();
            for (int i = 0; i < columns; i ++)
                FilterPanel filtre = (FilterPanel)filterRow.getComponent( i );
                Dimension d = filtre.getPreferredSize();
                d.width = tcm.getColumn(i).getWidth();
                filtre.setPreferredSize( d );
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    filterRow.revalidate();
        public void columnMoved(TableColumnModelEvent e)
            final int toIndex = e.getToIndex();
            final int fromIndex = e.getFromIndex();
            // Delaying so the component exists when we move it
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    Component moved = filterRow.getComponent(fromIndex);
                    if (moved != null) {
                        filterRow.remove(fromIndex);
                        filterRow.add(moved, toIndex);
                        filterRow.validate();
        public void columnSelectionChanged(ListSelectionEvent e) {}and the code for the filter component (listener part) :
        private Container parent = null;
        // Taken from ColumnControlButton (JXTable component)
        // This listener is added to the TableColumn associated to this filter component
        protected PropertyChangeListener createPropertyChangeListener() {
            return new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent evt) {
                    if ("visible".equals(evt.getPropertyName())) {
                        updateFromColumnVisible((Boolean) evt.getNewValue());
         * Hides or shows the filter component. This
         * is called on change of tablecolumn's <code>visible</code> property.
         * @param visible column visible state to synch to.
        private void updateFromColumnVisible(boolean visible) {
            if (visible) {
                if (parent != null) {
                    parent.add(this);
                    parent.validate();
            } else {
                parent = this.getParent();
                if (parent != null) {
                    parent.remove(this);
                    parent.validate();
        }Hope this helps someone :)

  • Hiding columns of a JTable

    I want to hide some of the columns of my JTable. Plz tell me how to do it?
    Thanks in advance

    Alternatively, remove those columns from the table's columnModel.Definitely the preferred approach.
    Wouldn't you still have to modify the TableModel so that the getValueAt method doesn't return the wrong value?No, the view of the table is not necessarily the same as the order of the data in the TableModel. What happens, for example when a column of the table is reordered? Well, each TableColumn contains a reference to a specific column in the TableModel. So the TableColumnModel is used by the table to control the view of the table and the TableColumn will get the data from the correct column. This way you can reorder TableColumns or remove TableColumns withouth affecting the TableModel only the view of the table.
    My FixedColumnScrollPane example uses this feature:
    http://forum.java.sun.com/thread.jspa?forumID=257&threadID=500055
    By the way, when you use the getValueAt(...) method you have to be carefull which index you use for the column.
    a) Do you want the first column viewable in the table, then just use the column
    b) Do you want the first column from the TableModel. In this case you have some helper methods (in case columns have been reordered or removed):
    convertColumnIndexToModel()
    convertColumnIndexToView()

  • How to get all the values in one column of a JTable

    How to get all the values in one column of a JTable as a Collection of String.
    I don;t want to write a for loop to say getValueAt(row, 1) eg for 2nd column.

    I don;t want to write a for loop to say getValueAt(row, 1) eg for 2nd column. You could always write a custom TableModel that stores the data in the format you want it. It would probably be about 50 lines of code. Or you could write a loop in 3 lines of code. I'll let you decide which approach you want to take.

  • SSRS 2005 - Dynamically control the width of columns in Matrix report or Hide any column

    Hi All,
    I just want to hide some column without having white space in Matrix report in SSRS 2005. Although I am aware of that perhaps this feature is not available on SSRS 2005. So, I just want to know if we can handle the width of column dynamically(using expressions)
    in matrix report?
    Please help. Thanks in Advance.
    Regards
    Kumud

    Hi Kumud,
    Based on my test, SSRS is not support column dynamically width. It has property “CanGrow” of text box. If we configure the property to True, it will wraps to next line if needed. In SSRS 2008, we can hide some columns without white space. If possible, I
    recommend you update your SSRS 2005 to SSRS 2008.
    There is a similar issue, you can refer to it.
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/9e6043f1-c458-4540-be59-d37b02feab8a/dynamic-column-width-for-a-report?forum=sqlreportingservices
    Alternatively, I recommend you that submit a wish to the Microsoft Connect at
    https://connect.microsoft.com/SQLServer/Feedback. Your feedback is valuable for us to improve our products and increase the level of service provided.
    Regards,
    Alisa Tang
    Alisa Tang
    TechNet Community Support

  • How to show or Hide Generic Column in a regular report

    Hi All,
    I have created report based on "SQL query (pl/sql function body returning sql query). It returns columns based on some conditions. I have total 60 generic columns like (COL1,COL2....COL60) but it returns 18 or 20 columns based on my conditions, how can I hide the columns that I don't needed. My column heading is based on function return by ':' separated. My function returns number of columns also. Is there any we I can show only those columns which contains data. My report is exactly similar to the default "SQL query (pl/sql function body returning sql query). I didn't find any logic how they are doing this show and hide. I appreciate any ones help.
    Thanks,

    Hi there,
    Somehow you need to find out how many columns your dynamic select will return (by what you said it seems that your procedure returns this information). Then store that number in a hidden page item, say Pnn_COUNT.
    Then, for the 19th and 20th columns in the report add these conditions:
    Column 19: :Pnn_COUNT >= 19
    Column 20: :Pnn_COUNT >= 20
    I hope this helps.
    Luis

  • How to hide Actions Column in Table

    Hi All,
    I have a simple requirement: I am showing a table (items)
    - the "Actions" column (Column with Buttons to Edit and Delete a particualr row) must not be show -> no changes to the table are allowed (I need to hide/ disable this column)
    How can I hide this column od the table?
    I have found out that the field is called thtmlb_oca and that htere is a getter method get-thtmlb_oca. However, the method does not contain coding and I do not know how to HIDE this field/ column...
    Please help me here..
    Thanks, Johannes

    Hi Johannes,
    To remove the column completely,
    you need to comment this line in the method GET_TABLE_LINE_SAMPLE of the Table View Context node class.
    TYPES: BEGIN OF line,
    *  thtmlb_oca  type  crm_thtmlb_one_click_action.
      INCLUDE TYPE xxxx.
      TYPES:  END OF line.
    Disabling can be controlled in the method GET_OCA_T_TABLE of the same class by putting code to delete the button.
    LOOP AT  rt_actions ASSIGNING <fs_actions>.
          <fs_actions>-active  = abap_false.
        ENDLOOP.
    Regards,
    Masood Imrani S.

  • Hide a column in one view, but show in other

    Hi all.
    I need to hide a column on "Table" view, but column needs to show up on "Pivot table".
    I know we can hide it on pivot ( exclude It ) and show on table, but I want to know if reverse is possible.
    This is needed because I am doing a view selector for writeback. And I dont want to display all the columns on writeback table view. But it needs to be there on Pivot table.
    Please let me know if it is possible.
    Thanks.
    Vinay

    Yes we can do that.
    Check on the "Hide" in the column format tab of the column that you need to display in the table lay out.
    Now dupliate the same view and in the pivot table column intially you will not see the column displayed.
    Now in the properties check on "hidden" in the "format headings" and you wont see it still and now uncheck the"hidden" and you shoud be able to see the column displayed in the pivot view
    In this way you will have the column hidden in the table view and displayed in the pivot table.
    Hope it helps
    Prash

Maybe you are looking for

  • 2nd Gen Shuffles charge with power adapter, not seen at all by computer

    I have three Gen 2 Shuffles (mine and kids), and am having same problem with all three. If I plug them into either of our home computers - an iMac and a brand  new Macbook Pro - they don't even seem to be recognized at all by the computer as even bei

  • Making filter setting changes propagate throughout my project?

    I'm using FCPro 4.5. Say I want to apply a particular color correction setting to a bunch of clips in my project's timeline. What I've done is I've saved off an instance of the 3-way filter with the settings I like into my favorites folder, and I've

  • DVD Studio Pro translated subtitle files (Spanish) - which format?

    I have an option to receive one of the following subtitle file formats from a subtitler/translator for DVD Studio Pro: - Spruce Text .stl file (text-based file, it will have font size information but you can edit if necessary; color is not specified

  • Error loading lynx (solved, thank you)

    Hello. I've got a clean base arch installation. 1st: I've installed Lynx web browser using pacman. When I type pacman -Qs lynx the result is: local/lynx 2.8.5-3 When I type lynx it says: error while loading shared libraries - libssl.so.0.9.8 I've the

  • Upgrading Oracle 8.1.7.2.1 to Oracle 10gR2

    My project is in Analysis Phase and I am not Oracle DBA.(PL/sql developer only.) I have few questions to check.How well we can do this upgradation. My current Oracle8i is lying on WindowsNT server. Step-1)we are trying to Upgrade to windows2008 versi