About hiding columns in a JTable.

I have read various ideas on how to hide columns in these forums,. Everything from using the removeColumn method in TableColumnModel to writing a wrapper TableModel to handle the details. These ideas work, but in certain situations it is difficult to retro-fit the code in this manner. Being that Swing has a MVC architecture, does it not make since that I should be able to alter the view ( The Table ) any way I like without altering the underlying models? Does anyone have a good solution?
I already had implemented a TableModel which does this, and a TableColumnModel. Probelm is, I have external libraries that make extensive use of the DefaultTableColumnModel in the JTable, and I would rather not have to alter it. those libraries.
Thanks.
AC

Being that Swing has a MVC
architecture, does it not make since that I should be
able to alter the view ( The Table ) any way I like
without altering the underlying models? Does anyone
have a good solution?I can see your point, but JTable presents the view it does which is customizable in certain ways only.
The hiding of columns just isn't part of what it does.
So you could extend JTable to add such functionality. Having looked at the source of JTable recently, I wouldn't want to do that.
The alternative is to wrap existing models in another model that does some transformation (i.e. hiding a column) without changing the underlying model. See the TableMap and TableSorter examples in the Swing Table Tutorial to see an example of this.

Similar Messages

  • 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.

  • 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()

  • 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));

  • 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.

  • How can I use a column header to select columns in a JTable?

    Hello,
    I've been working for ages on this, but I still can't come up with a suitable solution. What I want to be able to do is select a column header from a JTable, which in turn would select the corresponding column in my JTable. I cant seem to do this with a mouse listener, and I can't see how to toggle the buttons of the header either.
    Any help would be gratefully appreciated.
    Mike

    I have both row and columns selected depending on what you do in the JTable. Here's my code:
    where you init your JTable add:
    addressTable = new JTable(addressTableModel, addressTableColumnModel);
    JTableHeader th = addressTable.getTableHeader();
    th.addMouseListener(new tableHeaderMouseAdapter(addressTable));
    addressTable.getSelectionModel().addListSelectionListener(new selectionListener(addressTable));
    addressTable.setColumnSelectionAllowed(true);
    tableHeaderMouseAdapter looks like this (it should look familiar):
    private class tableMouseAdapter extends MouseAdapter
         private JTable tableView;
         public tableMouseAdapter(JTable newTableView)
              tableView = newTableView;
         public void mouseClicked(MouseEvent e)
              int selectedRow = tableView.getSelectedRow();
              if ((e.getClickCount() == 1) && (selectedRow != -1))
                   tableView.clearSelection();
                   tableView.setRowSelectionInterval(selectedRow, selectedRow);
                   tableView.setColumnSelectionInterval(0, tableView.getColumnModel().getColumnCount() - 1);
    selectionListener looks like this:
    private class selectionListener implements ListSelectionListener
         private JTable tableView;
         private boolean changingSelection;
         public selectionListener(JTable newTableView)
              tableView = newTableView;
              changingSelection = false;
         public void valueChanged(ListSelectionEvent e)
              if ((!changingSelection) && (tableView.getSelectedColumnCount() < tableView.getColumnCount()) && (tableView.getSelectedRowCount() < tableView.getRowCount()))
                   changingSelection = true;
                   int selectedRow = tableView.getSelectedRow();
                   if (selectedRow >= 0)
                        tableView.clearSelection();
                        tableView.setRowSelectionInterval(selectedRow, selectedRow);
                   tableView.setColumnSelectionInterval(0, tableView.getColumnModel().getColumnCount() - 1);
                   changingSelection = false;
    I'm sure there is a better way to do this, but it's the first thing I could get to work.
    disclamer:
    Use this code at your own risk. I make no claims about this code whatsoever.

  • Selective reordering of columns in a Jtable

    Hi
    I have this problem where I need to allow the first 8 columns to be reordered but not the remaining columns in a Jtable.
    I have tried a few approaches by adding listeners to the jtable header and identifying the column which is clicked for reordering and accordingly setting the rearrange policy / feature of the jtable to true/false.
    This works fine in almost all scenarios except for one where the user selects a column which can be reordered and drags it to a position beyond the allowed 8 columns, and now that column is frozen since it is beyond the permissible index of 8.
    I was wondering if there was a 'cleaner'/ better way to go about implementing this.

    Thanks for the link...
    I went through it but seems like a big change for the functionality I want to achieve.
    I am thinking about allowing the user to reorder the column and then if he has chosen an invalid column (one which cannot be rearranged) just undo that action using the moveColumn method.
    I tried overriding the columMoved method to inform me about a column reorder evernt but that method keeps getting fired while the user is rearranging.
    Is there anyway to get a notification once the user is done rearranging the column.
    Thanks

  • Event getting trigger after hiding columns in alv report

    Hi All,
              I having requirement like after hiding columns,i have to control some of the hard coded data in report output. Is there any event to know what all are the columns are selected to hide?

    You can use FM REUSE_ALV_LIST_LAYOUT_INFO_GET to read the fieldcat again.
    Look at the parameter it_event_exit on the ALV FM to now  user has press on some of the Layout buttons.
    In the fieldcatalog, look for
    - no_out = 'X'.  " column is not displayed but can be choosen when changing the layout
    -tech    = 'X'.
      " column is neither displayed nor availabe in the layout

  • 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

  • How to create Hyperlink column in a JTable

    Can anyone help in creating a hyperlink column in a JTable.
    Thanks in advance,
    Sridhar.

    If the parent is an Applet it is very simple .
    catch the mouse click on columns and execute the following code
    String url = getValueAt(i,j);
    getAppletContext().showDocument(new
    URL(url ), "_blank");
    thatz all .
    if ur program is an application use this getRuntime.exec() and use parameters to rundll32.exe url and iexplore.exe in Windows platform,
    if u have still doubts plz get back to me
    Renjith K.V

  • How to fix the value of first column in the JTable in java swing for every

    Hi ,
    I have a swing page that have table panel in which there is a table of size 7x4 now when I click on the perticulat row then that row data will displayin the table like that the selected row become the second column in the new table and the fist column of this table will remain constant for all the entry but the second column update according to the roe which is selected .How it is possible .
    Thanks in Advace,
    anu

    One thing you can do is to prevent the user from editing that column and programatically supply the values of that column yourself.
    JTable table = new JTable() {
       public boolean isCellEditable(int row, int col) {
           if(col == 0) {
              return false;
           return super.isCellEditable(row, col);
    };This allows you to prevent the user from editing the column information so you can supply some sort of a default value for the column always
    ICE

  • Looking for component: flexible rows like columns in a JTable

    Hello,
    I need a swing component to display several rows which can be moved up and down, the height resized, interchanged with the mouse like the columns in a JTable. But there is no need for columns. I think there is no standard swing component.
    Any ideas, resource hints?
    Thanks, Ulrich

    One more piece of advice. It is not very easy to get "pre-written custom components". Most developers do things to meet their own needs and these may not be exactly what you are looking for. The best thing to do is to try to develop this yourself. It will give you loads of experience and in later programmes you may write, based on the experience you obtained from the "pain-staking" development process you'll know how to go round these problems quicker and may be able to help others also.
    So just start writing some stuff. You may end up finishing sooner than you think. And remember forum members are always ready to help with problems (accompanied by minimal code examples of the actual problem).
    ICE

  • Help for adjusting columns of a JTAble in a Table Model

    Hello community,
    In order to have a good display of by DataBase in a JTable, I've wrote some code to adjust columns in function of datas. Those datas are displayed with a TableModel ( which I've declared in a class JDBCAdapter ).
    When I start my application, I call adjustColumns(), and all is great but when I add information to my DB and display it, the columns of my JTable return to default width...
    So I want to incorporate my function adjustColumns in my TableModel, and I need help...
         void adjustColumns()
         // Ajuste les colonnes aux donnes pour que tout soit visible
         int nbRow,nbCol;
         nbRow = JTable1.getRowCount();
         nbCol = test.getColumnCount();
         for ( int i = 0; i < nbCol; i++ )
         com.sun.java.swing.table.TableColumn column = null;
         column = JTable1.getColumnModel().getColumn(i);
         int dataLength = 0;
         for ( int j = 0; j< nbRow; j++ )
         FontMetrics fm;
         int dataLengthTmp;
         String valueTable;
         fm = JTable1.getFontMetrics(JTable1.getFont());
         if ( test.getValueAt(j, i) == null )
         System.out.println("Valeur nulle...");
         dataLengthTmp = 0;
         else
         valueTable = test.getValueAt(j, i).toString();
         dataLengthTmp = fm.stringWidth(valueTable);
         System.out.println(valueTable + " = " + dataLengthTmp);
         if ( dataLengthTmp > dataLength )
         dataLength = dataLengthTmp;
         if ( dataLength != 0 )
    column.setWidth(dataLength + 5);
    else
    column.sizeWidthToFit();
    JTable1.setModel(test);
    JTable1.repaint();
    import java.util.Vector;
    import java.sql.*;
    import com.sun.java.swing.table.AbstractTableModel;
    import com.sun.java.swing.event.TableModelEvent;
    public class JDBCAdapter extends AbstractTableModel {
    Connection connection;
    Statement statement;
    ResultSet resultSet;
    String[] columnNames = {};
    Vector rows = new Vector();
    ResultSetMetaData metaData;
    public JDBCAdapter(String url, String driverName,
    String user, String passwd) {
    try {
    Class.forName(driverName);
    System.out.println("Ouverture de la connexion a la base de donnee...");
    connection = DriverManager.getConnection(url, user, passwd);
    statement = connection.createStatement();
    catch (ClassNotFoundException ex) {
    System.err.println("Cannot find the database driver classes.");
    System.err.println(ex);
    catch (SQLException ex) {
    System.err.println("Cannot connect to this database.");
    System.err.println(ex);
    public void executeQuery(String query) {
    if (connection == null || statement == null) {
    System.err.println("There is no database to execute the query.");
    return;
    try {
    resultSet = statement.executeQuery(query);
    metaData = resultSet.getMetaData();
    int numberOfColumns = metaData.getColumnCount();
    columnNames = new String[numberOfColumns];
    // Get the column names and cache them.
    // Then we can close the connection.
    for(int column = 0; column < numberOfColumns; column++) {
    columnNames[column] = metaData.getColumnLabel(column+1);
    // Get all rows.
    rows = new Vector();
    while (resultSet.next()) {
    Vector newRow = new Vector();
    for (int i = 1; i <= getColumnCount(); i++) {
    newRow.addElement(resultSet.getObject(i));
    rows.addElement(newRow);
    // close(); Need to copy the metaData, bug in jdbc:odbc driver.
    fireTableChanged(null); // Tell the listeners a new table has arrived.
    catch (SQLException ex) {
    System.err.println(ex+" query = "+query);
    public void executeUpdate(String query) {
    if (connection == null || statement == null) {
    System.err.println("There is no database to execute the query.");
    return;
    try {
    statement.executeUpdate(query);
    // close(); Need to copy the metaData, bug in jdbc:odbc driver.
    fireTableChanged(null); // Tell the listeners a new table has arrived.
    catch (SQLException ex) {
    System.err.println(ex+" query = "+query);
    public void close() throws SQLException {
    System.out.println("Fermeture de la connection a la base de donnee... Bye !");
    resultSet.close();
    statement.close();
    connection.close();
    protected void finalize() throws Throwable {
    close();
    super.finalize();
    // Implementation of the TableModel Interface
    // MetaData
    public String getColumnName(int column) {
    if (columnNames[column] != null) {
    return columnNames[column];
    } else {
    return "";
    public Class getColumnClass(int column) {
    int type;
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return super.getColumnClass(column);
    switch(type) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    return String.class;
    case Types.BIT:
    return Boolean.class;
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return Integer.class;
    case Types.BIGINT:
    return Long.class;
    case Types.FLOAT:
    case Types.DOUBLE:
    return Double.class;
    case Types.DATE:
    return java.sql.Date.class;
    default:
    return Object.class;
    public boolean isCellEditable(int row, int column) {
    try {
    return metaData.isWritable(column+1);
    catch (SQLException e) {
    return false;
    public int getColumnCount() {
    return columnNames.length;
    // Data methods
    public int getRowCount() {
    return rows.size();
    public Object getValueAt(int aRow, int aColumn) {
    Vector row = (Vector)rows.elementAt(aRow);
    return row.elementAt(aColumn);
    public String dbRepresentation(int column, Object value) {
    int type;
    if (value == null) {
    return "null";
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return value.toString();
    switch(type) {
    case Types.INTEGER:
    case Types.DOUBLE:
    case Types.FLOAT:
    return value.toString();
    case Types.BIT:
    return ((Boolean)value).booleanValue() ? "1" : "0";
    case Types.DATE:
    return value.toString(); // This will need some conversion.
    default:
    return "\""+value.toString()+"\"";
    public void setValueAt(Object value, int row, int column) {
    try {
    String tableName = metaData.getTableName(column+1);
    // Some of the drivers seem buggy, tableName should not be null.
    if (tableName == null) {
    System.out.println("Table name returned null.");
    String columnName = getColumnName(column);
    String query =
    "update "+tableName+
    " set "+columnName+" = "+dbRepresentation(column, value)+
    " where ";
    // We don't have a model of the schema so we don't know the
    // primary keys or which columns to lock on. To demonstrate
    // that editing is possible, we'll just lock on everything.
    for(int col = 0; col<getColumnCount(); col++) {
    String colName = getColumnName(col);
    if (colName.equals("")) {
    continue;
    if (col != 0) {
    query = query + " and ";
    query = query + colName +" = "+
    dbRepresentation(col, getValueAt(row, col));
    System.out.println(query);
    System.out.println("Not sending update to database");
    // statement.executeQuery(query);
    catch (SQLException e) {
    // e.printStackTrace();
    System.err.println("Update failed");
    Vector dataRow = (Vector)rows.elementAt(row);
    dataRow.setElementAt(value, column);
    Thanks to help me.

    Hi,
    OK. I have read your code sample again. It looks like the JDBCAdapter class is reloading table data in the executeQuery method. Why not call adjustColumns at the end of this method after the new rows and columns are loaded? Perhaps it also should be called at the end of executeUpdate. Have you tried doing that?
    I would still set
    JTable1.setAutoCreateColumnsFromModel (false); to prevent Java from readjusting the size automatically at some other time.
    regards,
    Terry

  • How to set a JRadioButton as a column in a JTable

    Hello Friends,
    I need a help in JTable.
    I want to have a Radio button as a column of a JTable.(The Other Columns should be Strings).
    The heading of the Column which has the RadioButton is "Select" which means that I can select only one radiobutton at a time.
    Could you please give me a solution on this.
    I would appreciate if u give me the code for this, as it is very urgent.
    Thanks in Advance,
    Regards,
    Vijayakannan

    Hi,
    use a TableCellRenderer and CellEditor as described in http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    Propably you need to track the selected button yourself, e.g. by using an int value representing the row selected.

  • Right Justify a column in a JTable

    Hello,
    I formatted a decimal number and want to put it into a column in a JTable. Unfortunately, the value is being left justified. How do I make the data for the column right justitified?

    Thank you both for your answers. I had looked in the tutorial, but could not find the area for justifications. I did have a table model with a getColumnClass too, but didnt realize that I didnt have to use the actual data type's class to render the justification.
    Looking back at the tutorial, I now find that ImageIcon is supposed to be used for centering, but this didnt work. It wiped out the data for the column I tried to use it on rather than justifying it left or right. Any ideas how to get centering to work?

Maybe you are looking for

  • DVI to HDMI Audio not working

    So I bought a DVI to HDMI and I'm trying to play movies off my laptop to my HDTV and when I try to change the audio output, it does not show HDMI output. I bought this macbook pro 15" in september 2009. Can anyone help?

  • Merge multiple Cells in Numbers Spreadsheet

    I've imported an excel spreadsheet from my laptop into the numbers App on my iPad. I've hidden a number of columns in the spreadsheet and am now trying to merge cells in a row which starts in column A and ends in column AC, I've followed the instruct

  • Problem with update packages

    $ sudo pacman -Syu :: Synchronizing package databases... core is up to date extra is up to date community is up to date multilib is up to date :: Starting full system upgrade... :: Replace lib32-dbus with multilib/lib32-libdbus? [Y/n] y resolving dep

  • Help in BO WebI XI3.1 Input Control using language Translation

    Hello All, Need a help in BO WebI XI3.1 regarding Language Translation for Input Control. Input Control has been defined in the Report. The report is built in English language. The requirement here is to convert the report to French based on the Info

  • ITunes won't load..HELP!

    ok I have tried everything I know how to do..I try to download iTunes and I get an error that states: "There is a problem with this Windows Installer Package. A program required for this install to complete could not be run. Contact your support pers