Resize Jtable in panel (using setPreferredScrollableViewportSize)

Hi,
I have a JPanel which I've added a JTable. I have set it up with
               table.setPreferredScrollableViewportSize(new Dimension(900,450));
On the click of a button I want to call
               table.setPreferredScrollableViewportSize(new Dimension(900,100));
validate();
But the validate doesn't seem to work ?
Basically the idea is that I shrink the table and put another edit panel below the table for the selected row of the table.
Any ideas ? Is setPreferredScrollableViewportSize the correct way to resize the JTable ?
Mark.

Sorry I figured it out.
My table was in a panel, I resized the table but not the panel.
by changing the preferredsize of the panel I got the effect I was looking for.

Similar Messages

  • Resizing variable size panel with JScrollPane

    I have a JPanel which contains four radio buttons. Selecting each of them opens another panel which are of different sizes.
    These panels open in the same parent panel below the radio button panel.
    However these panels contain large no of components. i.e. the final size of the main panel varies depeding on which button is selected.
    I am using a JScrollPane to view them properly.
    However, I am facing problem while resizing the main panel. If I mention the preferred size of the JScrollPane, the main panel on maximizing, shows this scrollpane with the size mentioned and does not get maximized as the parent panel.
    If I don't mention the scrollpane size, resizing the main panel don't show the scrollbars.
    what is the correct way to implement a JScrollpane in this case?
    Also can anyone tell me what is the exact deifference between setSize() and setPreferredSize()?

    i think you are looking for this if i got it right.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ButtonGroup;
    import javax.swing.ComboBoxModel;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import javax.swing.JToggleButton;
    import javax.swing.WindowConstants;
    public class TestVariablePanelSize extends javax.swing.JPanel
        private JPanel buttonPanel;
        private JRadioButton jRadioButton3;
        private JRadioButton jRadioButton4;
        private JLabel jLabel3;
        private JPanel displayPanel2;
        private JLabel jLabel2;
        private JLabel jLabel1;
        private JPanel jPanel1;
        private ButtonGroup buttonGroup1;
        private JScrollPane jScrollPane1;
        private JToggleButton jToggleButton1;
        private JComboBox jComboBox1;
        private JPanel topPanel;
        private JPanel displayPanel;
        private JPanel parentPanel;
        private JRadioButton jRadioButton2;
        private JRadioButton jRadioButton1;
        JFrame container;
        public static void main(String[] args)
            JFrame frame = new JFrame();
            frame.getContentPane().add(new TestVariablePanelSize(frame));
            frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        public TestVariablePanelSize(JFrame frame)
            super();
            container = frame;
            initGUI();
        private void initGUI()
            try
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                System.out.println("screenSize" + screenSize);
                container.setMaximumSize(screenSize);
                final ErrorReportImportPanel errorReportPanel = new ErrorReportImportPanel();
                BorderLayout thisLayout = new BorderLayout();
                container.setLayout(thisLayout);
                container.setPreferredSize(new java.awt.Dimension(655, 365));
                container.setFocusable(false);
                // START >> jScrollPane1
                // START >>
                buttonGroup1 = new ButtonGroup();
                // END << buttonGroup1
                jScrollPane1 = new JScrollPane();
                container.add(jScrollPane1, BorderLayout.NORTH);
                jScrollPane1.setPreferredSize(new java.awt.Dimension(602, 285));
                // START >> parentPanel
                parentPanel = new JPanel();
                jScrollPane1.setViewportView(parentPanel);
                GridBagLayout parentPanelLayout = new GridBagLayout();
                parentPanelLayout.columnWeights = new double[]{0.1};
                parentPanelLayout.columnWidths = new int[]{7};
                parentPanelLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0};
                parentPanelLayout.rowHeights = new int[]{33, 23, 186, 26};
                parentPanel.setLayout(parentPanelLayout);
                // parentPanel.setPreferredSize(new java.awt.Dimension(652, 371));
                // START >> topPanel
                topPanel = new JPanel();
                parentPanel.add(topPanel, new GridBagConstraints(
                    0,
                    0,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.NORTH,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                // START >> jComboBox1
                ComboBoxModel jComboBox1Model = new DefaultComboBoxModel(new String[]{"Item One", "Item Two"});
                jComboBox1 = new JComboBox();
                topPanel.add(jComboBox1);
                jComboBox1.setModel(jComboBox1Model);
                jComboBox1.setPreferredSize(new java.awt.Dimension(75, 20));
                // END << jComboBox1
                // END << topPanel
                // START >> buttonPanel
                buttonPanel = new JPanel();
                parentPanel.add(buttonPanel, new GridBagConstraints(
                    0,
                    1,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.NORTH,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                // START >> jRadioButton1
                jRadioButton1 = new JRadioButton();
                buttonPanel.add(jRadioButton1);
                jRadioButton1.setText("jRadioButton1");
                jRadioButton1.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent evt)
                        displayPanel.setVisible(true);
                        // displayPanel2.setVisible(false);
                        // parentPanel.remove(displayPanel2);
                // END << jRadioButton1
                // START >> jRadioButton2
                jRadioButton2 = new JRadioButton();
                buttonPanel.add(jRadioButton2);
                jRadioButton2.setText("jRadioButton2");
                jRadioButton2.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent evt)
                        displayPanel2.setVisible(true);
                        displayPanel.setVisible(false);
                        parentPanel.remove(displayPanel2);
                // END << jRadioButton2
                // START >> jRadioButton3
                jRadioButton3 = new JRadioButton();
                buttonPanel.add(jRadioButton3);
                jRadioButton3.setText("jRadioButton3");
                // END << jRadioButton3
                // START >> jRadioButton4
                jRadioButton4 = new JRadioButton();
                buttonPanel.add(jRadioButton4);
                jRadioButton4.setText("jRadioButton4");
                // END << jRadioButton4
                // END << buttonPanel
                buttonGroup1.add(jRadioButton1);
                buttonGroup1.add(jRadioButton2);
                buttonGroup1.add(jRadioButton3);
                buttonGroup1.add(jRadioButton4);
                // START >> displayPanel
                displayPanel = new JPanel();
                parentPanel.add(displayPanel, new GridBagConstraints(
                    0,
                    2,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.NORTH,
                    GridBagConstraints.BOTH,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                displayPanel.setVisible(false);
                // START >> jLabel2
                jLabel2 = new JLabel();
                displayPanel.add(jLabel2);
                jLabel2.setText("displayPanel");
                jLabel2.setPreferredSize(new java.awt.Dimension(462, 152));
                jLabel2.setOpaque(true);
                jLabel2.setBackground(new java.awt.Color(128, 128, 255));
                jLabel2.setVisible(false);
                // END << jLabel2
                // END << displayPanel
                // START >> displayPanel2
                displayPanel2 = new JPanel();
                parentPanel.add(displayPanel2, new GridBagConstraints(
                    0,
                    2,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.CENTER,
                    GridBagConstraints.BOTH,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                displayPanel2.setVisible(false);
                // START >> jLabel3
                jLabel3 = new JLabel();
                displayPanel2.add(jLabel3);
                jLabel3.setText("displayPanel2");
                jLabel3.setOpaque(true);
                jLabel3.setBackground(new java.awt.Color(0, 128, 192));
                jLabel3.setPreferredSize(new java.awt.Dimension(460, 171));
                // END << jLabel3
                // END << displayPanel2
                // START >> jToggleButton1
                jToggleButton1 = new JToggleButton();
                parentPanel.add(jToggleButton1, new GridBagConstraints(
                    0,
                    3,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.WEST,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                jToggleButton1.setText("jToggleButton1");
                // END << jToggleButton1
                // START >> jPanel1
                jPanel1 = new JPanel();
                parentPanel.add(jPanel1, new GridBagConstraints(
                    0,
                    4,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.CENTER,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                // START >> jLabel1
                jLabel1 = new JLabel();
                jPanel1.add(jLabel1);
                jLabel1.setText("Another Panel");
                jLabel1.setPreferredSize(new java.awt.Dimension(469, 87));
                jLabel1.setBackground(new java.awt.Color(0, 128, 0));
                jLabel1.setForeground(new java.awt.Color(0, 0, 0));
                jLabel1.setOpaque(true);
                // END << jLabel1
                // END << jPanel1
                // END << parentPanel
                // END << jScrollPane1
            catch (Exception e)
                e.printStackTrace();
    }

  • Dynamically resize JTable cell to fit a JList

    Hi!
    I've been banging my head trying to add some dynamic behavior to a TableCellEditor. In short I'm trying trying to make it resize the height of the current row (the one it is in) to reflect the changes made to the JList used to let the user edit the cells value (which is a list of items).
    I've come across some threads dealing with the problem of resizing a cell to fit its content. This however is usually only done once (in the 'getTableCellEditorComponent' function) and so only provides half the answer. Also, since the editor is only active during cell editing I've been trying to make it revert to the old cell height after the editing is done.
    So far I have not come up with any decent solution to this problem and was hoping someone out there might have an idea or have read something similar and can point me to something helpful... anyone?
    Cheers!
    Teo

    The Swing tutorial on[url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables shows how to dynamically change the size to Table Columns.
    If you need help calculating the acutal size then try searching the forum. Using keywords "resize jtable column" (keywords I took directly from your topic title) I found some promising postings.

  • Resize photos for online use

    I have been trying all afternoon to resize photos for online use and can not follow directions given.  I know it must be simple but I am stumped.  I would like to speak to a real person and I'm sure my problem will be solved in less than five minutes.  PLEASE do not tell me to follow guidelines; I have tried that.
    Kay Wilhelm

    Hi Kay,
    As an example, let's say we're trying to prepare this 1000x664 pixel, 1MB image for online posting. 
    If the website you're posting to is giving you a maximum dimension, for example that the image has to be 600 pixels across or less, then follow these 4 steps:
    1. Go to File -> Save for Web
    2. In the Save for Web panel, look for the Image Size boxes. 
    3. Enter the desired dimension.  For example, if the website you're trying to upload to requires that images be 600 pixels across, enter 600 in the Width box.  The height should recalculate automatically. 
    4. Hit the Save button.  You will now have an image saved to the required pixel dimensions!
    If the requirement is for a maximum file size, rather than specific file dimensions, you would follow a different procedure.  If we were trying to resize the same 1000x664 pixel, 1MB image to a size of 100KB or less, we would follow these steps:
    1. Go to File -> Save for Web
    2. In the upper right hand corner of the Save for Web panel, make sure the format is set to JPEG.  Our original image was a PNG, which tends to have a larger file size.  JPEG images tend to have a smaller file size.
    3. In the Save for Web panel, look for the projected size of the file as saved with the current settings.  This is below the lower left hand corner of the image.  In this case, it is 170KB, which is higher than our desired maximum size of 100KB.  
    3.  The easiest way to control the file size at a given pixel dimension is by reducing the image quality.  The controls for image quality are in the upper right hand corner of the Save for Web panel.  The default setting for JPEG exports is 60%. 
    4.  You will need to determine how far you want to reduce the image quality in your particular case.  In this example, we can reduce the quality from 60% to 40% without affecting the visible image quality too much.  Setting the quality to 40% reduces the image size to 99KB, which is below our maximum of 100KB.
    5. When you are satisfied with the quality settings, press Save to save your image. 
    Hope this helps!

  • The CC control panel use to show my 4 applications CC, CS6, LR5 and Bridge, now LR5 is no longer showing up. I pay for the photographer bundle, which includes LR5 and CC, why has it been dropped off? Is there any way to bring it back in the panel, because

    The CC control panel use to show my 4 applications CC, CS6, LR5 and Bridge, now LR5 is no longer showing up. I pay for the photographer bundle, which includes LR5 and CC, why has it been dropped off? Is there any way to bring it back in the panel, because in the listed applications which can be added below it is not listed.  Thanks!

    If you're a paying Creative Cloud member, you may not see Lightroom in the Creative Cloud if your computer doesn't meet the minimum system requirements. Check to make sure that your system meets the minimum requirements for the latest release of Lightroom.
    If you're using a trial version of Creative Cloud, the Lightroom trial is not available through Creative Cloud. It is, however, available as a stand-alone trial. See Install Lightroom trial | Creative Cloud membership. 
    Please refer to : Lightroom and Creative Cloud FAQ
    Regards
    Rajshree

  • Change BG color of Panel using script (AS3)

    Dear, all
    I am a newbies in Flex. Now I have some trouble with thw
    sample thing.
    That is how can I change BackgroungColor of panel using
    script(AS3)
    I can do it by mxml BUT!! I really need to change it using
    AS3. Does you know what should I do NEXT.

    When you lookup a component in FB3 help sys, if you see it
    under styles, then you need to use setStyle() in AS, if you see it
    as a property, just use dot notation.

  • Problem in Printing jtable swing component using dot martix Epson printer

    Hello,
         I am devoloping desktop aplication using swing.In which i want to prit jtable on paper using dot matrix printer.
    It works well if i am not chnging the font.But if i changed the font (to my local language or any any other language)
    the printing text in table gets Blur (Characters in the text get ovewrites to each other and it become hard to recognize).
    Please help me in this problem.I am trying this from more than two days but not yet found the solution.
    Thank you,
    Dattatray

    Joerg22 wrote:
    Windows allows to change the keyboard to Hindi, but not to Marathi.
    But I wonder why you are changing the focus. The problem arose when you were setting a particular font. So the first question is: Can you do without that font? Meaning: are the Devanagari characters an option?No Devanagari characters are not option.I have to use Marathi language in my application for displaying to the user and taking value from user.See perblem come into picture when i am using setFont method.i did one expriment using characters 0900-097F.For one jtext field i have set text as "\u0937\u0937\0937".In gui i saw the corresponding marathi characters for it (here i did not used any set font method).Also after printuing that on paper i saw marathi text.As i mentioned in previous post i was not able to use "\u0937\u0937\0937" this in table.It might be some mistake in string formation.But i am sure it will work.Only need to check how to form string.
    In this case Only problem is that how to take input from user.As user will not gonna input "\u0900".He will laways enter abcd....I have to interprete them into unicode.Please correct me if i am thinking wrong.
    I will try by changing the language of keyboard to hindi and get back.
    Edited by: Ashtekar on Aug 9, 2010 2:13 AM
    Edited by: Ashtekar on Aug 9, 2010 2:13 AM

  • Is this possible to panel using CS4 like CS5

    Hi gurus.
    I have used Photoshop CS4. I have created both CS4 & CS5 Extensions Panel using from Adobe Confirator I & II .
    In Photoshop CS5 Extensions Panel HTML widget shows Image & Text in HTML window.
    Hence In Photoshop CS4 Extensions Panel HTML widget doesn't shows image in HTML window only shows Text fields.
    Is this possible to show image in HTML Widget CS4....?
    Thanks in advance.
    -yajiv

    Hi yajiv,
    When create extensions for CS4 Photoshop, you have to use "Configurator 1.0".
    Its not include HTML widget, So you can't use it for CS4 Extensions.
    and... you should better to ask this kind of question in Configurators forum.
    http://forums.adobe.com/community/labs/configurator/
    Ten.

  • Want to resize JTable after run programe by mouse

    I want to resize JTable by mouse after run programe.
    (want to resize Jtable anytime)
    please help me. thank you

    You cannot do that directly, you can only cause the container which holds the JTable to change size. As long as that container has a LayoutManager like BorderLayout then the JTable will resize with the container (Like a JFrame)

  • Resizing with my mouse using touch pad mac book pro does not work. how can i correct this problem?

    resizing with my mouse using touch pad mac book pro does not work. how can i correct this problem?

    See:
    * [/questions/777886]

  • User cannot resize jTables� columns

    Hello,
    Using NetBeans IDE 3.5.1, I built a jTable, controlled by a
    JScrollpane.
    My problem is that the user cannot resize the jTables� columns.
    Maximum details:
    1.     jtablewidth is set to a fixed value according to internal data:
    JTable1.setPreferredSize( new Dimension(tableWidth, i_TableHeight));
    2.     columnwidth is set according to internal data:
    Col = JTable1.getColumnModel().getColumn(i);
    Col.setWidth(width);
    Col.setResizable(true);
    Col.setMinWidth(width);
    3.     jTable header details:
    JTableHeader anHeader = JTable1.getTableHeader();
    anHeader.setReorderingAllowed(false);
    anHeader.setResizingAllowed(true);
    4.     JTable1.getTableHeader().setResizingAllowed(true);.
    5.     Initial declerations:
    a.     JTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
         JTable1.setColumnSelectionAllowed(true);
         JTable1.setDragEnabled(true);
         JTable1.setPreferredScrollableViewportSize(new
    java.awt.Dimension(650, 500));
         JTable1.setPreferredSize(new java.awt.Dimension(1200, 409));
         JTable1.setRequestFocusEnabled(false);
    b.     JScrollPane1.setMaximumSize(new java.awt.Dimension(750, 412));
         JScrollPane1.setPreferredSize(new java.awt.Dimension(750,
    412));
         JScrollPane1.setViewportView(JTable1);
         JScrollPane1.setAutoScolls(false);
    c.     Jtable.autoCreateColumnsFromModel (true);
    Thanks alot,
    Itay

    Columns resizing works by default. You don't need to do anything special.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Can't resize JTable

    In my code I display in a Panel a JScrollPane containing a table.
    When I resize the panel, the table is always the same height. I want the table to fill all the panel.
    Here is my code:
    public HistComm() {
    super(new GridLayout(1,0));
    table = new JTable(model);
    table.setRowSelectionAllowed(true);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    model = (DefaultTableModel)table.getModel();
    model.addColumn("Name");
    model.addColumn("Method");
    // table.setPreferredScrollableViewportSize(new Dimension(500,70));
    scroll_pane = new JScrollPane(table);
    add(scroll_pane);
    }

    Result won't be the same if you say super(new BorderLayout);
    but later when you add your ScrollPane to Panel you should try with:
    add(scrollPane, BroderLayout.CENTER);
    This will do the trick!!
    Zorro (javagod)

  • Resize JTable in JTabbedPane

    Given the FileTableDemo from the Java Foundation Class in a Nutshell book.(O'Reilly) Chapter 3 page 51 in my addition.
    I have modified the example to place the JTable in a JTabbedPane. Now when the window (JFrame) is resized by the user the JTable no longer resizes. How do I passing the "resizing" into the component (JTable) placed in the JTabbedPane?
    Here is the code: My deviation from the example is enclosed in "///////////KBS" and of course the line frame.getContentPane().add(myTP, "Center"); where "pane" has been replaced with "myTP"
    Thanks Brad
    import javax.swing.*;
    import javax.swing.table.*;
    import java.io.File;
    import java.util.Date;
    public class FileTableDemo
    public static void main(String[] args)
    // Figure out what directory to display
    File dir;
    if (args.length > 0)
    dir = new File(args[0]);
    else
    dir = new File(System.getProperty("user.home"));
    // Create a TableModel object to represent the contents of the directory
    FileTableModel model = new FileTableModel(dir);
    // Create a JTable and tell it to display our model
    JTable table = new JTable(model);
    JScrollPane pane = new JScrollPane(table);
    pane.setBorder(BorderFactory.createEmptyBorder(60,20,20,20));
    ////////KBS
    JTabbedPane myTP = new JTabbedPane();
    JPanel myOne = new JPanel();
    JPanel myTwo = new JPanel();
    myOne.add(pane);
    myTP.add("One", myOne);
    myTP.add("Two", myTwo);
    ////////KBS
    // Display it all in a scrolling window and make the window appear
    JFrame frame = new JFrame("FileTableDemo");
    frame.getContentPane().add(myTP, "Center");
    frame.setSize(600, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    // The methods in this class allow the JTable component to get
    // and display data about the files in a specified directory.
    // It represents a table with six columns: filename, size, modification date,
    // plus three columns for flags: direcotry, readable, writable
    class FileTableModel extends AbstractTableModel
    protected File dir;
    protected String[] filenames;
    protected String[] columnNames = new String[] {
    "name",
    "size",
    "last modified",
    "directory?",
    "readable?",
    "writable?"
    protected Class[] columnClasses = new Class[] {
    String.class,
    Long.class,
    Date.class,
    Boolean.class,
    Boolean.class,
    Boolean.class
    // This table model works for any one given directory
    public FileTableModel(File dir)
    this.dir = dir;
    this.filenames = dir.list();
    // These are easy methods
    public int getColumnCount()
    return 6;
    public int getRowCount()
    return filenames.length;
    // Information about each column
    public String getColumnName(int col)
    return columnNames[col];
    public Class getColumnClass(int col)
    return columnClasses[col];
    // The method that must actually return the value of each cell
    public Object getValueAt(int row, int col)
    File f = new File(dir, filenames[row]);
    switch(col)
    case 0: return filenames[row];
    case 1: return new Long(f.length());
    case 2: return new Date(f.lastModified());
    case 3: return f.isDirectory() ? Boolean.TRUE : Boolean.FALSE;
    case 4: return f.canRead() ? Boolean.TRUE : Boolean.FALSE;
    case 5: return f.canWrite() ? Boolean.TRUE : Boolean.FALSE;
    default: return null;
    }

    Well, I didn't find an answer but I did find a solution.
    The JPanel is the problem. I use it to help with layout which is not obvious in this example.
    As you can see in the code the JTable is placed in a JScrollPane which is place in a JPanel which is placed in a JTabbedPane.
    If I use Box instead of JPanel the JTable in the JScrollPane in the Box in the TabbedPane in the JFrame resizes correclty.
    So although JPanel is resizable with setSize it does not get resized when it's JFrame gets resized.
    I would still like to know why?
    ////////KBS
    JTabbedPane myTP = new JTabbedPane();
    Box myOne = Box.createHorizontalBox();
    Box myTwo = Box.createHorizontalBox();
    myOne.add(pane);
    myTP.add("One", myOne);
    myTP.add("Two", myTwo);
    ////////KBS

  • Resize jtable in jscrollpane

    Hi,
    I have a frame containing a JTable and a panel with buttons. When the window gets resized, I would like that the jtable takes the extra space and that the button panel stays the same. How can I do that? The jtable panel is already the "Center" and both panels stay the same...
    Thanks,
    Marie
    Here's the code:
    package test;
    import javax.swing.*;
    import java.awt.AWTEvent;
    import java.awt.event.WindowEvent;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    public class Testframe extends JFrame {
        private JPanel mainPanel = new JPanel();
        private JPanel buttonPanel = new JPanel();
        private JPanel tablePanel = new JPanel();
        //Button panel
        private JButton applyTableBt = new JButton("Generate Table");
        private JButton addBt = new JButton("Add");
        private JButton editBt = new JButton("Edit");
        private JButton deleteBt = new JButton("Delete");
        private JButton matchBt = new JButton("Find");
        private JButton saveBt = new JButton("Save to file");
        private JButton loadBt = new JButton("Load from file");
         * Constructor.
         * @param a_parent Frame
        protected Testframe() {
            enableEvents(AWTEvent.WINDOW_EVENT_MASK);
            try {
                jbInit();
                this.setResizable(true);
                this.setVisible(true);
                pack();
            } catch (Exception e) {
                e.printStackTrace();
         * Initialization of the dialog.
         * @throws Exception
        private void jbInit() throws Exception {
            this.setTitle("Pattern management - CAT");
            Object[][] data = { {"11", "12", "13", "14", "15", "16", "17", "18"},
                              {"21", "22", "23", "24", "25", "26", "27", "28"}
            Object[] names = {"col1", "col2", "col3", "col4", "col5", "col6",
                             "col7", "col8"};
            JTable table = new JTable(data, names);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            //table.setColu
            TableColumnModel colModel = table.getColumnModel();
            for (int i = 0; i < table.getColumnCount(); i++) {
                TableColumn column = colModel.getColumn(i);
                column.setPreferredWidth(511);
            JScrollPane scrollPane = new JScrollPane(table);
            tablePanel.add(scrollPane);
            //Layout = vertical box with vertical gap
            buttonPanel.setLayout(new GridLayout(7, 1, 0, 5));
            buttonPanel.add(applyTableBt);
            buttonPanel.add(addBt);
            buttonPanel.add(editBt);
            buttonPanel.add(deleteBt);
            buttonPanel.add(matchBt);
            buttonPanel.add(saveBt);
            buttonPanel.add(loadBt);
            //mainPanel.setLayout(new BorderLayout());
            mainPanel.add(tablePanel, BorderLayout.CENTER);
            mainPanel.add(buttonPanel, BorderLayout.EAST);
            this.setContentPane(mainPanel);
         * Overrides this class to call the good method when the dialog is closed.
         * @param a_windowE WindowEvent
        protected void processWindowEvent(WindowEvent a_windowE) {
            //If it is a request to close the window (X)
            if (a_windowE.getID() == WindowEvent.WINDOW_CLOSING) {
                cancel();
            super.processWindowEvent(a_windowE);
         * Closes the dialog.
        private void cancel() {
            dispose();
        private static void createAndDisplayFrame() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            new Testframe();
        public static void main(String[] args) {
            createAndDisplayFrame();
    }

    try changing these lines
    mainPanel.add(tablePanel, BorderLayout.CENTER);
    mainPanel.add(buttonPanel, BorderLayout.EAST);
    this.setContentPane(mainPanel);
    to this
    mainPanel.add(buttonPanel, BorderLayout.EAST);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(mainPanel, BorderLayout.EAST);

  • 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

Maybe you are looking for