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

Similar Messages

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

  • Setting the CheckBoxGroup column width

    Hello guys
    I'm using the IWDCheckBoxGroup UI element to display a list of items in my WD application.
    It is working fine, but the project designer asked me, to set it width to 100%, to fill all the screen width ( that is inside a EP IView )
    My problem is: I'm using 3 columns and it does'nt respect the proportion (33%,33%,33%). Put all the columns agrouped in the left ( or center ) is not an option
    Is there any way to set the columns width in the CheckboxGroup?
    Thanks

    Tks for your answer, but it didn't solve my problem.
    I need to use 100% becouse my checkboxgroup MUST to fill all the page width. My problem as I said is that I don't know how to set the width of the columns. I'm using 3 columns in my checkboxgroup and its widht becomes diferent in runtime.
    To create proportional widths I think that I need to set it own width, not the width of the group.
    Is it possible? I read the API and didn't find any references about this
    Tks again

  • What method should be used for resizing the particular JTable Column width

    I have a four table. Only one table which are on top have a table header. I want that when user resize the topmost table with a mouse other table colume also be resized automatically. So I want to know that what method should be used for resizing the particular JTable Column width.
    Thanks
    Lalit

    maybe you can implement a interface ComponentListener as well as ComponentAdapter with your topmost Table.
    for example:
    toptable.addComponentListener(
    new ComponentAdapter(){
    public void componentResized(ComponentEvent e){
    table1.setSize(....);
    table2.setSize(....);
    /*Optionally, you must also call function revalidate
    anywhere;*/
    );

  • How do I set my side column width & height - Help ?

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

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

  • How can I fix the 1st column width (member) in Planning data forms

    Hi all,
    does anybody know a trick, how I can fix the first column width in planning data forms? I need a composite data form (Planning 9.3.1) and the problem is, that in the first form the member names are longer. So Planning sizes the column as it is needed to display the full member name. The member names of the second data form are shorter, so the data entry cells are not exactly among each other for both data forms and that looks terrible....
    Thanks and kind regards
    André

    There are 3 ways of setting the width in webforms:-
    1. There is a global setting for input box length which has a syntax of FormInputBoxLength=30.
    2. When you specify the format for each of the dimensions you can choose to select the width of either a column heading or a row heading. In the following example, each time you specified the dimension ‘Account’ a format would be applied to its header. The syntax for this would be something like… HeaderOptionAccount=Length:50,Style:font-size: 12pt;font-family: calibri
    3. Each column can have its own width specified. The syntax for this can be setting in each of the column’s code. For example C6=Blank,Style:Background-color:rgb(203,218,231);width:3 would just show a thick vertical line as the width is so small.
    You can not set widths in data grids through the normal settings. You can manually change the widths and save the grid though. This can be done in the xml directly. For example… <HDRWIDTH idx=”0″ width=”50″/>.
    Then load the amended xml file back into the system.

  • How to create a dynamic table were the JTable columns keep varying

    How to create a dynamic table were the JTable columns keep varying based on the input to the jtable

    Oooh, I lied. DefaultTableModel has an API for adding and
    removing columns. I didn't know that. You should have read
    the API.
    As for preferring to extend AbstractTableModel rather than
    DefaultTableModel, I think it's more correct. DefaultTableModel
    is a simple implementation of Abstract for basic cases. It isn't
    intended to be extended. I figure most people extending
    DefaultTableModel are also extending JFrame, JPanel, and Thread
    instead of encapsulating the first two and implementing
    Runnable for the third.

  • What is the best column width & font size for an ipad magazine

    I'm creating a magazine that will be shown on the ipad I was wondering what is the best column width and font size to use. If someone has any suggestions I'd love the help.
    thanks,

    You should know how you publish it and what the technical limitations of each type are.
    No one can or will give you any advise to use this or that font. Make several drafts, try it, pass on several drafts to testers and get response.
    If you work with styles, it is then easy for you to change it to the best result with a few clicks.
    Normally a column width with 37 to 45 letters I would personally suggest to be the best width, but opinions are very different on it. The more letters in a line the less readability is given, the less letters the more difficulty you will have to get an even grey factor. (I mean that through space between words some lines become bright others dark, which does not look so fine, I don't know the English technical term for that.)

  • Set the height and width of a new browser window

    I am trying to open a new browser window when the user clicks
    on an audio. The audio will be played in the new browser window.
    The only problem I have is that I cannot set the height and width
    of the new browser window. I need the window to be much smaller.
    How can I do this in flash?

    You need to ask on a JavaScript forum. Java != JavaScript

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

  • JTable - programmatically setting the left column and top row

    I have a JTable in a JScrollPane. I would like to be able to programmatically scroll the table so that a certain column is shown as the left most column in the table, and/or a certain row is shown as the first visible row in the table.
    This is to allow a user to enter a value for the column or row that the want to be on the left or top of the viewport (ie, it is up to the user how they want to move the initially see the table).
    Any help would be much appreciated,
    Cheers, Sean

    Here is one way to do it:
    1) use the getCellRect(row,column,false) to get a rectangle for the cell you wish to display in the upper left corner
    2) use the getVisibleRect() method to get the viewport
    3) set the viewport x and y coordinate to be the same as the cell x,y coordinate
    4) use the scrollRectToVisible method to scroll to the desired area
    For example:
    Rectangle cellRect=myTable.getCellRect(5,10,false);
    Rectangle vis=myTable.getVisibleRect();
    vis.x=cellRect.x;
    vis.y=cellRect.y;
    myTable.scrollRectToVisible(vis);
    Caveat: posted code has not been tested!
    ;o)
    V.V.

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

  • 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

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

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

Maybe you are looking for

  • How to execute a procedure depending on the result of a query?

    Hello, I'm new in ODI. I want to execute a procedure depending on the result of a query Oracle table. We have a Oracle Table whit a column that contains two possibles values. I want read the table, row by row, and depending on this value, execute a P

  • Screws in the Macbook Air

    I removed the screws on the bottom of my computer (don't ask why - long story), but I cannot get them back in, they become super tight. They go in easy about half way, and then it becomes impossible to turn them any more. Are they rigged a certain wa

  • Solaris 10 won't boot:(

    I am running Solaris 10. I get the following mesage after reboot "Select (b)oot or (i) interpreter:" Neither option allows me to boot successfully.What should I do? Is there an emergency repair utility that will fix boot problems?

  • Integrating Trex search With Solution manager

    HI Guys, Please help me with this . Let's say the solution manager is integrated in the SAP Portal and trex is available in the SAP portal. Can we search documents stored in the solution manager via the trex which is integrated in the SAP Portal? Is

  • I can't get icloud to sync ALL of my information, only my calendar!?

    I have opened an account and am successfully using the iCloud calendar which automatically updates between my Mac and iPhone 4, as expected. However, it took a while for this to work and I still can't get any of the other applications, like Reminders