JTable column resize listener

Hi friends !
I want to trap the event when user resizes the width of any column. Which listener will help me for this.
Thanks in advance.

Thanks a lot camickr !!
It worked fine !! I did it like this
table.getColumnModel().addColumnModelListener(new TableColumnModelListener(){
     public void columnMarginChanged(ChangeEvent e)
               // Your code goes here..     
     public void columnSelectionChanged(ListSelectionEvent e){}
     public void columnAdded(TableColumnModelEvent e){}
     public void columnMoved(TableColumnModelEvent e){}
     public void columnRemoved(TableColumnModelEvent e){}
});Thanks a lot again !!

Similar Messages

  • Jtable column resize

    Hi all!
    i'm using:
    to resize jtable column width but it's not working, do you know what can be happening?

    All you've done is say what size you would prefer.
    You then have to force the component to repaint, with something like
                jTable1.repaint();Ps. I posted a nice utility class to automaticaly fit the JTable columns to the exact size required here.

  • JTable column resize dilemma?

    I have a JTable instance jTable resides in a JScrollPane that loads data from a file. However the horizontal scroll bar does not come out even if there are way too many columns. I searched online and find out I have to do this:
    Now I have another problem. Every column are the same size, even if some column clearly have longer string.
    Sure I can write an algorithm calculating suitable column width, but, is there a better way? I mean JTable's auto resizing algorithm clearly know which column should be wider but it is just a little stupid for trying to squeeze everything in a tiny space even though there is a horizontal scroll bar...
    Can't we let the JTable figure out the right width without the width constraint?

    Can't we let the JTable figure out the right width without the width constraint?There are solutions in the forum for dynamically determining the width of a column.

  • Resize JTable Columns without Column Header

    Hi all.
    I have a JTable that doesn't display a column header.
    I would like to allow the user to resize the columns by dragging a mouse at the column edges at any point down the table.
    It is not obvious how I can accomplish this.
    Does anyone have any ideas?
    Thanks, Paul.

    That doesn't work, though, since the table has its own listenersIt's not just that. The header's mouse listeners work with instance fields of BasicTableHeaderUI and detection (using e.getPoint) of the header cell and column.
    I would start with copying the entire code of BasicTableHeaderUI to a class of my own, then first eliminate anything that obviously isn't related to column dragging/resizing, then refactor, refactor, refactor to make the listener codes work with a table instead of a header. But like I said, easier said than done, particularly when having to deal with the various JTable column resize modes.

  • JTable:  resizing all columns as 1 column resizes

    I have a JTable with 480 columns inside of a JScrollPane (AUTO_RESIZE_ALL_COLUMNS needs to be off for the JTABLE to display correctly in the JScrollPane). When the user resizes one column I would like the rest of the columns to resize too, so that the column widths of each column are equal.
    Thank you in advance,

    [...] I
    I have the JScrollPane listening to a histogram of the
    balances so the user can click on a month in the
    histogram and the JScrollPane (actually JViewport)
    will move to display the appropriate column in the
    JTable. If the column sizes are not uniform then I
    cannot be sure that I'm moving the JViewport to
    display the correct JTable column(s).
    I thing the GUI is a great design for what must be
    done. And thank you for your help and comments.That still sounds pretty klunky. I don't see any user navigating around a 480 column table. They click in your histogram to go to a column, they click somewhere or do keyboard navigation and the display scrolls them a few columns/rows away... they are now lost in a sea of cells and have to go back to the histogram again to try and get back, etc. Having delt with similar situations, there are better ways. Read the last two days dilbert cartoons carefully. :-)
    But anyway...
    You don't have to have all the columns the same width to make a column visible in the viewport. You can just get the appropriate column's rect by either of these methods:Rectangle r = myTable.getTableHeader().getHeaderRect( col );
    Rectangle r = myTable.getCellRect( row, col, true );And then tell the viewport to make sure that rect is visible:myViewport.scrollRectToVisible( r );Much easier than hacking around with custom column resizing logic.

  • JTable in JPanel last Column resize clips JTable doesnt repaint JPanel

    I have a JTable in a JPanel, when I drag the last column of the JTableHeader (u can see the column resizing as the text of the Table HeaderColumn moves with the drag) the JTable is outside the JPanel. Only when u click on another component and then click back on the JTableHeader does it repaint.
    I have tried jPanel.revalidate(); in the mouseDragged event of MouseMotionListener on the JTableHeader and all manner or repaints and fireTableStructureChanged. But I dont understand the order of events.
    The last bug to fix!!!
    NB I dont want to use scrollpane as its not necessary and as many tables are synchronized with one table it makes repaints less smooth
    Thanks Paul

    Well, I didn't find an answer but I did find a solution.
    The JPanel is the problem. I use it to help with layout which is not obvious in this example.
    As you can see in the code the JTable is placed in a JScrollPane which is place in a JPanel which is placed in a JTabbedPane.
    If I use Box instead of JPanel the JTable in the JScrollPane in the Box in the TabbedPane in the JFrame resizes correclty.
    So although JPanel is resizable with setSize it does not get resized when it's JFrame gets resized.
    I would still like to know why?
    JTabbedPane myTP = new JTabbedPane();
    Box myOne = Box.createHorizontalBox();
    Box myTwo = Box.createHorizontalBox();
    myTP.add("One", myOne);
    myTP.add("Two", myTwo);

  • Resize JTable columns by double-clicking header

    I want to implement column resizing in a JTable so that when the user double clicks on the column header with the mouse in the "resize zone" the column automatically adjusts to the width of the longest text in the column. this is how many applications behave (e.g. windows explorer) but I don't think I've ever seen a swing app that does this. I've looked in the API docs for JTable and JTableHeader and I can't see any way of finding out if the mouse is over the edge of a column header. does anyone know of a way to do this?

    Is this laf independant?import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test extends JFrame {
      public Test() {
        Container content = getContentPane();
        String[] head = {"One","Two","Three"};
        String[][] data = {{"R1-C1","R1-C2","R1-C3"},
        JTable jt = new JTable(data, head);
        JScrollPane jsp = new JScrollPane(jt);
        content.add(jsp, BorderLayout.CENTER);
        JTableHeader jth = jt.getTableHeader();
        jth.addMouseListener(new MouseAdapter() {
          public void mouseClicked(MouseEvent me) {
            JTableHeader jth = (JTableHeader)me.getSource();
            int col = jth.columnAtPoint(me.getPoint());
            Rectangle r = jth.getHeaderRect(col);
            if (jth.getCursor().equals(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR))) {
              System.out.println("Cursor, col="+col);
        setSize(300, 300);
      public static void main(String args[]) { new Test(); }

  • What method should be used for resizing the particular JTable Column width

    I have a four table. Only one table which are on top have a table header. I want that when user resize the topmost table with a mouse other table colume also be resized automatically. So I want to know that what method should be used for resizing the particular JTable Column width.

    maybe you can implement a interface ComponentListener as well as ComponentAdapter with your topmost Table.
    for example:
    new ComponentAdapter(){
    public void componentResized(ComponentEvent e){
    /*Optionally, you must also call function revalidate

  • User cannot resize jTables� columns

    Using NetBeans IDE 3.5.1, I built a jTable, controlled by a
    My problem is that the user cannot resize the jTables� columns.
    Maximum details:
    1.     jtablewidth is set to a fixed value according to internal data:
    JTable1.setPreferredSize( new Dimension(tableWidth, i_TableHeight));
    2.     columnwidth is set according to internal data:
    Col = JTable1.getColumnModel().getColumn(i);
    3.     jTable header details:
    JTableHeader anHeader = JTable1.getTableHeader();
    4.     JTable1.getTableHeader().setResizingAllowed(true);.
    5.     Initial declerations:
    a.     JTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    java.awt.Dimension(650, 500));
         JTable1.setPreferredSize(new java.awt.Dimension(1200, 409));
    b.     JScrollPane1.setMaximumSize(new java.awt.Dimension(750, 412));
         JScrollPane1.setPreferredSize(new java.awt.Dimension(750,
    c.     Jtable.autoCreateColumnsFromModel (true);
    Thanks alot,

    Columns resizing works by default. You don't need to do anything special.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • How to resizea JTable column to fit to text programatically?

    hi evreyone,
    i'm trying to resize a JTable column width to fit to the contained text programatically.my approach was that i made a comparison between the length of String objects contained in my column and got the biggest String length value but i want to know how can i resize the column to fit to this biggest String object

    You're going the wrong way about it - don't go calculating string lengths. Get the TableCellRenderer, query it for the renderer component for each cell in the column, obtain its preferred size and keep a record of the greatest width value.

  • Updating JTable Column in real time

    I have a JTable which has listener listens for a specific event and updates the corresponding column accordingly in real time. This works fine. One small problems though, the user could actually see the redrawing of the JTable sometimes. Most of time, it went so fast, they don't see it, sometimes, user could see it. Why is it?


  • JTable Header resizing codes ?

    Does anyone have reusable codes that can accept the column names then resize the JTable columns automatically. By using the column names width the table headers are automatically computed to column preferred size.

    Please refer to http://www2.gol.com/users/tame/swing/examples/SwingExamples.html for a possible solution.

  • JTable column auto-maximum width

    Does anyone have an idea on how to make the JTable to support column auto-maximum width resize, like we always see in a microsoft's table component, you double click on the column seperater and the column resized to its maximum size according to the content in it.

    Hi again,
    I wrote two methods to solve this kind of problem... take a look at them and tell me what you think about it...
       /** Adjusts the widths of a JTable columns
        * @param  table    the table
       public static void resizeTableColumns(JTable table) {
          TableColumn c = null;
          FontMetrics fm = table.getFontMetrics(table.getFont());
          for (int i=0; i<table.getColumnCount(); i++) {
             c = table.getColumn(table.getColumnName(i));
             c.setPreferredWidth(determineColumnWidth(c, table.getModel(), fm));
       /** Returns the preferred width of a JTable column. The resulting width
        * is 5 pixels wider than the biggest column
        * @param  col    the column
        * @param  model  the table model
        * @param  fm     the font metrics
        public static int determineColumnWidth(TableColumn col, TableModel model,
                                              FontMetrics fm) {
          String value = (String)col.getHeaderValue();
          int headerWidth = fm.stringWidth("." + value.trim() + ".");
          int columnNumber = col.getModelIndex();
          int max = headerWidth;
          int columnWidth = 0;
          int nrows = model.getRowCount();
          String cell = "";
          for (int i=0; i<nrows; i++) {
             value = (String)model.getValueAt(i, columnNumber);
             columnWidth = fm.stringWidth("." + value.trim() + ".");
             if (columnWidth > max) max = columnWidth;
          return max + 5;

  • Can Jtable column preferences be preserved?

    I re-ordered my JTable columns and removed/added a few. However, this gets overwritten as soon as I perform another search. Can column preferences be preserved for for a particular user?

    You can register a TableColumnModelListener with your tables TableColumnModel and save the changes to a file in the users home directory.
    When restoring you can change the tables TableColumnModel using the stored values (before registering the Listener).

  • JTable Column Resizig Event

    Can anyone tell the event that is fired when the column of a jtable is resized

    This is just a guess
    I have not tried it out
    Try addPropertyChangeListener() of class javax.swing.table.TableColumn
    and in that as the size changes for that write appropriate code

Maybe you are looking for

  • Get Old Value and the new value based on the date


  • Assigning existing G/L account to another company code

    I have been asked to assign an existing G/L account, which belongs to Company code A to another Company code B. G/L account is created at Chart of accounts level. Is there a way to do it without having to create the G/L account again for Company code

  • Forgot password - alternative reset mechanisms

    Hey everyone, One of my clients is acknowledges that his users won't answer the authentication questions, and even if they do, they won't remember the answers. He's looking for a way to send them a random link (that expires after a while, say 24 hour

  • Strage shortcut win+space , cs6 and cc

    hi i found a strange shortcut i load a 5d mark 2 image , and i zoom in 100% after i selected the hand tool i kept the windows key down+left mouse click it's weird , it display a rectangle and zoom in different place of the image might you please chec

  • No such metric, emagent.trc errors

    Hi *, i need some help with the following problem. In Enterprise Manager DB Console i get the error "no such metric" and emagent.trc shows error messages like this. Thread-140 ERROR fetchlets: Could not load library '/opt/lib/oracle/app/product/10gr2