Reodering columns in jtable

I want to reorder the column sequence in my jtable. But the number of columns I need to reorder are around 10. So i am trying to use the following
myTable.moveColumn(curIndex, newIndex);
Say I have columns like id, name ,age , ...etc. I want to set age to 1st column, id to 2nd column and so on.
int ageIndex= myTable.getColumn("age").getModelIndex();
myTable.moveColumn(ageIndex, 0);
int idIndex= myTable.getColumn("id").getModelIndex();
myTable.moveColumn(idIndex, 1);
int nameIndex= myTable.getColumn("name").getModelIndex();
myTable.moveColumn(nameIndex, 2);But when I see the final GUI , age is the 3rd column. I believe age is set to 1st column and then the latter ones are moving it. Can you please suggest how this can be avoided.
Thanks in advance.

Below is the code I created to try to understand the behavior of JTable.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SimpleTableDemo extends JPanel {
    private boolean DEBUG = true;
    public SimpleTableDemo() {
        super(new GridLayout(1,0));
        String[] columnNames = {"First Name",
                                "Last Name",
                                "Sport",
                                "# of Years",
                                "Vegetarian"};
        Object[][] data = {
         {"Kathy", "Smith",
          "Snowboarding", new Integer(5), new Boolean(false)},
         {"John", "Doe",
          "Rowing", new Integer(3), new Boolean(true)},
         {"Sue", "Black",
          "Knitting", new Integer(2), new Boolean(false)},
         {"Jane", "White",
          "Speed reading", new Integer(20), new Boolean(true)},
         {"Joe", "Brown",
          "Pool", new Integer(10), new Boolean(false)}
        final JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
//        table.setFillsViewportHeight(true);
        if (DEBUG) {
            table.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    printDebugData(table);
        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);
        //Add the scroll pane to this panel.
        add(scrollPane);
        rearrangeColumns(table);
    private void printDebugData(JTable table) {
        int numRows = table.getRowCount();
        int numCols = table.getColumnCount();
        javax.swing.table.TableModel model = table.getModel();
        System.out.println("Value of data: ");
        for (int i=0; i < numRows; i++) {
            System.out.print("    row " + i + ":");
            for (int j=0; j < numCols; j++) {
                System.out.print("  " + model.getValueAt(i, j));
            System.out.println();
        System.out.println("--------------------------");
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create and set up the content pane.
        SimpleTableDemo newContentPane = new SimpleTableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
    private static void rearrangeColumns(JTable table){
         int yearIndex = table.getColumnModel().getColumnIndex("# of Years");
         System.out.println("Removing the column with index :"+yearIndex);
         table.removeColumn(table.getColumn("# of Years"));
         int columnsNumber = table.getColumnCount();
         for(int num = 0 ; num < columnsNumber ; num++){
              String columnName = table.getColumnName(num);
              if(columnName.equalsIgnoreCase("First Name")){
                   table.moveColumn(num, 3);
              }else if (columnName.equalsIgnoreCase("Last Name")) {
                   table.moveColumn(num, 2);
               }else if (columnName.equalsIgnoreCase("Sport")) {
                    table.moveColumn(num, 1);
               }else if (columnName.equalsIgnoreCase("Vegetarian")) {
                    table.moveColumn(num, 0);
}I updated the example from the swing tutorial on the sun site. When I run this example the expectation is that 'Last Name' column should be the 3rd column, but it is displaying as 2nd. Can this inconsistent behavior be explained.
Edited by: snarikvs on Aug 9, 2010 2:46 PM

Similar Messages

  • Hiding a column in jtable made from DefaultTableModel.

    I have made my jtable from DefaultTableModel.
    I want to keep one column in the jtable as hidden storing some data containing neccessary information like the "path of the file"
    which need not be shown to the user.
    Please tell me how I can hide one column in the Jtable.
    please provide siome link or code for the same.
    Tia,
    Sarwa

    dayanandabv wrote:
    [http://search.sun.com/search/onesearch/index.jsp?qt=hide+column%2B+JTable&rfsubcat=&col=developer-forums]
    My thought exactly.
    db

  • How to set different renderers to different cells in same column of JTable?

    Hello Friends,
    I need your help again...
    Does any body knows, how to set different renderer's for different cells of same column in JTable..??
    For ex.
    Col1 Col2 Col3 Col4
    A       A       A      A
    A       A       A      B
    A       A       A      C
    A       A      A       D
    Where A B C D would be different Renderers.  I want set exactly same ,,, ie. one column with different renderer at different cell positions..
    Right now i m setting renderer using statement bellow :
    table.getColumnModel().getColumn(int).setCellRenderer(rederer_Instance);But with this, effect in the last renderer is applicable whole column....
    Can any body help me out ?????????
    please refer this thread for similar kind of discussion...
    http://forums.sun.com/thread.jspa?forumID=57&threadID=571445Thanks
    Suyog

    Please refer to the first reply of [this thread|http://forums.sun.com/thread.jspa?forumID=57&threadID=571445] for the answer. If you have a specific problem implementing it, post you code with a specific question.

  • Add and remove columns from JTable

    Help me please!
    A try to remove column from JTable. It's removed, but when I try to add column in table, then I get all old (removed early) columns + new column....
    I completely confused with it.....
    Here is my code for remove column:
    class DelC implements ActionListener
              public void actionPerformed (ActionEvent e )
                   int [] HowManyColDelete = table.getSelectedColumns();
                   if (HowManyColDelete.length !=0)
                        TableColumnModel tableCModel = table.getColumnModel();
                        for (int i = HowManyColDelete.length-1; i>-1; i--)
                             table.getColumnModel().removeColumn (tableCModel.getColumn (HowManyColDelete [ i ]));
                   else
                          JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Column is not selected!");
         }

    It's little ex for me, I just try understand clearly how it's work (table models i mean). Here is code. All action with tables take place through menu items.
    My brain is boiled, I've try a lot of variants of code, but did't get right result :((
    It's code represent problem, which I've describe above. If you'll try remove column and then add it again, it will be ma-a-a-any colunms...
    I understand, that my code just hide columns, not delete from table model....
    But now I have not any decision of my problem...
    Thanks a lot for any help. :)
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.table.DefaultTableModel;
    class JTableF extends JFrame
         Object [] [] data = new Object [0] [2];
         JTable table;
         DefaultTableModel model;
         String [] columnNames = {"1", "2"};
         TableColumnModel cm;
         JTableF()
              super("Table features");
              setDefaultLookAndFeelDecorated( true );
              setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              JMenuBar MBar = new JMenuBar();
              JMenu [] menus =  {new JMenu("A"), new JMenu("B")};
              JMenuItem [] menu1 =  {new JMenuItem("Add row"), new JMenuItem("Delete row", 'D'),  new JMenuItem("Add column"), new JMenuItem("Delete column")};
              menu1 [ 0 ].addActionListener(new AddL());
              menu1 [ 1 ].addActionListener(new DelL());
              menu1 [ 2 ].addActionListener(new AddC());
              menu1 [ 3 ].addActionListener(new DelC());
              for (int i=0; i<menu1.length; i++)
                   menus [ 0 ].add( menu1 [ i ]);
              for (int i=0; i<menus.length; i++)
                   MBar.add(menus );
              JPanel panel = new JPanel ();
              model = new DefaultTableModel( data, columnNames );
              table = new JTable (model);
              cm = table.getColumnModel();
              panel.add (new JScrollPane(table));
              JButton b = new JButton ("Add row button");
              b.addActionListener(new AddL());
              panel.add (b);
              setJMenuBar (MBar);
              getContentPane().add(panel);
              pack();
              setLocationRelativeTo (null);
              setVisible (true);
         class DelC implements ActionListener
              public void actionPerformed (ActionEvent e )
                   int [] HowManyColDelete = table.getSelectedColumns();
                   if (HowManyColDelete.length !=0)
                        TableColumnModel tableCModel = table.getColumnModel();
                        for (int i = HowManyColDelete.length-1; i>-1; i--)
                             int vizibleCol = table.convertColumnIndexToView(HowManyColDelete [ i ]);
                             tableCModel.removeColumn (tableCModel.getColumn (vizibleCol));
                        //cm = tableCModel;
                   else
                        JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Column is not selected!");
         class AddC implements ActionListener
              public void actionPerformed (ActionEvent e)
                   //table.setColumnModel(cm);
                   Object NewColumnName = new String();
                   NewColumnName = JOptionPane.showInputDialog ("Input new column name", "Here");
                   int i = model.getRowCount();
                   int j = model.getColumnCount();
                   Object [] newData = new Object [ i ];
                   model.addColumn ( NewColumnName, newData);
         class AddL implements ActionListener
              public void actionPerformed (ActionEvent e)
                   int i = model.getColumnCount();
                   Object [] Row = new Object [ i ];
                   model.addRow ( Row );
         class DelL implements ActionListener
              public void actionPerformed (ActionEvent e)
                   int [] HowManyRowsDelete = table.getSelectedRows();
                   if (HowManyRowsDelete.length !=0)
                        for (int k = HowManyRowsDelete.length-1; k>-1; k--)
                             model.removeRow (HowManyRowsDelete[k]);
                   else
                        JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Row is not selected!");
         public static void main (String [] args)
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        JTableF inst = new JTableF();

  • Keyboard Access For a Column in JTable with default editor as JComboBox

    I want to get Key board access for a column in JTable.
    The user should be able to select from a drop down list for the column with default
    editor set as JComboBox.
    Presently,it works fine with mouse,also I am able to focus it with Keyboard using
    ALT+Up keys,but how to make drop down list appear.
    Plz help,it's urgent.
    Thanks in Advance

    Hi,
    In addition to setting DO_SUM = 'X' you need to specify function in H_FTYPE field. It should be set to 'AVG' in your case.
    ls_fielcat-do_sum = 'X'.
    ls_fieldcat-h_ftype = 'AVG.

  • Serial number column in Jtable

    Apologies for this distraction.
    I read at this forum about a year ago how to add a s/n column in Jtable such that all the nos are automatically updated/adjusted when a row is added/deleted. the count starts from the top down serially and unaffected by sorting.
    pls help!

    thanks a million BaltimoreJohn and especially camickr whose solutions to problems have been most helpful. applying the referenced post, i worked around the problem by resetting the values of the column having the serial number, based on table rowCount every time there is an operation on it(deleting, addition etc)

  • Problem with Hiding Columns in JTable

    Hi.
    Who knows how to hide column in JTable.
    I try to get column:
    MyTab.getColumnModel().getColumn(i)But there is no methods like SetVisible(false)
    What to DO???

    http://www.google.com/search?hl=en&q=%2Bhide+%2Bcolumn+%2Bjtable&btnG=Google+Search

  • Programmatically Sorting columns in JTable

    Hi,
    How can I programmatically sort a particular column in JTable without having to click on column header.
    Thanks.

    to sort the desired column w/o click on header
    int columnIndexToSort = 1;
    RowSorter.SortKey sortKey = new RowSorter.SortKey(columnIndexToSort,SortOrder.ASCENDING);
    ArrayList alist = new ArrayList(1);
    alist.add(sortKey);
    ((DefaultRowSorter)table.getRowSorter()).setSortable(columnIndexToSort , true);
    ((DefaultRowSorter)table.getRowSorter()).setSortKeys(alist);
    ((DefaultRowSorter)table.getRowSorter()).sort();expecting dukestars..

  • Freezing columns in JTable....  -  Need Suggestions!!!!!!!!!

    Hai Friends,
    i need suggestions for the following,
    How to freeze the columns in swing JTable.?????????????
    I need to freeze 3 columns in JTable... how it can be done?
    eg: its like the option used in excel for freezing the panes. like that, i need to freeze the column in JTable. so that, it wont be scrolled while scrolling the records, it should also be done in colmns of jtable for horizontal scroll n row for vertical scroll. is this can be done in JTable. Can u pls help me out in this...?
    Regards,
    Ciya.

    Did you actually try the code which was pointed out to you when you [url http://forum.java.sun.com/thread.jspa?threadID=701198]asked this question before? It does just what you want...

  • Hidden Columns in JTable

    I wont to hide a elected column in JTable.
    how it to do

    TableColumnModel tcm = table.getColumnModel();
    TableColumn column = tcm.getColumn( modelIndex );
    tcm.removeColumn( column );
    Next time, search the forum first. There are at least a dozen posts asking this question.

  • Show/hide a column  in JTable

    I want to show/hide columns in JTable
    How is this possible
    Note that columns that are hidden may be showed later
    thanks in advance
    Renjith

    I tried out for this:TableColumn col = jTable.getColumnModel().getColumn( colnum );
    if( col != null )
      col.setPreferredWidth( 0 );
      col.setMaxWidth( 0 );
    }But the column seems to have minimum width which you can't even change with col.setMinWidth( 0 );

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

  • To setup scrollbars for individual columns in JTable

    Hi,
    I need to setup individual scrollbars for the
    columns in JTable.
    Can anybody help?
    Thanks in advance.
    Rgds,
    sita

    Hi,
    I need to setup individual scrollbars for the
    columns in JTable.If i understand you correctly, you want to have a scrollbar for every column. If so, you will need a new instance of JTable and JScrollPane for every column, but that's a lot of work if you want to do it fancy.
    The good news, is you can reuse the table model.
    You could do something like that.
    for (int i= 0; i < model.getColumnCount(); i++) {
        JTable table = new JTable();
        table.setAutoCreateColumnsFromModel(false);
       //container
        someContainer.add(new ScrollPane(table), null/* or some layout constrains*/);
        TableColumn tc = new TableColumn(i, 120);
        tc.setHeaderValue(model.getColumnName(i));
        table.addColumn(tc);
    Can anybody help?
    Thanks in advance.
    Rgds,
    sita

  • Scroll Fix Column in JTable

    I have see a lots of examples of whow to create fix column into JTable.
    But all the examples have the same problems.
    When I wont to scroll over the fix column the vertical scroll bar of the no fix column dont move, so the no fix column dose not move and the fix columns and no fix columns aren?t alined.
    If sameone have same example, send it please !!!!
    Thanks !!!
    Pablo

    In a recent project I've had the same problem.
    After a long research at the Swing forum at java.sun.org and google I found out that
    1. Currently there is no proper Open Source solution
    2. All the postings at sun are good concepts, but far away from solutions
    3. The only (for me )acceptable commercial solution is the JCTable from Quest (formerly KGroup)
    Since I want to have full control over the source code of the table, I decided to collect all the tips from this forums and write my own table.
    Here is a first try:
    http://jroller.com/resources/kriede/CoolTable.java
    The main idea is to have two tables, one for the locked columns (= fixed columns = frozen columns) and one for the scrollable columns. With all the tips from this forum it was more or less a puzzle to make it work pretty.

  • How can i make hidden column in JTable

    hi, how can i make hidden column in JTable,
    basically i have a ID field in JTable, i have to use this ID , but i also dont want to show this ID in JTable.
    any idea how ??

    staiji its not working
    i did this :
    first :
    TableColumnModel columnModel =
    usersTable.getColumnModel();TableColumn column =
    columnModel.getColumn(1);
    usersTable.removeColumn(column);
    then when i trying to get this :
    Integer userId =
    (Integer)usersTable.getValueAt(UserBrowser.this.usersTa
    le.getSelectedRow(), 0);
    it not give me ID column's value .
    i have a column in JTable like :
    ID | Username | First name | Last name
    i want to hide ID column , but get this ID's value
    when user clicks on JTable row.Hi, if you would read the documentation about JTable.getValueAt(...) you will find, that there is a significant difference between this method and the datamodels getValueAt(...) method. JTables getValueAt(...) method interprets column-index as index in its TableColumnModel - in your TableColumnModel there is no column any longer that holds ID values, therefore you were not able to get it by JTable.getValueAt(...). Do not use these methods for the purpose you want it for - you will also get the wrong values, if the user has repositioned columns - the column index is always interpreted as index in the currently used TableColumnModel and IS NOT A MODELINDEX.
    greetings Marsian

Maybe you are looking for

  • Internal 3TB Cavier Green WD Hard Disk not detect on mac but detected on Windows (Parallels

    I bought a 3TB Cavier Green Western Digital and I have a Astone external 3.5 case. I attached both of this together and hook up USB to my Mac mini. It seems like my Disk Utility doesn't detect my 3TB at all, at first I thought my hard drive has a pro

  • Using Decode Or Case Statement / Any Method

    Dear All, In my table Fields are EmpId TranYear TranMonth ApprovedBy ApprovedYear ApprovedMonth My Input parameters are 1. TranYear 2. TranMonth 3. Tag1 4. Tag2 My requirement is Tag1 Input are 0,1,2 Tag2 Inputs are 0,1,2 If Tag1 is 0 then checking T

  • Problem with finding Cd Information with Itunes

    I am using ITunes 7.3.2 and every time I insert some cds I recently bought from Best Buy, ITunes is unable to locate the Cd Information online even though I am cearly connected to the internet and Gracenote is not down. I even tried putting in cds th

  • Access Sequnce in Partner Function

    Hi We are using same transaction types for 3 different types of service orders functionality. Service order, Copy Service Order, Follow up service Order, we are defined partner function with below category, Client, Alternative Requester, Employee Res

  • Find feature Highlight Color and End of document alert

    I am using Version 2.0.7 and noticed two problems with the text find feature that I hope someone else knows about a configuration setting or work around that will resolve the problems. Thanks, Problem 1. Found search characters are highlighted in gra