Dragging columns in a JTable

how to drag columns in a JTable ?

JTable myTable = new JTable(mymodel,myheaders);
JTableHeader head =myTable.getTableHeader();
//// this function will solve your problem
head.setReorderingAllowed(true);

Similar Messages

  • Dragging columns in JTable

    I am dragging a JTable column with my mouse. If I release the column, will an event be fired indicating that the column was dragged AND is now being released??
    The mouseReleased(MouseEvent e) in MouseListener() will just inform me of the release of the mouse button, it will not inform me whether this release of the mouse button has induced the release of a dragged column.
    The columnMoved(TableColumnModelEvent e) in TableColumnModelListener() will give me the coordinates of a column WHILE it is being dragged. It will not inform me if a column gets released.
    If no specific event exist to indicate the release of a dragged column, I guess I'll try to obtain the same result by combining both the mouseReleased method and the columnMoved method.
    Thanks in advance.
    Olivier

    try attaching MouseMotionListener as well as MouseListener to the table header. when mouse drag starts, make a boolean variable, say dragged true, and then in mouseReleased() method, check if dragged is true or not. if true, it'll meet your both the requirements.
    add this code to your code.
    private boolean dragged = false;
    private void addDragListener(JTable tableObj) {
         final JTable table = tableObj;
         MouseMotionAdapter motionListener = new MouseMotionAdapter() {
              public void mouseDragged(MouseEvent me) {
                   dragged = true;
                   TableColumnModel columnModel = table.getColumnModel();
    int viewColumn = columnModel.getColumnIndexAtX(me.getX());
    int column = table.convertColumnIndexToModel(viewColumn);
                   System.out.println("column " + column +" dragged");
         MouseAdapter mouseListener = new MouseAdapter() {
              public void mouseReleased(MouseEvent me) {
                        if(dragged) {
                             System.out.println("column released after dragging");
                             dragged = false;
         JTableHeader th = table.getTableHeader();
         th.addMouseMotionListener(motionListener);
         th.addMouseListener(mouseListener);
    hope this helps,

  • Can i stop the columns in a JTable from re-ordering?

    Hi,
    As we know, JTable by default allows re-ordering of the columns within it.
    I mean to say that the columns in a JTable can be interchanged, by drag and drop utility.
    I want to refrain my JTable from doing so.
    Can someone please suggest me how can i do this?
    Thanx in advance :)
    Regards,
    Archana

    Thank you :)
    This did solve my problem of columns getting re-ordered in my JTable.
    But i am facing one more problem now :(
    I sort my JTable by clicking on the JTableHeader.
    Clicking on the column header of any one of the columns of the JTable, sorts all entries in either ascending or descending order.
    This is not happening.:(
    Can someone please help me out?
    Thanx in advance :)
    Regards,
    Archana

  • 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

  • Resize column width for JTable without column headers?

    Hi,
    I find that for me to resize columns of a JTable by using
    mouse dragging, I MUST have column headers and then drag
    column headers to resize them. Is my understanding correct?
    Actually, I need to have a table without header columns.
    How can I use mouse to resize column width by dragging?
    The background for this request is that I am putting a
    complex table as another table's column header and I hope to
    be able to resizing the complex table by mouse dragging.
    Thanks very much,
    David

    Hi,
    I think you have mistake there. Try
    <style type="text/css">
    table.apexir_WORKSHEET_DATA td {
    white-space:nowrap !important;
    td[headers="DESCR"] {
    width:300px !important;
    max-width:300px !important;
    #apexir_DESCR {
    width:10px;
    max-width:300px !important;
    </style>And you can try add
    table.apexir_WORKSHEET_DATA {
    width: 100% !important;
    table-layout: fixed !important;
    }Regards,
    Jari
    My Blog: http://dbswh.webhop.net/htmldb/f?p=BLOG:HOME:0
    Twitter: http://www.twitter.com/jariolai

  • Resizing & dont drag column

    How to do to a column in a Jtable cant drag and drop in a other column position.
    And i need that these columns arent resizable.
    Thanks

    The methods you seek are found in the JTableHeader class.

  • 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

  • Drag and Drop in JTable never gets DropTargetListener events

    I'm trying to implement Drag/Drop between two JTables. I have adapted the source from the Drag/Drop Tutorial but none of the DropTargetListener events get called. When I try to drag a row from one table to the other, the debug output is as follows:
    beginning drag : ROW 3
    dragsource : dragExit
    dragsource : dragDropEnd
    I'm using JDK 1.3. Any help would be appreciated, here is the source:
    public class DnDTable extends JTable implements DropTargetListener, DragSourceListener, DragGestureListener
    public DnDTable(Object[][] rowData,Object[] columnNames)
    super(rowData,columnNames);
    m_dropTarget = new DropTarget(this,this);
    m_dragSource = new DragSource();
    m_dragSource.createDefaultDragGestureRecognizer(this,DnDConstants.ACTION_MOVE,this);
    public void dragEnter(DropTargetDragEvent event)
    System.out.println("droptarget : dragEnter");
    event.acceptDrag(DnDConstants.ACTION_MOVE);
    public void dragExit(DropTargetEvent event)
    System.out.println("droptarget : dragExit");
    public void dragOver(DropTargetDragEvent event)
    System.out.println("droptarget : dragOver");
    public void drop(DropTargetDropEvent event)
    System.out.println("droptarget : drop");
    try
    Transferable transferable = event.getTransferable();
    // we accept only Strings
    if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor))
    event.acceptDrop(DnDConstants.ACTION_MOVE);
    String s = (String)transferable.getTransferData(DataFlavor.stringFlavor);
    setValueAt(s,rowAtPoint(event.getLocation()),0);
    event.getDropTargetContext().dropComplete(true);
    else
    event.rejectDrop();
    catch(IOException exception)
    exception.printStackTrace();
    System.err.println( "Exception" + exception.getMessage());
    event.rejectDrop();
    catch(UnsupportedFlavorException ufException )
    ufException.printStackTrace();
    System.err.println( "Exception" + ufException.getMessage());
    event.rejectDrop();
    public void dropActionChanged(DropTargetDragEvent e)
    public void dragGestureRecognized(DragGestureEvent event)
    int nDragRow;
    Object object;
    nDragRow = getSelectedRow();
    object = getValueAt(nDragRow,0);
    if (object != null )
    System.out.println("beginning drag:" + object.toString());
    StringSelection text = new StringSelection(object.toString());
    m_dragSource.startDrag(event,DragSource.DefaultMoveDrop,text,this);
    else
    System.out.println("nothing was selected");
    public void dragDropEnd(DragSourceDropEvent event)
    System.out.println("dragsource : dragDropEnd");
    public void dragEnter(DragSourceDragEvent event)
    System.out.println("dragsource : dragEnter");
    public void dragExit(DragSourceEvent event)
    System.out.println("dragsource : dragExit");
    public void dragOver(DragSourceDragEvent event)
    System.out.println("dragsource : dragOver");
    public void dropActionChanged(DragSourceDragEvent event)
    System.out.println("dragsource : dropActionChanged");
    DropTarget m_dropTarget;
    DragSource m_dragSource;

    Hi My friend,
    The code you have took will perfectly works.
    I have an option please try this.
    Instead of DnDConstants.ACTION_MOVE try DnDConstants.ACTION_COPY.
    Lakshmi.

  • 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