How to size JTable Column width?? Need help

Using the following logic to size column width, but only the 1st column is sized. How can I get the other columns sized??
int widthsSummary[] = {340,60,150,60,60};
for (int i=0; i<1; i++)
column = getScrollPaneTableSummary).getColumnModel ().getColumn(i);
column.setMinWidth(widthsSummary);
column.setMaxWidth(widthsSummary[i]+50);
column.setPreferredWidth(widthsSummary[i]);          

First, take a look at your for loop
for (int i=0; i<1; i++)i starts at 0 and cannot be equal to or greater than 1. This loop will only occur once, when i = 0.
Second, take a look at your set...Width calls
column.setMinWidth(widthsSummary);
column.setMaxWidth(widthsSummary+50);
column.setPreferredWidth(widthsSummary); widthsSummary is an array. You need a number to set widths. Try ...set...width(widthsSummary);
Hope that helps.

Similar Messages

  • How to set jtable column width

    Hello..
    I 'm using a simple jtable with the default model. I just want to set each column size to make table smaller Is this possible?
    Thanks
    Feras

    newdeveloper wrote:
    Hello..
    I 'm using a simple jtable with the default model. I just want to set each column size to make table smaller Is this possible?
    Thanks
    FerasI think that your problem probably has more to do with the Layout you're using (or not using) than it does with individual column sizes. What layout are you using?
    What happens when you set the size (or preferredSize, minimumSize, and maximumSize) on the whole JTable?
    You might also be looking for JTable.[getColumnModel()|http://download-llnw.oracle.com/javase/6/docs/api/javax/swing/JTable.html#getColumnModel%28%29].[getColumn()|http://download-llnw.oracle.com/javase/6/docs/api/javax/swing/table/TableColumnModel.html#getColumn%28int%29].[setPreferredWidth()|http://download-llnw.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setPreferredWidth%28int%29].
    If none of those approaches work, post an SSCCE that demonstrates the problem.
    PS- Swing questions belong in the Swing forum.

  • How to set displayed column width for a search help

    I have created an elementary search help for a custom field with a value table behind it.
    The search help functions correctly, but when displayed the column widths are all 10 characters. The user has to adjust the column to view the descriptive text.
    Can anyone tell me how to set default column widths for the help?

    Please  open you Elementary search  help  and see the Column  width   behind the Fields of your ...there  increase the width of the fields
    "Activate it  and refresh
    reward  points if it is usefull .....
    Girish

  • How can i Auto Size the Column width in RDLC Report

    Hi Friend's,
    I have created Windows application with RDLC Report. I am binding(Generating) dynamic columns and data's in RDLC Report Using Matrix control, I need to make Auto size of Column width for each Column in
    Matrix of RDLC report. So Can any one suggest me to make the Auto Size of Column Width in RDLC.
    Thanks in Advance,
    Mohan G

    Hi Mohan,
    In Reporting Services, the column width/height is hard-coded, hence, we cannot set the column width/height dynamically or based on an expression. So is the report size.
    In addition, since it is a RDLC report, we need a ReportViewer control to display this report within a custom application. If you need to change the size of the whole report, we can set the AsyncRendering property of the ReportViewer control to false, and
    set the SizeToReportContent property to true.
    Regards,
    Mike Yin
    TechNet Community Support

  • How can I set column width in JTable?

    How can I set column width in JTable?

    Also, read the JTable API before posting questions. You will find a link to the Swing tutorial on "How to Use Tables", which contains an example of doing exactly this.

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

  • 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 do I set my side column width & height - Help ?

    Please see my website I am building using a Dreamweaver template  - it has a spry accordian menu in the right column - I am not skilled enough to understand how to set the height and width of this column   Can someone help?

    Here is spry css:
    * SpryAccordion.css - Revision: Spry Preview Release 1.4 */
    /* Copyright (c) 2006. Adobe Systems Incorporated. All rights reserved. */
    /* This is the selector for the main Accordion container. For our default style,
    * we draw borders on the left, right, and bottom. The top border of the Accordion
    * will be rendered by the first AccordionPanelTab which never moves.
    * If you want to constrain the width of the Accordion widget, set a width on
    * the Accordion container. By default, our accordion expands horizontally to fill
    * up available space.
    * The name of the class ("Accordion") used in this selector is not necessary
    * to make the widget function. You can use any class name you want to style the
    * Accordion container.
    .Accordion {
              overflow: hidden;
              width: 210px;
              border-bottom: 1px solid #ffffff;
              outline: none;
    /* This is the selector for the AccordionPanel container which houses the
    * panel tab and a panel content area. It doesn't render visually, but we
    * make sure that it has zero margin and padding.
    * The name of the class ("AccordionPanel") used in this selector is not necessary
    * to make the widget function. You can use any class name you want to style an
    * accordion panel container.
    .AccordionPanel {
              margin: 0px;
              width: 210px;
              padding: 0px;
    /* This is the selector for the AccordionPanelTab. This container houses
    * the title for the panel. This is also the container that the user clicks
    * on to open a specific panel.
    * The name of the class ("AccordionPanelTab") used in this selector is not necessary
    * to make the widget function. You can use any class name you want to style an
    * accordion panel tab container.
    .AccordionPanelTab {
              color: #ffffff;
              margin: 0px;
              cursor: pointer;
              padding: 5px 10px 5px 30px;
              font-weight: normal;
              font-family: "Trebuchet MS";
              font-size: 12px;
              text-transform: uppercase;
              -moz-user-select: none;
              -khtml-user-select: none;
              background-repeat: no-repeat;
              background-image: url(../images/accordion_plus_closed.png);
              background-position: 10px 7px;
              border: 1px solid #ffffff;
              border-bottom: none;
    /* This is the selector for a Panel's Content area. It's important to note that
    * you should never put any padding on the panel's content area if you plan to
    * use the Accordions panel animations. Placing a non-zero padding on the content
    * area can cause the accordion to abruptly grow in height while the panels animate.
    * Anyone who styles an Accordion *MUST* specify a height on the Accordion Panel
    * Content container.
    * The name of the class ("AccordionPanelContent") used in this selector is not necessary
    * to make the widget function. You can use any class name you want to style an
    * accordion panel content container.
    .AccordionPanelContent {
              margin: 0px 0px 0px 0px;
              padding: 0px 0px 0px 0px;
              border-left: 1px solid #ffffff;
              border-right: 1px solid #ffffff;
              overflow: auto;
    /* This is an example of how to change the appearance of the panel tab that is
    * currently open. The class "AccordionPanelOpen" is programatically added and removed
    * from panels as the user clicks on the tabs within the Accordion.
    .AccordionPanelOpen .AccordionPanelTab {
              color: #ffffff;
              background-image: url(../images/accordion_plus_open.png);
              border-bottom: none;
    /* This is an example of how to change the appearance of the panel tab as the
    * mouse hovers over it. The class "AccordionPanelTabHover" is programatically added
    * and removed from panel tab containers as the mouse enters and exits the tab container.
    .AccordionPanelTabHover {
              color: #95c8fc;
    /* This is an example of how to change the appearance of all the panel tabs when the
    * Accordion has focus. The "AccordionFocused" class is programatically added and removed
    * whenever the Accordion gains or loses keyboard focus.
    .AccordionFocused .AccordionPanelTab {
    /* This is an example of how to change the appearance of the panel tab that is
    * currently open when the Accordion has focus.
    .AccordionFocused .AccordionPanelOpen .AccordionPanelTab {
    /* Custom classes */
    .acontent {
              padding: 5px 10px 10px 20px;
              font-size: 10px;
    .acontent p{
              font-size: 12px;
              color: #ffffff;
    .acontent li a { color: #fffff; font-size: 12px; text-decoration: none;}
    .acontent li a:visited  { color: #0CF; }
    .acontent li a:hover    { color: #5872f4; }

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

  • How to set the column width of JTable

    I want do remember the column width and write it to a file, when the window is started , the column width is read from the file and the table is set as that. I also want the column width is not fixed and can be changed by mouse.But I am always failded.
    How to do? would you please help me!
    Thanks a lots.

    To "remember" the column widths, add a mouse listener to the table header. Upon mouseReleased(), get the column widths and save them to your file. When the application starts next time, get the stored widths and set them using:
    table.getColumn("XXX").setPreferredWidth(...);
    By default, your columns are adjustable, but you can use:
    table.getTableHeader().setResizingAllowed(true);

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

  • How do you autosize column widths in a multicolumn listbox?

    I know that it's possible to autosize row height, but I can't find anything relating to autosizing column widths in a multicolumn listbox. This makes what I'm doing difficult, because I want to be able to have dynamic content and won't know beforehand how wide to make the columns. Therefore, I need to do it programatically or find something already built in.
    Thanks for your help!

    I did an example along the lines of the suggestions above and it works pretty well. I'll attach it here. Note that this only works for 13pt font. If you want to scale this example to include larger font, then you can get that information from the cell height property, which does autoscale by default. The cell height is usually about 2 larger than the font size (i.e. 13pt font = 15 cell height, 24 pt font = 26 height).
    This example is written in LV7.0. What would really be cool is if someone would write an XControl for LV8 that would do all this automatically and require no extra block diagram code! If only I had the time...
    Jarrod S.
    National Instruments
    Attachments:
    Autosize_Columns.vi ‏30 KB

  • Setting exact    jtable column width

    I need to set each column width in table 200. Columns are added dynamically. And after one column added the previous one width is become small(about 75).
    There is test code. Please, help, here is last place I can find the answer.
    package visual.jtable;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import java.awt.*;
    import java.io.File;
    import java.util.Arrays;
    import java.util.List;
    import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
    public class TestFrame extends JFrame
        public JTable table;
        public TestFrame()
            super("Test frame");
            createGUI();
        public void createGUI()
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            table = new JTable();
            table.setBounds(400, 400, 700, 300);
            JScrollPane pane = new JScrollPane(table);
            System.out.println(pane.getLayout().getClass().toString());
            pane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
            pane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            panel.add(pane, BorderLayout.CENTER);
            getContentPane().add(panel);
        static int lastCol = -1;
        static int lastRow = -1;
        static int visibleRows = 13;
        public static void addFile(JTable table, File file)
            DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
            if (lastRow == visibleRows - 1 || lastCol == -1)
                TableColumnModel cm = table.getColumnModel();
                table.getTableHeader().setResizingAllowed(false);
                table.setAutoscrolls(true);
                table.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
                tableModel.addColumn(String.valueOf(lastCol + 1), new File[visibleRows]);
                int index = tableModel.findColumn(String.valueOf(lastCol + 1));
                cm.getColumn(index).setMinWidth(200);
                cm.getColumn(index).setMaxWidth(200);
                cm.getColumn(index).setWidth(200);
                cm.getColumn(index).setPreferredWidth(200);
                cm.getColumn(index).setResizable(false);
                System.out.println("width = " + cm.getColumn(index).getWidth());
                System.out.println(table.getAutoResizeMode());
                lastCol++;
                lastRow = -1;
            lastRow++;
            tableModel.setValueAt(file, lastRow, lastCol);
        public static void main(String[] args) throws Exception
            JFrame.setDefaultLookAndFeelDecorated(true);
            try
                UIManager.setLookAndFeel(new WindowsLookAndFeel());
            catch (Exception e)
            TestFrame frame = new TestFrame();
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            List<File> f = Arrays.asList(FileSystemView.getFileSystemView().getFiles(new File("C:\\Documents and Settings\\Admin\\&#1056;&#1072;&#1073;&#1086;&#1095;&#1080;&#1081; &#1089;&#1090;&#1086;&#1083;"), false));
            for (File file : f)
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
    class ListViewTableCellRenderer2 extends DefaultTableCellRenderer
       // public ListViewTableCellRenderer(){}
        // implements javax.swing.table.TableCellRenderer
        public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
            Component component = super.getTableCellRendererComponent(
                    table, value, isSelected, hasFocus, row, column);
            File file = (File) value;
            JLabel label = (JLabel) component;
            label.setMinimumSize(new Dimension(200, label.getHeight()));
            label.setMaximumSize(new Dimension(200, label.getHeight()));
            label.setPreferredSize(new Dimension(200, label.getHeight()));
            label.setSize(200, label.getHeight());
            label.setMinimumSize(new Dimension(200, label.getHeight()));
            label.setText("<table width=\"200\">" +
                    "  <tr>" +
                    "    <td>Month</td>" +
                    "  </tr>" +
                    "</table>");
            if(file == null)
                label.setIcon(null);
                return label;
            //label.setIcon(ViewManager.getCachedIcon(file));
              label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(file));
            if(file.isHidden())
               label.setText("<html><font color = \"red\">" + file.getName() + "</font></html>");
            label.setText(file.getName());
            label.setText("<table width=\"200\">" +
                    "  <tr>" +
                    "    <td>Month</th>" +
                    "  </tr>" +
                    "</table>");
            return label;
    }

    And after one column added the previous one width is become small(about 75).The model.addColumn() method causes a fireTableStructureChanged event to be generated which causes the TableColumns to be recreated and therefore they default back to their default sizes.
    So you need to prevent the columns from being recreated. You do this by adding:
    JTable table = new JTable(....);
    table.setAutoCreateColumnsFromModel(false);But now you are responsible for adding table columns to the table manually. So your code would be something like;
    int index = model.getColumnCount();
    model.addColumn(...);
    TableColumn tc = new TableColumn(index);
    tc.setHeaderValue("" + index);
    table.addColumn( tc );

  • How to set initial column widths for a table

    What I'd like to do is to control the initial column widths for a table.
    I'm building the table by using a class which extends AbstractTableModel. This class takes care of setting the headers and reading the data for the table.
    If I do the following:
    VarTableModel vtm = new VarTableModel(vi);
    JTable jt = new JTable(vtm);
    JScrollPane jsp = new JScrollPane(jt);
    frame.getContentPane().add(jsp);
    frame.setVisible(true);
    I will see a table in my window. The widths of the columns are equal and are a function of the horizontal dimension of the window.
    I have tried to set the width of a column by doing the following:
    TableColumn aColumn;
    aColumn = jt.getColumn(vtm.getColumnName(0));
    aColumn.setWidth(40);
    But this has no effect on what gets displayed. I can force the widths that I want by using 'setMaxWidth' but this has the unfortunate side effect of not allowing the user to make the column wider if they want.
    What I'd like is a way to specify the widths of the columns when initially displayed and then let the user adjust to their liking.
    I'm sure that there is a way to do this, but I don't seem to understand where to intervene in the process to produce the effect that I want.
    Any help or suggestions will be greatly appreciated!

    Table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    add this line and try ur codeThanks for the suggestion! Unfortunately, it doesn't seem to do the trick. Here is an abbreviated segment of my code:
    vtm = new VarTableModel(vi);
    JTable jt = new JTable(vtm);
    // we want a horizontal scrollbar, so turn resizing off
    // and we want to control column widths
    jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    aColumn = jt.getColumn(vtm.getColumnName(0));
    aColumn.setWidth(40);
    . // same kind of thing for each column
    aColumn = jt.getColumn(vtm.getColumnName(4));
    aColumn.setWidth(400);
    JScrollPane jsp = new JScrollPane(jt);
    frame.getContentPane().add(jsp);
    frame.setVisible(true);
    If I do the above, the table gets displayed with each of the five columns the exact same width. So, the sizing of the columns is happening somewhere else despite turning auto resizing off.
    Where is that occurring and how can I intervene so that I can control the widths of the columns on initial display and still allow the user to adjust the widths if they so choose?

  • How to change the column width in Smartforms..?

    Hi All..
    I need to change the column width in a smartform.
    The requirement has been mentioned as follows...
    Adjust the column width of the following columns:
    MATERIAL: 14 char
    DESCRIPTION: 20 char
    How to perform this..??
    Where can i find the column width of various columns of a smartform..???
    Please Help me...
    Regards
    Pavan

    In the SMART Forms, you would have created a Table object and specified the line width and divided that into no. of columns that you want, you have to mandatorily specify the width of each column so that total of column width will be equal to that of the line width.
    When you double click on the Table object, you can TABLE tab on the right side. If you can't see the line / columns details, click on the DETAILS button.
    Regards,
    Ravi
    Note - Please mark all the helpful answers

Maybe you are looking for