JTable width

I've got the following code:
public class JMyFrame
extends JFrame
  public JTable jTable;
  public JScrollPane jScrollPane;
  public JMyFrame()
    setSize(APP_WIDTH, APP_HEIGHT);
    setResizable(false);
    jTable = new JTable(...);
    jScrollPane = new JScrollPane(jTable);
    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    contentPane.add(jScrollPane, BorderLayout.CENTER);   
  public static void main(String[] args)
    try {
      JFrame jFrame = new JMyFrame();
      jFrame.addWindowListener(
        new WindowAdapter()
          public void windowClosing(WindowEvent e)
            System.exit(0);
      jFrame.setVisible(true);
    } catch (Exception e) {
      e.printStackTrace();
}I want to adjust the size of the columns depending on the avalaible width. How can I know the real avalaible width before the table is going to be shown in the screen?
If I add the following lines of code just before the end of the JMyFrame constructor:
System.err.println("jTable.getSize()=" + jTable.getSize());
System.err.println("jTable.getPreferredSize()=" + jTable.getPreferredSize());
System.err.println("jScrollPane.getSize()=" + jScrollPane.getSize());
System.err.println("jScrollPane.getPreferredSize()=" + jScrollPane.getPreferredSize());
System.err.println("jScrollPane.getViewport().getSize()=" + jScrollPane.getViewport().getSize());
System.err.println("jScrollPane.getViewport().getPreferredSize()=" + jScrollPane.getViewport().getPreferredSize());I get:
jTable.getSize()=java.awt.Dimension[width=0,height=0]
jTable.getPreferredSize()=java.awt.Dimension[width=150,height=32]
jScrollPane.getSize()=java.awt.Dimension[width=0,height=0]
jScrollPane.getPreferredSize()=java.awt.Dimension[width=470,height=404]
jScrollPane.getViewport().getSize()=java.awt.Dimension[width=0,height=0]
jScrollPane.getViewport().getPreferredSize()=java.awt.Dimension[width=450,height=400]but neither of these values represent the real avalaible width.
I've added a button in order to get more information after everything is displayed on the screen. When I clicked the same lines of code show totally different results:
jTable.getSize()=java.awt.Dimension[width=150,height=32]
jTable.getPreferredSize()=java.awt.Dimension[width=150,height=32]
jScrollPane.getSize()=java.awt.Dimension[width=594,height=350]
jScrollPane.getPreferredSize()=java.awt.Dimension[width=470,height=424]
jScrollPane.getViewport().getSize()=java.awt.Dimension[width=574,height=326]
jScrollPane.getViewport().getPreferredSize()=java.awt.Dimension[width=450,height=400]In this case, the value returned by jScrollPane.getViewport().getSize() do represent the avalaible width and height.
I guess this happens because this way I'm getting this values after the whole applications in displayed on the screen. Is there a way to do it before?

I doesn't work. Everytime I execute this code:
System.err.println("jTable.getSize()=" + jTable.getSize());
System.err.println("jTable.getPreferredSize()=" + jTable.getPreferredSize());
System.err.println("jScrollPane.getSize()=" + jScrollPane.getSize());
System.err.println("jScrollPane.getPreferredSize()=" + jScrollPane.getPreferredSize());
System.err.println("jScrollPane.getViewport().getSize()=" + jScrollPane.getViewport().getSize());
System.err.println("jScrollPane.getViewport().getPreferredSize()=" + jScrollPane.getViewport().getPreferredSize());before executing jFrame.setVisible(true) I get:
jTable.getSize()=java.awt.Dimension[width=0,height=0]
jTable.getPreferredSize()=java.awt.Dimension[width=150,height=32]
jScrollPane.getSize()=java.awt.Dimension[width=0,height=0]
jScrollPane.getPreferredSize()=java.awt.Dimension[width=470,height=404]
jScrollPane.getViewport().getSize()=java.awt.Dimension[width=0,height=0]
jScrollPane.getViewport().getPreferredSize()=java.awt.Dimension[width=450,height=400]But If I execute it after executing jFrame.setVisible(true) I get:
jTable.getSize()=java.awt.Dimension[width=150,height=32]
jTable.getPreferredSize()=java.awt.Dimension[width=150,height=32]
jScrollPane.getSize()=java.awt.Dimension[width=394,height=97]
jScrollPane.getPreferredSize()=java.awt.Dimension[width=470,height=424]
jScrollPane.getViewport().getSize()=java.awt.Dimension[width=374,height=73]
jScrollPane.getViewport().getPreferredSize()=java.awt.Dimension[width=450,height=400]and these values are the ones I'm looking for...but just before setting the visibility of the main frame to true.
I've also tried to do the following:
jFrame.doLayout();
System.err.println("jTable.getSize()=" + jTable.getSize());
System.err.println("jTable.getPreferredSize()=" + jTable.getPreferredSize());
System.err.println("jScrollPane.getSize()=" + jScrollPane.getSize());
System.err.println("jScrollPane.getPreferredSize()=" + jScrollPane.getPreferredSize());
System.err.println("jScrollPane.getViewport().getSize()=" + jScrollPane.getViewport().getSize());
System.err.println("jScrollPane.getViewport().getPreferredSize()=" + jScrollPane.getViewport().getPreferredSize());
jFrame.setVisible(true)or
jFrame.validate();
System.err.println("jTable.getSize()=" + jTable.getSize());
System.err.println("jTable.getPreferredSize()=" + jTable.getPreferredSize());
System.err.println("jScrollPane.getSize()=" + jScrollPane.getSize());
System.err.println("jScrollPane.getPreferredSize()=" + jScrollPane.getPreferredSize());
System.err.println("jScrollPane.getViewport().getSize()=" + jScrollPane.getViewport().getSize());
System.err.println("jScrollPane.getViewport().getPreferredSize()=" + jScrollPane.getViewport().getPreferredSize());
jFrame.setVisible(true)but it doesn't work either.

Similar Messages

  • JTable width resize

    Hello,
    I insert a JTable without header in a JTextPane. I'm able to resize the width of the columns with the mouse, but the JTable isn't resized. I call the method JTable.setWidth(int width); to set the start width.
    Do anyone knows a solution ?
    Thanks in advance

    Usually a JTable is added in an JScrollPane. Please use setMinimumSize() or setPreferredSize() to set this pane the size you want it to start.

  • JTable  - getting component width

    Hello
    I've come across a small problem I can't overcome as I'm new with Swing.
    I would like to set the initial sizes of JTable column headers using a values from array that indicate the percentage size of JTable container for every header e.i.:
    int[] columnsWidth = new int[]{20,70,5,5};   //4 columns //20%,70%,5%,5% of   JTable width
    //in MyTable constructor
                    TableColumn column = null;
              for(int i =0; i<dm.getColumnCount();i++){
                   column = getColumnModel().getColumn(i);
                      double width = (columnsWidth/100.0)* getWidth();
                   column.setPreferredWidth((int)width);
    unfortunately JComponent:getWidth() returns 0, probably because its in JTable constructor, but where can i get correct component width ?
    Thanks for your help!

    I have some code that does something close; but I don't think it's completely what you want.
    First, in our table model, we define some widths:
    private final static int[] widths = { 10, 20, 20, 10};Then, in our table class, we for each of these columns. We essentially take the width of 10, multiple by some value, and use that value. I was tryign to be able to specify widths in characters, assuming a fixed width font.
        private void setPreferredColumnWidths() {
            for (int i = 0; i < getColumnCount(); i++) {
                TableColumn col = getColumnModel().getColumn(i);
                int w = getColumnWidth(i);
                col.setPreferredWidth(w);
                col.setWidth(w);
        }We disable the resize on the table columns, as we want fixed width columns within a scrollable pane. However, if you enable auto sizing:
    setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);You'll find that the EXTRA space is alloted relative on the preferred size of those columns. It doesn't result in the exact % width you are looking for, so I don't know if that's close enough for you.

  • JTable Horizontal Scroll WHEN NEEDED fix?

    Me again....
    JTable in a JScrollPane When the Jtable width exceeds the scrollpane I would like a horizontal scrollbar to appear. If the Jtable does not exceed the width Id like it to fill the ScrollPane.
    If I use the AUTO_RESIZE_OFF I get a horizontal scrollbar all the time. I dont want this if possible.
    I did try to overwrite getScrollableTracksViewportWidth() and getPreferredSize() as suggested by work around http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4127936
    However this bug is not exactly what I am having trouble with.
    Anyone know what I can do for this?
    Thanks
    B.

    You're welcome.
    Autoscrolling means that you can middle click on a web page and then get a scroll icon to indicate that you can move the mouse up or down to scroll the page automatically.

  • [Feature request] Runtime width of JTable columns based on attribute settings

    I'm wondering if it's possible to let 'JClient' dynamically resize the columns in a JTable. Eg: I have set the width of some attribute of some ViewObject to 3. But when I run the application all columns are equally sized. I tried changing the JTable's property autoResizeMode (figuring it might override settings by JClient), but that doesn't seem to have any effect.
    Also, 'grabbing' a column from the table through some manual coding and setting the width of that column doesn't seem to work either.
    I've posted something regarding JTable Re: for specifically RIZWAN from PAkistan or anyone, but I'm curious to know if this 'Specialised editor for Grid Control (JTable)' that Grant Ronald spoke of, will include some sort of applicable functionality.
    It's clear that we need some better (that is, 'any' ;)) way of manipulating columns in a JClient table.
    Any comments?
    Thanks.
    Arno

    We are currently looking into that.
    The column width should not be controlled from the model, it is a setting on JTable, We are considering providing a JClient control (JUTable ??), which is a JTable in a scrollpane and give you more power over column width, column headers etc....
    We are currently evaluating that.
    It would mean that you've got a table control with properties allowing you to set these things on the control itself.
    Currently you have to set the hints on the TableColumn.
    Here is an example :
    tableDeptView1.setModel(JUTableBinding.createAttributeListBinding(panelBinding, tableDeptView1, "DeptView1", null, "DeptView1Iter", new String[] {"Deptno", "Dname", "Loc"}));
    tableDeptView1.getColumn("Deptno").setMaxWidth(75);
    tableDeptView1.getColumn("Loc").setPreferredWidth(200);
    tableDeptView1.getColumn("Loc").setMinWidth(100);
    tableDeptView1.getColumn("Loc").setMaxWidth(450);

  • Column width in JTables.Help needed!!!!

    Hi
    I am trying to print out a JTable and have had a few problems along the way but have managed to solve them all so far apart from this one. When the JTable is shown on screen it doesn't make the columns wide enough . I ahev managed to find some code from these forums but it doesnt resize correctly if the Column headings contain more text than any of the data (If you know what i mean). Below is the code i am using
    public void sizeAllColumnsToFitData (JTable table)  {
        for (int col = 0; col < table.getColumnCount (); col++)  {
          TableColumn curColumn = table.getColumn (table.getColumnName (col));
          if (curColumn == null)
            continue; // not a valid column skip
    //  Translate to the model
          int modelColumn = curColumn.getModelIndex ();
    //  Loop for all rows in this column looking for the widest piece of data
          int maxColumnWidth = 0;
          for (int row = 0; row < table.getRowCount(); row++)  {
            TableCellRenderer curCellRenderer = table.getCellRenderer (row, modelColumn);
            Object value = table.getValueAt (row, modelColumn);
            Component curRenderComponent = curCellRenderer.getTableCellRendererComponent(table, value, true, true, row, modelColumn);
            Dimension cellDimension = curRenderComponent.getPreferredSize ();
            if (cellDimension.width > maxColumnWidth)
              maxColumnWidth = cellDimension.width;
    //  Set the column width to fit the maximum
          Dimension cellSpacing = table.getIntercellSpacing ();
          curColumn.setPreferredWidth (maxColumnWidth + (cellSpacing != null ? cellSpacing.width : 1));
      }I pass my table into here and it works fine apart from in doesnt take into consideration the size of the headings. Please Help ME!!!!

    java.lang.NullPointerException
         at database_testing.SLAMS.sizeAllColumnsToFitData(SLAMS.java:473)
         at database_testing.SLAMS.getInfo(SLAMS.java:364)
         at database_testing.SLAMS.getInfo_actionPerformed(SLAMS.java:434)
         at database_testing.SLAMS_getInfo_actionAdapter.actionPerformed(SLAMS.java:527)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1764)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1817)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
         at java.awt.Component.processMouseEvent(Component.java:5134)
         at java.awt.Component.processEvent(Component.java:4931)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3639)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Window.dispatchEventImpl(Window.java:1590)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)Also i think it may have something to do with my headerRenderer being null cus if i replace the line TableCellRenderer headerRenderer = curColumn.getHeaderRenderer(); with TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer(); then it doesnt come up with an error but only increase the size of the coluns (where neccessary by 2 characters)

  • 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

  • Jtable cell width in JFileChooser

    I wonder if there is a way to adjust the table cell width in JFileChooser ?
    When I list the "My Computer" directory, I can see a list of drives in a JTable, such as "A:\", "C:\", "D:\", I've set it that way so that it displays the JTable view details as default. But the widths of the columns aren't the way I'd like to see, how can I adjust the cell widths of "Name", "Type","TotalSize" ...
    Thanks
    Frank

    uhmm yes, but i want to set automatically at run time,Then you need to calculate it at run time. Search the forum. There are many postings on this topic that give a solution. Basically you loop through all the rows in the column and invoke the prepareRenderer(...) method of the table and save the largest width and then set the TableColumn width.

  • 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 set the width of a cell in JTable?

    I have created a JTable and I want to set the width of cells.How can I do that?

    This is now the third person to tell you that Swing questions should be posted in the Swing forum.
    You have several postings out there where you have been given an answer but you haven't bothered to respond to the posting. Indicating whether the suggestion was helpfull or not. I guess you really don't want help from people in the future.

  • Display a horizontal scrollbar in a JTable as to fit column width

    hi all,
    I am using JTable to display records.I've set a horizontal scrollbar by using 'table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);',but although i got a horizontal scrol bar the column width is constant for all the columns and not getting adjusted according to the lenght of the column names. As the column names and the records are of different size in the database i want the column widht to be adjusted according to the length of column names and record length.so please tell me how to do it?
    regards...

    .I've set a horizontal scrollbar by using 'table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);You are welcome.
    i want the column widht to be adjusted according to the length of column names and record length.so please tell me how to do it?Search the forum. This question has been asked and answered before.

  • 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();
    }

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

  • How can i adjest the width of the JTable Header

    hi all,
    I have putted group header in JTable, due to this the width of the JTable and width of the column of the row is little bit variation. pleases suggest me any way to avoid it.
    Thanks
    Dayananda B V

    TableColumn tCol = null;
            for(int i = 0; i <= 5; i++){
                tCol = tblData.getColumnModel().getColumn(i);
                if(i == 1)
                    tCol.setPreferredWidth(130);
                else
                    tCol.setPreferredWidth(30);
            }

  • Is there a jtable column width minimum?

    Hi,
    I try to set the column width in a JTable to 3 or 5, but it seems that there is a hard minimum width of 15.
    I use
    table.getColumnModel().getColumn(0).setMaxWidth(3);
    Just afterwards I get with
    System.out.println("width: "+table.getColumnModel().getColumn(0).getWidth());
    width: 15
    I tried to set autoresize false, validate, repaint, .... Nothing helps. I have no table header. It doesn't matter if I use a custom cell renderer or the default. If I set the width to e.g. 30, it works. But no way to get below 15.
    Thanks, Ulrich

    >
    table.getColumnModel().getColumn(0).setMaxWidth(3);
    Try this instead
    table.getColumnModel().getColumn(0).setPreferredW
    dth(3);ICE
    The default minimum is 15, there is a setMinWidth function.
    table.getColumnModel().getColumn(0).setMinWidth(3);then I would try setting the preferred width.

Maybe you are looking for