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.

Similar Messages

  • Adjusting JTable column width

    I want to set the width of one column and let the other columns have the rest of the width in the table. Right now I am doing this by setting the width of each column. But can someone please tell me if it is possible to do programmatically.
    I have tried to use sizeWidthToFit(). But it does not work. I have also set the headers to null.
    Thanks,
    sjl

    hi Mark,
    you can try C_CELL_TD_EXTEND
    e.g C_CELL_TD_EXTEND = 'width=200'.
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/b1089290-0201-0010-288c-98e4d26487ee
    Extension of TD tag
    Here you can set the properties such as the width, height, alignment or color of the cell. This parameter is not normally set because many of the properties are already defined when the style is defined.
    hope this helps.

  • I want to adjust the column width of "From", "Subject" and "Date". in the AT&T email within Firefox browser

    My computer runs under Windows Vista Home Premium, and Firefox browser 3.6.13. Within the Firefox browser, it shows an AT&T email window (www.sbc.yahoo.com). There are several columns such as subject, date, etc. I was able to adjust such column width before. Now I cannot do it. (Also I can adjust column width if I run in the Internet Explorer. I have another computer running Window 7 professional, same set up with Fire Fox and AT&T email, I am able to adjust the column width so I can show the full subject line.

    Start Firefox in [[Safe Mode]] to check if one of the add-ons is causing the problem (switch to the DEFAULT theme: Tools > Add-ons > Themes).
    * Don't make any changes on the Safe mode start window.
    See:
    * [[Troubleshooting extensions and themes]]
    You can also try to set the pref layout.frames.force_resizability to true on the about:config page.
    See also http://kb.mozillazine.org/about%3Aconfig

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

  • Is there a way to adjust the column width of only one cell

    Using iWork '09: specifically Keynote '09 and want to adjust the column width of just one cell in the column, not the other cells in the whole column just this one individual cell. Have no idea how to do it though. Checked the manual and this discussion group as well as youtube and found nothing.

    Scott Fox wrote:
    Using iWork '09: specifically Keynote '09 and want to adjust the column width of just one cell in the column, not the other cells in the whole column just this one individual cell. Have no idea how to do it though. Checked the manual and this discussion group as well as youtube and found nothing.
    Perfectly normal, this feature is unavailable.
    Keynote, Numbers and Pages use quite the same code to build tables which are in fact spreadsheets and this code doesn't offer this feature.
    As you don't give many details, look at the merge cells feature.
    Given your exact problem, it may be a soluce.
    Yvan KOENIG (VALLAURIS, France) mercredi 7 octobre 2009 18:26:05

  • Fix ALV column width independent of content

    Hi All,
    I need to fix ALV column width independent of content. If I set the width of column as 10 and when the content is 20 characters long, the column expands to 20. I want the width of column to be fixed irrespective of content. I tried all properties available for ALV column and table but couldn't figure it out. We are on ECC 6.0 ENHP4. Any ideas how to achieve this.
    Thanks,
    Tom

    I believe that I have done this setting fixed layout to true, and then manually setting the column widths in the code.
    lo_model->if_salv_wd_table_settings~set_fixed_table_layout( abap_true )
    lt_alv_column_table = lo_alv_model->if_salv_wd_column_settings~get_columns( ).
    LOOP AT lt_alv_column_table INTO ls_alv_one_column.
    ls_alv_one_column-r_column->set_width( '90' ).

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

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

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

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

  • Proglem with JTable column width

    Hi Friends,
    I'm using jtable. For that table, i want to set the column width. But it is not working. Here is my code...
    class ProcessTable extends JTable {
    ProcessTable(){
    getTableHeader().setResizingAllowed(true);
    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         TableColumn col = getColumnModel().getColumn(0);
         col.setPreferredWidth(100);
         col = getColumnModel().getColumn(1);
         col.setPreferredWidth(130);
    }

    Either don't change the TableModel or make sure you don't call fireTableStructureChanged() but fireTableDataChanged() (meaning loading the data doesn't change the columns, just the rows).
    Or you can use JTable.setAutoCreateColumnsfromModel(false) and create the TableColumnModel yourself.

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

  • JTable column width

    I am having trouble initializing column widths in my JTable.... after I create the table I use JColumn.setWidth(int) to set the width of every column. It doesn't work! the table sets
    default equal widths. Am trying like this :
         if(e.getSource()==column)
         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);     
    for(int i=0;i<table.getColumnCount();i++)
    table.getColumnModel().getColumn(i).setPreferredWidth(Integer.parseInt(column.getText()));
    modelTable.fireTableStructureChanged();     
         }

    Instead of setPreferredWidth(..), try setMaxWidth(..)
    table.getColumnModel().getColumn(i).setMaxWidth(Integer.parseInt(column.getText()));
    I does the trick for me.

  • Fitting JTable column widths

    Hi,
    I have a JTable that it's columns are in AUTO_RESIZE_OFF mode. The table is in a JScrollPane that it's scrolls are shown when needed. The problem is that the table columns don't fill the scroll pane (horizontally) and because I'm using a layout I don't know that scroll size until the component appears. I need to set the column widths before the table appears.
    Is there a solution for this problem?
    Thanks,
    Shai

    To fill all the scrollpane you must use AUTO_RESIZE_ALL_COLUMNS or another mode different from AUTO_RESIZE_OFF. But in this case, rhe horizontal scrollbar won't appear.
    I found a workaround to show the scrollbar when the viewport width is smaller than the preferred width of the JTable.
    Denis

Maybe you are looking for

  • Many contacts are not visible to alphabetical browse on Contacts after update to OS 10.2 on the Z10

    After updating to 10.2 on Z10  many contacts do not appear on the Contacts list, but if I search for them, I get them one at a time. I can't browse for them, but they are still in a file somewhere. That file is no longer fully connected to the Contac

  • I am utterly unable to make iMovie 10 do anything at all!

    "Up"graded to iM 10 after updating my OS to Mavericks, and cannot open any Events, cannot get iM 10 to even recognize any of my old projects, can't even get the stupid screen to re-size, can't do a single solitary thing with it but open it and close

  • How to truncate a partition in owb

    I wonder how can i achieve truncating a partition before loading into this target table. I found this pre-mapping prcess where we have this option of truncating a table, but how can i just truncate a partition within a table in a mapping? please advi

  • Account Billing Address Insert

    I am trying to insert an Account along with a Billing Address into OnDemand. I don't always have, or want to insert all the Billing Address information, but the service seems to require this. This problem can only be overcome by adding Accounts and B

  • Store analysis

    Hi, We are running Messaging Server: Sun Java(tm) System Messaging Server 6.3-4.01 libimta.so 6.3-4.01 We are planning to implement message expire rule by age and implement quota in our existing setup. We need to get some analysis on store done to de