Resize jtable column width

I am trying implement a utility in JTable by which when a person clicks on the column header, the whole column should resize according to the cell which has lengthiest data. If you have seen this in MS Excel where by clicking on the column this happens. I want the same thing.
Is there anyway already defined in javax.swing?
I have added a Mouselistener on Tableheader and when the person clicks on a column header, I first finds out the column index. Now on that column index scan the whole column for the lengthiest data. After finding the lengthiest data I set the preferred width for that column and call doLayout on the table object. In this case the problem is of font as the font is not fixed width. The multiplication factor which returns the pixel doesn't gives the right pixel width. Is there any way by which I can find pixel width of a String?

Use the following code to compute the width of a
column in pixels required to display the maximum sized
string in the table column:
FontMetrics fm =
table.getFontMetrics(table.getFont());
int width =
SwingUtilities.computeStringWidth(fm,maxSizeString)
//then to set the width of your column:
TableColumnModel columnModel =
table.getColumnModel();
TableColumn column =
columnModel.getColumn(YOUR_COLUMN);
column.setPreferredWidth(width);Rizwanthx that was usefull

Similar Messages

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

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

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

  • 1. Resizing of column width. 2. Drag and drop of columns for resequencing

    QUERY : Has anyone some experience in implementation/development of following functionality in a JSP/Tomcat server based application:
    1. Resizing of column width for a result which has multiple columns. .2. Drag and drop of these columns or any other mechanism for re-sequencing the columns?
    I would like to know will JSF would be helpful in it.

    Amit,
    The column resizing and 'drag and drop ' are client side issues. They requires DHTML and Javascript.
    AJAX is what is required. (wiki AJAX for more info)
    I am working on an AJAX grid and combobox component for JSF that will do this and many more functions.
    Let me know if you want more information.
    [email protected]

  • JTable resizing the column width

    Have a JTable whose column width's are set using
    int width = ((String)getDataTbl().getColumnModel().getColumn(0).getHeaderValue()).length() + 32;
    getDataTbl().getColumnModel().getColumn(0).setPreferredWidth(width);
    int width1 = ((String)getDataTbl().getColumnModel().getColumn(1).getHeaderValue()).length()+207
    getDataTbl().getColumnModel().getColumn(1).setPreferredWidth(width1);
    Now depending on the data in column 1 the column width has to be increased if more than width1 and the scroll bar should apprear only in this case only?
    How to do this?
    Thanks.

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

  • JTable column widths - help

    Hi,
    I have a JTable and I am having problems with the column widths. Currently, I place my JTable in a JScrollPane, and that's it. What I want is this:
    1. When the table is initially displayed, I want all the columns to be of equal width and use the entire width of the table (so no empty space at the end of the table)
    2. When I resize a column I want the other columns to maintain their size, and just have the scroll bars appear.
    3. When I resize the frame/browser that my app is running in, I want the scroll bars to appear.
    I tried the different autoResizeModes but I cant get the entire result which I need..any suggestions? Below is a code example...
    import java.awt.BorderLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class Test1 extends JPanel {
         JScrollPane scroller;
         JTable table;
         String[][] rowData = new String[][] {
                   {"John", "18"},
                   {"Bill", "20"},
                   {"Alex", "17"}
         String[] columns = new String[] {
              "Name", "Age"     
         public Test1() {
              table = new JTable(rowData, columns);
              scroller = new JScrollPane(table);
              setLayout(new BorderLayout());
              add(scroller, BorderLayout.CENTER);
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Test1 t = new Test1();
              f.getContentPane().add(t);
              f.setSize(600, 600);
              f.setVisible(true);
    }

    Forget about my last post. The following code works but I guess you'll have to work on it to make it more elegant.import java.awt.BorderLayout;
    import javax.swing.*;
    public class Test1 extends JPanel {
         String[][] rowData = new String[][]{{"John", "18"}, {"Bill", "20"}, {"Alex", "17"}};
         String[] columns = new String[]{"Name", "Age"};
         JTable table;
         JScrollPane scrollPane;
         public Test1() {
              super(new BorderLayout());
              table = new JTable(rowData, columns);
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              scrollPane = new JScrollPane(table);
              add(scrollPane, BorderLayout.CENTER);
         public void pack() {
              System.out.println("pack");
              int columnCount = table.getColumnCount();
              if (columnCount == 0) {
                   System.out.println("columnCount = 0");
                   return;
              int width = scrollPane.getViewport().getSize().width;
              System.out.println("width = " + width);
              if (width == 0) return;
              int columnWidth = width / columnCount;
              System.out.println("columnWidth = " + columnWidth);
              for (int i = 0; i < columnCount; i++) {
                   table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth);
              table.revalidate();
              table.repaint();
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              final Test1 t = new Test1();
              f.setContentPane(t);
              f.setSize(600, 600);
              f.setVisible(true);
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        t.pack();
    }

  • User cannot resize jTables� columns

    Hello,
    Using NetBeans IDE 3.5.1, I built a jTable, controlled by a
    JScrollpane.
    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);
    Col.setWidth(width);
    Col.setResizable(true);
    Col.setMinWidth(width);
    3.     jTable header details:
    JTableHeader anHeader = JTable1.getTableHeader();
    anHeader.setReorderingAllowed(false);
    anHeader.setResizingAllowed(true);
    4.     JTable1.getTableHeader().setResizingAllowed(true);.
    5.     Initial declerations:
    a.     JTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
         JTable1.setColumnSelectionAllowed(true);
         JTable1.setDragEnabled(true);
         JTable1.setPreferredScrollableViewportSize(new
    java.awt.Dimension(650, 500));
         JTable1.setPreferredSize(new java.awt.Dimension(1200, 409));
         JTable1.setRequestFocusEnabled(false);
    b.     JScrollPane1.setMaximumSize(new java.awt.Dimension(750, 412));
         JScrollPane1.setPreferredSize(new java.awt.Dimension(750,
    412));
         JScrollPane1.setViewportView(JTable1);
         JScrollPane1.setAutoScolls(false);
    c.     Jtable.autoCreateColumnsFromModel (true);
    Thanks alot,
    Itay

    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.

  • Setting the jTable column width

    Coming from VB6 to Java is hard for me. Syntax is so much different.
    Below is what I am doing to populate the jTable and the values are coming from MySQL. My problem is setting the column width but I am having difficult understanding how to do it. I looked on the website and downloaded some examples and clearly because I am new and I simply do not understand it. I was wonder if someone is willing to modify the codes below on how I should do it. Thanks
    private void populate_grid(){
    Vector dataVector = new Vector();
    Vector columnVector = new Vector();
    columnVector.add("ID#");
    columnVector.add("Account Description");
    columnVector.add("Contact");
    columnVector.add("State");
    while (myResult.next()) {
    Vector rowVector = new Vector();
    System.out.println(myResult.getString("acct_name"));
    rowVector.add(myResult.getString("cust_id"));
    rowVector.add(myResult.getString("acct_name"));
    rowVector.add(myResult.getString("main_contact"));
    rowVector.add(myResult.getString("main_state"));
    dataVector.add(rowVector);
    jTable1.setModel(new javax.swing.table.DefaultTableModel(dataVector, columnVector));

        int rows = 3;
        int cols = 3;
        JTable table = new JTable(rows, cols);
        // Disable auto resizing
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        // Set the first visible column to 100 pixels wide
        int vColIndex = 0;
        TableColumn col = table.getColumnModel().getColumn(vColIndex);
        int width = 100;
        col.setPreferredWidth(width);

  • Adjust JTable column width according to content

    'morning all,
    How can I resize each column's width according with the content ? I mean, i'd like to show all the content of my cells, neither clipped nor with leading space.
    Can something help me, please ?
    Bye bye by Dhavide - we will, forever -

    If you don't set specific font for individual cells, your JTable inherited a default font from the Component class. You can try something like this (untested):
    FontMetrics FM=getFontMetrics(myTable.getFont());
    int j=0;
    int col=1;  // or whatever column you want to change width
    String out;
    for (int row=0;row<maxRow;row++) {
       out=myTable.getValueAt(row,col);
       if (FM.stringWidth(out)>j) j=FM.stringWidth(out);
    myTable.setColWidth(col,col+1,j);          // width plus a fudge factorwhere myTable is a reference to your own table and out is the label in each row in the column that you want to change the width.
    ;o)
    V.V.

  • Help with JTable column width

    Hi,
    I'm trying to resize my JTable columns with this code, but it's not working. What I am doing wrong?
    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
    TableColumn tc = table.getColumnModel().getColumn(i);
    int width = (i == 0)? 10 : table.getWidth()/2 - 10; // three columns
    tc.setPreferredWidth(width);
    Thanks,
    Andr�

    Now my problem is that using either of these methods
    is they don't carry the user's selected column width
    through updates.It sounds like the change event your table model is firing is causing the entire table to be rebuilt. I would guess that you are firing fireTableStructureChanged() which would cause the entire table to be rebuilt (columns, cell values, etc.) Just fire a change event for the minimum necessary. If you can't identify what data in your table has changed (to fire cell or row change events), but the structure (columns) of the table hasn't changed, just fire fireTableDataChanged(). This will cause the cells to be redrawn with the new values, but shouldn't cause the columns to be rebuilt and resized.

  • Tweaking JTable column widths

    One of the things I don't seem to be able to do cleanly is programatically sizing column widths. What I'm trying to do, presently, is to try and set column widths on numeric columns according to class.
    This is what I'm trying:
       public static void tweakColumns(JTable table) {
            TableColumnModel tcm = table.getColumnModel();
            TableModel data = table.getModel();
            table.createDefaultColumnsFromModel();
            for(int i = 0; i < tcm.getColumnCount(); i++) {
                TableColumn col = tcm.getColumn(i);
                Class cls = data.getColumnClass(i);
                if(cls.equals(Percentage.class))
                    col.setPreferredWidth(44);
                else if(cls.equals(Money.class))
                    col.setPreferredWidth(60);
                else if(cls.equals(Integer.class))
                    col.setPreferredWidth(20);
            table.revalidate();
        }I've tried calling this when I set the table up, I've tried defering it with invokeLater. The problem appears to be when there's plenty of space the additional space is applied indiscrimitely, smothering my settings, whereas I want the extra to be applied to the columns I don't set preferences for (typically text fields).
    I don't want to impose a maximum column width if the user choses to resize columns. I want to control the distribution of space when it's done by swing.

    I think your only solution is to set the Preferred sizes of all the columns, even the textfields.
    I have done similar thing and it works but only when all the preferred sizes of all the columns are set.
    If you record the total width available to all columns before you start setting the preferred sizes of the Percentage, Money and Integer columns you can subtract the sizes of these columns as you set them. When you come out of the loop you will have a value that is what is left of the width. You can then set all the remaining unset columns to values based on this remaining width.
    i.e. you have 700 pixels total width the the initial loop you have fields that result in 340 pixels being allocated. You have 360 pixels left over. If you have 3 remaining unset fields then you then set their preferred sizes to be 120 pixels. This, I think, will force swing to allocate in the way you want.
    I've never tried it but you might find setting the textfields to unrealistically large Preferred sizes will make swing attempt to do its best and end up with what you want.

  • Is it possible to resize page column widths at runtime (by the user)?

    hi all,
    i have cretaed a page using the 2-columns narrow/wide layout.  this layout is perfect for what i want to do.
    however, the users have complained that they would like to be able to resize the columns, just like they are able to do with the Detailed Navigation column (using the small "<" and ">" arrows).
    is it posssible to add this functionality to my custom pages so that can also resize the columns?
    i searched for options in the properties, but didn't find anything.
    thanks,
    mm

    This was a great place for me to start
    Thank you
    I took profdant139's suggestions a bit further as my real goal was to have the "Document column" narrower. The goal to be able to see all the other document info that was usually hidden way out to the right
    To achieve my results I right clicked in the upper bar with the column names and chose from the drop down box "comments" column (as suggested). I then dragged it to the far right. This pushed all the other columns over.
    In the end of the day I ended up adding "Size" and "Date modified" columns as well to get my desired results.
    Remember one can move different columns around to be in the order you need by clicking on the column to get it active and then left click and drag it to where you want
    Another great thing is that by default (Using Mavericks) the date modified, opened,created columns have date and time. One can shrink them down to xx/xx/xx format by manually adjusting the column width like one does in Excel - click on column separator up top and drag
    Once all that is done, at least on my box, I closed it out and opened up a new finder window and everything was as I wanted.
    Thank you for the help  from the above helper to get me here

  • Set JTable column width

    Hi,
    I would like to set the column width of JTable.
    ========================================
    JTable table;
    DefaultTableModel tableModel;
    tableModel = new DefaultTableModel();
    table = new JTable( tableModel);
    JScrollPane scrollPane = new JScrollPane(table);
    for(int i = 0; i < heading.length; i++)
    tableModel.addColumn( heading[ i ]);
    ========================================

    Did you run the tutorial code? Did it work?
    Now compare the tutorial code with your code to determine what is different.
    We can't tell you what is different based on the one line of code you posted:
    colModel.getColumn(i).setPreferredWidth(100);

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

  • Form Resize Affect Column width?

    Hi Folks,
    I have a very strange problem. I try to add a new matrix to Production Order form. The matrix will have 2 columns which are:
    1. No - Non Editable (for numbering)
    2. Description (information).
    My code is like the following:
            oItem = oForm.Items.Add("mxRoute", SAPbouiCOM.BoFormItemTypes.it_MATRIX)
            oItem.Left = 12
            oItem.Width = 532
            oItem.Top = 136
            oItem.Height = 183
            oItem.FromPane = 3
            oItem.ToPane = 3
            oMatrix = oItem.Specific
            oColumns = oMatrix.Columns
            '// Adding Culomn items to the matrix
            oColumn = oColumns.Add("#", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            oColumn.TitleObject.Caption = "#"
            oColumn.Width = 20
            oColumn.Editable = False
            oColumn = oColumns.Add("Col1", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            oColumn.TitleObject.Caption = "Operations"
            oColumn.Width = 500
            oColumn.Editable = True
    The problem occured when i try to maximize my form. The first Col (#) will resize to a very big size!!! When i try to resize it to smaller form, it still very big column. Anybody has clue what should i do to the form since it is not possible to restrict the form type to Fixed???
    Your help will be very appreciated..
    Rgds,
    Harianto Ng

    Hi Harianto Ng,
    Catch the after resize event and resize both columns by hand.
    1. calculate width of columns 1 + 2
    2 resize the first to 20
    3 resize the second to totalwidth-20
    Regards
    Ad

Maybe you are looking for

  • How to use another XSLT processor

    Hello all, Recently, I do need to use XSLT 2.0 processor, but how to install it to the JDK? Please give the detailed steps. And how to use it, just import the package? How to avoid the program to the old processor, because I doubt probably the old pr

  • Create two users for the same schema

    Hi, I want to create 2 users, with different privilleges each, so that they can have access to the same database tables and also to their metadata tables (user_sdo_maps, user_sdo_themes, user_sdo_styles). I have created the tables under the first use

  • Exception handling in sorting arrays

    Hi all, I have a problem with the use of the built in java sort fo arrays. My program works on an array with 4 or 5 entities. When I run it in some folders it works but not in others. I get the following error after compilation, where "ResultData" is

  • Help!  Flash drive worries...

    While on my macbook I dragged several files from a flash drive folder to the trash can.  I then ejected the flash drive and gave it to a coworker.  I am very concerned they will be able to see my "deleted" files if they plug the drive into a PC becau

  • Finder acting weird on AFP shares

    Hi everyone, I am using an OS X 10.8.5 Server with mostly 10.6.8 Clients. The clients usually open, save, copy to and from AFP shares provided by the server. Sometimes it happens that a client gets thrown out of a folder it is currently viewing on th