Moving columns in a JTable

I'm having a problem with moving of columns by dragging the table header. The table header value moves but the information in the table cells below remain where they were. Has anyone come across anything like this before?
Could it be something to do with the way my tablemodel interacts with my tablesorter?

Cheers Richard,
I'm using TableSorter which is part of the TableSorterDemo in How To Use Tables in the Sun Java tutorial if you want to look - it works fine within the demo. I'm afraid I'm fairly new to java so I'm not sure where to look for the problem. I think I'll try using the default tablemodel, see if that works and then add stuff until it all goes wrong again! Is this sensible? Any more ideas?
Thomas

Similar Messages

  • How to forbid to moving columns in a JTable

    Hi together,
    i have one simple question. How can i forbid, that columns can be moved in my Jtable?
    If anyone can help or may has a useful link, i would be glad.
    thanks
    BackUP

    Hi,yourTable.getTableHeader() .setReorderingAllowed(false);

  • Moving columns in JTable

    hi all
    i'm having a slight problem after i've moved a column within my JTable, i need to reallocate the column index numbers. i'm using a sorter for the data, so when i move a column and select another column (or that one) it sorts a different column to the one selected based on the original (pre-move) indexes ( i do hope that makes some sense).
    i have a mouseDragged listener which works fine when moving a column, i just now need to add the index changes for all columns to it but i keep coming up with very very bad code that doesn't work.
    any suggestions would be most appreciated.
    thanks heaps...
    Takis

    i've actually been fiddling with those and that is actually where my problem lies.
    i use the following:
    int viewColumn = columnModel.getColumnIndexAtX(e.getX());
    int column = tableView.convertColumnIndexToModel(viewColumn);
    the sorter then works on "column".
    problem is, that when the column is moved, the viewColumn changes, but the column value remains the same. i've also tried sorting on the view column but then it gets even more confused.
    i just can't seem to figure it out...
    Takis

  • How to disable moving Columns in JTable

    Hi,
    How can I make sure that the columns in my JTable cannot be moved?
    Any ideas?
    thanks

    How about:myTable.getTableHeader().setReorderingAllowed(false);

  • 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

  • Giving names to the columns in a JTable

    Hi,
    I am using JTable(int numRows, int numColumns) constructor to create a JTable. After I built my application I came to knw that I cannot change the column names. The JTable in my GUI will keep on changing and the no. of rows,columns and even the column names may also change. I just wanted to know what constructor I should shift to.
    Thanks,
    Adhiraj

    I would use something like the following:
    DefaultTableModel model = new DefaultTableModel(columnNames, rowCount);
    JTable table = new JTable( model );
    The following code gives some examples on using the DefaultTableModel to add rows and columns:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableRowColumn extends JFrame
         private final static String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         JTable table;
         DefaultTableModel model;
         JPanel buttonPanel;
         JButton button;
         public TableRowColumn()
              //  Create table
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"} };
              String[] columnNames = {"Number","Letter"};
              model = new DefaultTableModel(data, columnNames);
              table = new JTable(model);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              //  Add table and a Button panel to the frame
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              buttonPanel = new JPanel();
              getContentPane().add( buttonPanel, BorderLayout.SOUTH );
              button = new JButton( "Add Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        model.addRow( createRow() );
                        int row = table.getRowCount() - 1;
                        table.changeSelection(row, 0, false, false);
                        table.requestFocusInWindow();
              button = new JButton( "Insert Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        model.insertRow( 0, createRow() );
                        table.changeSelection(0, 0, false, false);
                        table.requestFocusInWindow();
              button = new JButton( "Empty Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        model.setRowCount( model.getRowCount() + 1 );
                        int row = table.getRowCount() - 1;
                        table.changeSelection(row, 0, false, false);
                        table.requestFocusInWindow();
              button = new JButton( "Add Column" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        String header = "Col" + (table.getColumnCount() + 1);
                        model.addColumn( header );
                        table.requestFocusInWindow();
              button = new JButton( "Add Column & Data" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        String header = "Col" + (table.getColumnCount() + 1);
                        int rows = table.getRowCount();
                        String[] values = new String[rows];
                        for (int j = 0; j < rows; j++)
                             values[j] = Integer.toString(j);
                        model.addColumn( header, values );
                        table.requestFocusInWindow();
              button = new JButton( "Add Column - No Reordering" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        //  Use this method when you don't want existing columns
                        //  to be rebuilt from the model.
                        //  (ie. moved columns will not be reordered)
                        table.setAutoCreateColumnsFromModel( false );
                        String header = "Col" + (table.getColumnCount() + 1);
                        model.addColumn( header );
                        //  AutoCreate is turned off so create table column here
                        TableColumn column = new TableColumn( table.getColumnCount() );
                        column.setHeaderValue( header );
                        table.addColumn( column );
                        // These won't work once setAutoCreate... has been set to false
                        buttonPanel.getComponent(3).setEnabled( false );
                        buttonPanel.getComponent(4).setEnabled( false );
                        table.requestFocusInWindow();
              button = new JButton( "Remove Last Column" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        int columns = model.getColumnCount();
                        if (columns > 0)
                             if (!table.getAutoCreateColumnsFromModel())
                                  int view =
                                       table.convertColumnIndexToView(columns - 1);
                                  TableColumn column =
                                       table.getColumnModel().getColumn(view);
                                  table.getColumnModel().removeColumn( column );
                             model.setColumnCount(columns - 1);
                        table.requestFocusInWindow();
         private Object[] createRow()
              Object[] newRow = new Object[2];
              int row = table.getRowCount() + 1;
              newRow[0] = Integer.toString( row );
              newRow[1] = LETTERS.substring(row-1, row);
              return newRow;
         public static void main(String[] args)
              TableRowColumn frame = new TableRowColumn();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

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

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

  • Adding mouse listener to the column header of a column in a JTable

    Hi
    I want to add a mouse listener to the column header of the 3rd column in a JTable. I dont find any appropriate method to do this. The code I have written to do this is below. But on using this code, the mouselistener is invoked if I click on any column header. Can anyone please help me to fix this.
    table.getTableHeader().addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    /* some actions */
    }

          table.getTableHeader().addMouseListener(new MouseAdapter(){
               public void mousePressed(MouseEvent me) {
                   int tableColumn  =table.columnAtPoint(me.getPoint());//it returns the column index
            });

  • How to programmatically select a column in a JTable

    Hi,
    I'm writing a program which requires me to select a column in the JTable through code. The problem is that I could only find getSelectedColumn() function in JTable and no setSelectedColumn().
    Please let me know if there is any workaround for this.
    Regards,
    Derreck

    Hi,
    table.setColumnselectionInterval(index0,index1);
    The above line will suffice your requirement.
    Cheers,
    Gokul.

Maybe you are looking for

  • There was an error processing a page. a number is out of range.

    When I open a PDF generated from a classic ASP application, some particular documents fail when accessing a page: there was an error processing a page. a number is out of range. This only happens in Adobe Reader 10 and 11. The ASP page has a code sim

  • Cant open itunes on my pc

    I cant seem to open itunes on my windows based PC. When I link on the desktop icon it simply circle whirls and then does nothing. this means I cant back up info on my PC which i prefer to do rather than using the cloud. What do i need to do?

  • Itunes stopped working on my windows 7 laptop

    my itunes stopped working on the windows 7 PC. i am now unable to sync my ipad!

  • Generally when does optimizer use nested loop and Hash joins  ?

    Version: 11.2.0.3, 10.2 Lets say I have a table called ORDER and ORDER_DETAIL. ORDER_DETAIL is the child table of ORDERS . This is what I understand about Nested Loop: When we join ORDER AND ORDER_DETAIL tables oracle will form a 'nested loop' in whi

  • MacBook won't boot up

    My MacBook takes about 7 mins to start up and when it does all I see is my background  and cursor and that's it, if it try click the cursor turns into the spinning rainbow and that's as far as she goes, help please, I started it up in recovery but my