Results 1 to 7 of 7
  1. #1
    kosmos890 is offline Member
    Join Date
    Apr 2012
    Posts
    40
    Rep Power
    0

    Default How to adjust JTable column width to max string length?

    I will add data dynamically in my JTable.
    Iwant to adjust column 0.
    I used two methods (getWidth1 and getWidth2) to get max width without result.

    What I'm doing wrong?
    Java Code:
    public final class ColumnAdjust extends JFrame {
    
        JTable table;
        DefaultTableModel model;
    
        ColumnAdjust() {
            super("Column djust");
            setSize(300, 500);
    
            String[] header = {"s/n", "Content"};
            model = new DefaultTableModel(header, 0);
            table = new JTable(model);
            add(new JScrollPane(table));
    
            String content = "ABCDEDFGHIJKLMONOP";
    
            for (int i = 0; i < 20; i++) {
                String[] row = {Integer.toString(i), content};
                model.addRow(row);
            }
    //width1=18
          int width=getWidth1();
    //        int width = getWidth2();
    //width2=16
            table.getColumnModel().getColumn(0).setMinWidth(width);
            table.getColumnModel().getColumn(0).setMaxWidth(width);
            table.getColumnModel().getColumn(0).setPreferredWidth(width);
            
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) {
            new ColumnAdjust().setVisible(true);
        }
    
        public int getWidth1() {
    
            int width = 0;
    
            for (int i = 0; i < table.getRowCount(); i++) {
                TableCellRenderer renderer = table.getCellRenderer(i, 0);
                Component comp = renderer.getTableCellRendererComponent(table, table.getValueAt(i, 0), false, false, i, 0);
                int w = comp.getPreferredSize().width;
                width = Math.max(width, w);
            }
            return width;
        }
    
        public int getWidth2() {
            FontMetrics fontMetrics = table.getFontMetrics(table.getFont());
            int width = 0;
    
            for (int i = 0; i < table.getRowCount(); i++) {
                int w = SwingUtilities.computeStringWidth(fontMetrics, Integer.toString(i));
                width = Math.max(w, width);
            }
            return width;
        }

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default Re: How to adjust JTable column width to max string length?

    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    kosmos890 is offline Member
    Join Date
    Apr 2012
    Posts
    40
    Rep Power
    0

    Default Re: How to adjust JTable column width to max string length?

    @DarrylBurke
    Thanks for your reply.
    Table Column Adjuster does what I need.
    My JTable has column which contains a big text.
    For this reason I use a Multiline Cell Renderer.
    Unfortunately I can't use both TableColumnAdjuster and MultilineCellRenderer.

  4. #4
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,234
    Rep Power
    7

    Default Re: How to adjust JTable column width to max string length?

    You should be able to use the Table Column Adjuster. Just invoke the adjustColumn(...) method directly for the columns you want to adjust. For the column with the multiline renderer you just set the width you want to use.

  5. #5
    kosmos890 is offline Member
    Join Date
    Apr 2012
    Posts
    40
    Rep Power
    0

    Default Re: How to adjust JTable column width to max string length?

    @camickr
    Thanks for your reply.

    My JTable has two columns. The first column is the serial number.
    The second column is a big text (The data that I want to show)

    My first thought was to use a Table Row Header. In my opinion this code has a small flaw.
    If you notice row "d", the bottom border line is placed some pixels lower compared with the adjacent cell "d-A"
    (Sorry I'm off topic but this issue concerns me)

    For the column with the multiline renderer you just set the width you want to use.
    You mean to set explicitly column width.
    I want to avoid this. I want the data column to expand to the whole panel and s/n column to occupy the minimum necessary width

    Now I use fixed width to s/n column. Here is my table cellrenderers.

    Serial number column
    Java Code:
    public class AlignCenterTableCellRenderer extends DefaultTableCellRenderer {
    
        public AlignCenterTableCellRenderer() {
            setHorizontalAlignment(JLabel.CENTER);
        }
    
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {      
            
            Color background = table.getTableHeader().getBackground();        
            this.setBackground(background);
            
            if (value != null) {
                setText(Integer.toString(row+1));
            } else {
                setText("");
            }
            return this;
        }
    }
    Data column
    Java Code:
    public class MultiLineTableCellRenderer extends JTextArea implements TableCellRenderer {
    
        private List<List<Integer>> rowColHeight = new ArrayList<>();
    
        public MultiLineTableCellRenderer() {
            setLineWrap(true);
            setWrapStyleWord(true);
            setOpaque(true);
        }
    
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    
            if (isSelected) {
                setForeground(table.getSelectionForeground());
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            }
            setFont(table.getFont());
    
            if (hasFocus) {
                setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
                if (table.isCellEditable(row, column)) {
                    setForeground(UIManager.getColor("Table.focusCellForeground"));
                    setBackground(UIManager.getColor("Table.focusCellBackground"));
                }
            } else {
                setBorder(new EmptyBorder(1, 2, 1, 2));
            }
    
            if (value != null) {
                setText(value.toString());
                
            } else {
                setText("");
            }
            adjustRowHeight(table, row, column);
    
            return this;
        }
    
        private void adjustRowHeight(JTable table, int row, int column) {
           
            int cWidth = table.getTableHeader().getColumnModel().getColumn(column).getWidth();
            setSize(new Dimension(cWidth, 1000));
            int prefH = getPreferredSize().height;
            while (rowColHeight.size() <= row) {
                rowColHeight.add(new ArrayList<Integer>(column));
            }
            List<Integer> colHeights = rowColHeight.get(row);
            while (colHeights.size() <= column) {
                colHeights.add(0);
            }
            colHeights.set(column, prefH);
            int maxH = prefH;
            for (Integer colHeight : colHeights) {
                if (colHeight > maxH) {
                    maxH = colHeight;
                }
            }
            if (table.getRowHeight(row) != maxH) {
                table.setRowHeight(row, maxH);
            }
        }
    }

  6. #6
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,234
    Rep Power
    7

    Default Re: How to adjust JTable column width to max string length?

    Use the following on the table:
    Java Code:
    table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    then set the width of the first column. Then the last colum should resize as the panel resizes.

  7. #7
    kosmos890 is offline Member
    Join Date
    Apr 2012
    Posts
    40
    Rep Power
    0

    Default Re: How to adjust JTable column width to max string length?

    @camickr
    Thanks for your reply

    I test all JTable options.
    I think that JTable.AUTO_RESIZE_ALL_COLUMNS and JTable.AUTO_RESIZE_LAST_COLUMN have the same effect in my JTable
    Java Code:
    private void initTable() {
    
            initModel();
    
            table = new JTable(model);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    //        table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
            table.setAutoCreateColumnsFromModel(true);
    //        table.setDefaultRenderer(String.class, renderer);
    
            MultiLineTableCellRenderer multiLineRenderer = new MultiLineTableCellRenderer();
            DefaultTableCellRenderer centerRenderer = new AlignCenterTableCellRenderer();
    
            table.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
            table.getColumnModel().getColumn(1).setCellRenderer(multiLineRenderer);
    
            TableRowSorter<? extends TableModel> sort = new TableRowSorter<>(model);
            sort.setSortable(0, false);
            table.setRowSorter(sort);
    
            table.getTableHeader().setReorderingAllowed(false);
            table.getTableHeader().setResizingAllowed(false);
    
            int width=80;
            TableColumn column = table.getColumnModel().getColumn(0);
            column.setPreferredWidth(width);
            column.setMinWidth(width);
            column.setMaxWidth(width);
        }
    
        private void initModel() {
    
            model = new DefaultTableModel() {
                @Override
                public Class<String> getColumnClass(int columnIndex) {
                    return String.class;
                }
    
                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
    
            Object[][] data;
            data = null;
            String[] COL_NAMES = {"S/N", "Data"};
    
            model.setDataVector(data, COL_NAMES);
        }

Similar Threads

  1. set column width in Jxl
    By irakli_dev in forum Java Servlet
    Replies: 4
    Last Post: 03-01-2012, 02:54 PM
  2. Column width in excel through jsp
    By syed0071 in forum JavaServer Pages (JSP) and JSTL
    Replies: 1
    Last Post: 07-05-2011, 04:16 PM
  3. Replies: 1
    Last Post: 07-19-2010, 12:31 AM
  4. Replies: 14
    Last Post: 09-18-2009, 04:48 AM
  5. how to retrieve the width of the column
    By katie in forum New To Java
    Replies: 1
    Last Post: 08-06-2007, 10:56 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •