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.

Similar Messages

  • 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

  • OLE2 how to set a column width of an excel file i'm creating?

    how can i set the column width in an excel file i'm creating with ole?
    or even, haw can i set the auto-fix properties?

    Hallo !
    SORRY MY ENGLISH is very BAD.
    I tried to set page header and  footer in Excel sheet with abap ole
    DATA : BEGIN OF enter,
             x(1) TYPE x VALUE '0D',
            END OF enter.
    DATA : format(255) TYPE c.
    FORM set_page_sheet.
      CALL METHOD OF excel 'ActiveSheet' = sheet.
      CALL METHOD OF sheet 'PageSetup' = pagesetup.
      SET PROPERTY OF pagesetup 'Orientation' = xllandscape.
      SET PROPERTY OF pagesetup 'PrintTitleRows' = '$9:$12'.
      CLEAR format.
    ERROR
      CONCATENATE 'PAGESHEET' enter-x 'PAGE &P/&N' INTO format.
    ERROR
      SET PROPERTY OF pagesetup 'RightHeader' = format.
      CLEAR format.
      CONCATENATE ' Text 1 ' enter-x 'Text 2'
    enter-x 'Text 3 ' INTO format.
      SET PROPERTY OF pagesetup 'RightFooter' = format.
      FREE OBJECT pagesetup.
    ENDFORM.                    " set_page_sheet
    Activate report -
    ERROR - The enter-x must by data type c or another then data type x
    Thanks for answer.

  • 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 to set JTable column's color?

    How can I set JTable Columns' color? I only found this class DefaultTableCellRenderer
    which can set cell's color.

    rmalina wrote:
    You are going to need to derive a renderer class for your Column from DefaultTableCellRenderer and override the following function with something like this:
    @Override
         public Component getTableCellRendererComponent(JTable jTable, Object oValue, boolean isSelected, boolean hasFocus, int nRow, int nColumn) {
    super.setForeground(Color.GREEN);
    super.setBackground(Color.GREEN);
    }That would set your column to green.
    Edited by: rmalina on Jul 28, 2008 8:47 AMHow can I know I only change the columns' color instead of other cells?

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

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

  • How to set dynamic column width for analysis item

    Dear Experts,
    I have a query view which is added in the web template as an analysis item. The web item properties on width is not working - I tried entering a value in the width but when I execute the template, the query view's width still stays the same.
    Module com.sap.ip.bi.rig.ColumnWidth don't seem correct because I don't want the column width to be static. As my number of columns may change, I wanted the overall width of my query view to stay the same.
    Appreciate any ideas which can solve this issue
    Thanks and Regards,
    huimin
    BW newbie

    Hi Huimin,
    I don't think it is possible to fix the width of the Analysis webitem since it dynamically adjusts its width based on the text maxlength within its cells. Unless you use com.sap.ip.bi.rig.ColumnWidth where the cols are static, you cannot achieve this.
    Even if you do override the css settings using a cell padding or something, the portal settings would override the same. How about using a Report webitem to insert tables/charts & check if the width can be adjusted here - just a thought.
    --Priya

  • How to set the column width in the PDF exports of interactive reports ?

    Hello,
    I have a huge problem with the PDF export for the Interactive reports. I'm using APEX 3.2.
    I have to produce a PDF report in landscape format that show 21 columns. My problem is that the columns have a ridiculous short width and that the text inside the columns do not wrap in the columns. So I get things like that :
    Date Name
    2011 Leina
    I should see 2011-08-01 and the name Leinad Jan
    I tried several things to format the columns, but none of the them has any effect on the PDF itself.
    1) I used HTML code in the report query. It works well with the interactive report, but display the HTML tags in the PDF.
    2) I used css to set the width of my columns. It works in the interactive report, but not in the PDF, the column width do not change.
    It's like the report do not notice that my page format is Legal 14 x 8.5 (Landscape) and still believe it's 8.5 x 11 (which is "portrait")
    Do you have any idea so set the columkn widths in the reports ?
    Thank you !
    Edited by: leinadjan on Aug 1, 2011 11:15 AM

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

  • How to set equal column width?

    In one report I have 5 tables with different number of rows etc. Is there any possibility or way to make columns inside of it equal? Problem is when report is being exported to .XLS file there are columns which are not visible or sometimes they are merged.
    Is there any quick way to avoid it or they only way is to sit in front of SSRS report few hours and somehow manage to set it manually praying that it will be good?

    Hi glaeran,
    The Excel renderer is primarily a layout renderer. Its goal is to replicate the layout of the rendered report as closely as possibly in an Excel worksheet and consequently cells might be merged in the worksheet to preserve the report layout. As per my understanding,
    this behavior is currently by design. For more information about it, please refer to the link below to see merge cells section:
    http://msdn.microsoft.com/en-us/library/dd255234.aspx
    To avoid the merged cells, if we want to display multiple tables horizontally, the rows of the two tables must be aligned horizontally strictly. If we want to display multiple tables vertically, then the columns of the tables must be aligned vertically strictly.
    The following thread about the similar issue is for your reference:
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/7fbb3d31-fc1b-4c9b-8a7d-afc76cbb0291/ssrs-2012-report-export-to-excel-and-sort-thje-data-on-excel-spreadsheet?forum=sqlreportingservices
    Hope it helps.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support
    Well I do realise the point of "avoiding merged cells" however the points was to find a simply way to avoid it not just a summary "why SSRS report is behaving this way not another". Hoped that there's somekind of solution for my problem since in one report
    as it was said I had to put 5 different tables and every time the report itself is exported to XLS file.. So I thought that maybe it's possible to set same align of cells using table/column/cell properties or whatever so I won't have to spend whole day trying
    to match align of 5 tables column by column.. :)

  • How can i set the column width in the jtable?

    how can i set the column width in the jtable?
    can anybody send me a simple example??

    TableColumn column = table.getColumnModel().getColumn( columnIndex );
    column.setWidth( desiredColumnWidth);
    column.setMinWidth( desiredMinColumnWidth);
    column.setMaxWidth( desiredMaxColumnWidth);

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

  • Can't set custom column widths in JTable

    I'm trying to set custom columns widths. They are set as I wish but then they are reset to default values (all columns have the same size). This is caused by method JFrame.setVisible(true) which invokes JTree.setWidthsFromPreferredWidths(). It can be investigated from following stack trace printed when a column being resized (see below).
    How to prevent this auto width sizing?
    P.S. can't override JTable.setWidthsFromPreferredWidths(); seems it's private
    table = new JTable(model) {
         public void columnMarginChanged(ChangeEvent event) {
              new Exception("stack trace").printStackTrace();
              super.columnMarginChanged(event);
    // setting here custom columns widths via table column model ...java.lang.Exception: stack trace
         at mtu.gui.TrackList$1.columnMarginChanged(TrackList.java:30)
         at javax.swing.table.DefaultTableColumnModel.fireColumnMarginChanged(DefaultTableColumnModel.java:615)
         at javax.swing.table.DefaultTableColumnModel.propertyChange(DefaultTableColumnModel.java:679)
         at javax.swing.event.SwingPropertyChangeSupport.firePropertyChange(SwingPropertyChangeSupport.java:264)
         at javax.swing.event.SwingPropertyChangeSupport.firePropertyChange(SwingPropertyChangeSupport.java:232)
         at javax.swing.table.TableColumn.firePropertyChange(TableColumn.java:249)
         at javax.swing.table.TableColumn.firePropertyChange(TableColumn.java:255)
         at javax.swing.table.TableColumn.setWidth(TableColumn.java:482)
         at javax.swing.JTable$2.setSizeAt(JTable.java:2242)
         at javax.swing.JTable$5.setSizeAt(JTable.java:2336)
         at javax.swing.JTable.adjustSizes(JTable.java:2372)
         at javax.swing.JTable.adjustSizes(JTable.java:2340)
         at javax.swing.JTable.setWidthsFromPreferredWidths(JTable.java:2250) <======
         at javax.swing.JTable.doLayout(JTable.java:2165)
         at java.awt.Container.validateTree(Container.java:1089)
         at java.awt.Container.validateTree(Container.java:1096)
         at java.awt.Container.validateTree(Container.java:1096)
         at java.awt.Container.validateTree(Container.java:1096)
         at java.awt.Container.validateTree(Container.java:1096)
         at java.awt.Container.validateTree(Container.java:1096)
         at java.awt.Container.validateTree(Container.java:1096)
         at java.awt.Container.validateTree(Container.java:1096)
         at java.awt.Container.validateTree(Container.java:1096)
         at java.awt.Container.validateTree(Container.java:1096)
         at java.awt.Container.validateTree(Container.java:1096)
         at java.awt.Container.validateTree(Container.java:1096)
         at java.awt.Container.validate(Container.java:1064)
         at java.awt.Window.show(Window.java:455)
         at java.awt.Component.show(Component.java:1134)
         at java.awt.Component.setVisible(Component.java:1089) <=====
         at mtu.gui.Test.test_03(Test.java:56)
         at mtu.gui.Test.main(Test.java:29)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at com.intellij.rt.execution.application.AppMain.main(Unknown Source)

    When I create the table I have code like this:TableColumn col = getColumnModel().getColumn(2);
    col.setMinWidth(width + 4);
    col.setMaxWidth((int)(width * 1.2));Works just fine for me. The setWidthsFromPreferredWidths() method will use these limits as far as I can see.
    PC&#178;

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

Maybe you are looking for