Set column width in JTable

I have two columns in a JTable and I am trying to set the column width for the first.
I am trying to this by
getDataTbl().getColumnModel().getColumn(0).setHeaderValue("Index");
getDataTbl().getColumnModel().getColumn(1).setHeaderValue(" Data ");
int width = ((String)getDataTbl().getColumnModel().getColumn(0).getHeaderValue()).length();
getDataTbl().getColumnModel().getColumn(0).setPreferredWidth(width);
but it doesn't reset the width. I want the first column width to be smaller than the second which should be much larger width.
Any suggessions to this?
Thanks.

Hi there
Use this JTable method
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);This should solve your resize problem
ICE

Similar Messages

  • How can I set column width in JTable?

    How can I set column width in JTable?

    Also, read the JTable API before posting questions. You will find a link to the Swing tutorial on "How to Use Tables", which contains an example of doing exactly this.

  • Setting column width in a command-line program

    Is there a way to send data to the screen in a command-line Java program that will be formatted as a number
    of columns with a set column width? I am looking for something similar to the C++ setw() I/O manipulator
    used in cout.
    Thanks,
    Steve

    If you go to: http://java.sun.com/docs/books/tutorial/essential/io/writingFiltered.html
    it will show you how to subclass a filtered output stream and add your own formatting methods.Then you can chain your new class to System.out
    like this:
    YourFilteredStream yfs = new YourFilteredStream(System.out); .
    Then:
    yfs.yourNewMethod(); goes directly to system out in the new format.

  • Set Column width in query (not using SQL*Plus)

    How can I Set Column width in query
    I understand you can set column width using
    column col1 FORMAT A5
    select col1 from table1;But this only works in SQL*Plus
    I want to be able to do this in a regular SQL query window (not in SQL*Plus), how can I do it.....
    I am using a 'SQL window' in PL/SQL Developer IDE
    and when I use this syntax it says:
    ORA-00900: Invalid SQL statement
    Any suggestions are appreciated...
    thanks,
    M.

    Did you try using RPAD or LPAD functions? They fill the unfilled part of a string with character you provide... either on right or left side depending on what function you use.
    e.g.
    SELECT RPAD('Smith', 10, ' ') Name FROM dual;http://www.adp-gmbh.ch/ora/sql/rpad.html
    Edited by: Zaafran Ahmed on Nov 10, 2010 11:50 AM

  • How to set column widths in tables for selected table only, not globally throughout document?

    I've been utilizing the below script (thank you so much Ramkumar. P!) to set column widths throughout a sizable InDesign book with tables on every page and it is truly a time saver. At this point in time, I have three versions of it because there are different column widths throughout the book. Is it possible to augment the script to run only on a selected text frame (containing a table)? If so, would someone be kind enough to share the augmented script with me? I've been trying to figure out this seemingly simple change through trial and error with no success as yet. I realize this is a totally newbie request and I'm entirely at the mercy of the kindness of the Javascript gods that contribute within this forum. Seeing that in a different post related to this script, one such guru responded to a request as simple as "Where do I put the scripts in InDesign" gave me enough courage to ask for some help! Thank you in advance to anyone willing to provide a solution.
      var myDoc = app.activeDocument;
         var myWidths = [100, 100, 150, 150];
         for(var T=0; T < myDoc.textFrames.length; T++){
             for(var i=0; i < myDoc.textFrames[T].tables.length; i++){
                 for(var j=0; j < myWidths.length; j++){
                     myDoc.textFrames[T].tables[i].columns[j].width = myWidths[j];
         alert("Table width updated successfully...");

    Hello all
    I have the same problem in that I'm not a scripting person, but was able to get the above script working without problem, and it does set irregular table column widths perfectly, so thanks to Ramkumar. P for that.
    BUT, it changes the column width for ALL tables in the document, whereas I would like to just target the selected table.
    Any ideas as to how I might amend this script to achieve this?
    Thx, Christian

  • How to set column width in alvgrid

    hi
    how to set column width in alvgrid.
    thanks.

    Hi,
    Check this,
    REPORT  ztest.
    DATA: BEGIN OF i_scarr_tab OCCURS 0.
            INCLUDE STRUCTURE  scarr.
    DATA: END OF i_scarr_tab.
    DATA: i_scarr LIKE TABLE OF i_scarr_tab WITH HEADER LINE,
          w_scarr LIKE LINE OF i_scarr_tab.
    DATA: o_grid      TYPE REF TO cl_gui_alv_grid,
          o_container TYPE REF TO cl_gui_custom_container.
    DATA: lt_fcat     TYPE lvc_t_fcat,
          ls_layo     TYPE lvc_s_layo,
          ls_sort     TYPE lvc_s_sort,
          lt_sort     TYPE lvc_t_sort,
          ls_fieldcat TYPE slis_t_fieldcat_alv WITH HEADER LINE.
    START-OF-SELECTION.
      CALL SCREEN 9000.
    *&      Module  status_9000  OUTPUT
          text
    MODULE status_9000 OUTPUT.
      SET PF-STATUS '9000'.
      SET TITLEBAR '9000'.
    ENDMODULE.                 " status_9000  OUTPUT
    *&      Module  user_command_9000  INPUT
          text
    MODULE user_command_9000 INPUT.
      CASE sy-ucomm .
        WHEN 'BACK' OR 'EXIT'.
          SET SCREEN 0.
          LEAVE SCREEN.
      ENDCASE.
    ENDMODULE.                 " user_command_9000  INPUT
    *&      Module  init_9000  OUTPUT
          text
    MODULE init_9000 OUTPUT.
      IF o_container IS INITIAL.
        SELECT * FROM scarr INTO CORRESPONDING FIELDS OF TABLE
           i_scarr UP TO 100 ROWS.
        IF cl_gui_alv_grid=>offline( ) IS INITIAL.
    Create a custom container control for ALV Control
          CREATE OBJECT o_container
              EXPORTING
                  container_name = 'CONTROL'.
    Create a ALV Control
          CREATE OBJECT o_grid
              EXPORTING i_parent = o_container.
          PERFORM build_field_catalgue.
          ls_layo-sel_mode = 'A'.
          CALL METHOD o_grid->set_table_for_first_display
            EXPORTING
              i_save          = 'A'
              i_default       = 'X'
              is_layout       = ls_layo
            CHANGING
              it_outtab       = i_scarr[]
              it_fieldcatalog = lt_fcat
              it_sort         = lt_sort[].
        ENDIF.
      ENDIF.
    ENDMODULE.                 " init_9000  OUTPUT
    *&      Form  build_field_catalgue
          text
    -->  p1        text
    <--  p2        text
    FORM build_field_catalgue .
      DATA: ls_fcat TYPE lvc_s_fcat.
      CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
        EXPORTING
          i_program_name         = sy-cprog
          i_internal_tabname     = 'I_SCARR_TAB'
          i_structure_name       = 'SCARR'
         i_client_never_display = 'X'
        CHANGING
          ct_fieldcat            = ls_fieldcat[]
        EXCEPTIONS
          inconsistent_interface = 1
          program_error          = 2
          OTHERS                 = 3.
      IF sy-subrc <> 0.
        MESSAGE 'FCAT Error' TYPE 'I'.
        EXIT.
      ENDIF.
      LOOP AT  ls_fieldcat.
        CLEAR ls_fcat.
        ls_fcat-fieldname = ls_fieldcat-fieldname.     "Fieldname
        ls_fcat-ref_table = ls_fieldcat-tabname.       "DDIC ref struct
        ls_fcat-inttype   = ls_fieldcat-inttype.       "Data type
        ls_fcat-outputlen = ls_fieldcat-outputlen.     "Column width
        ls_fcat-coltext   = ls_fieldcat-seltext_m.     "Column Header
        ls_fcat-seltext   = ls_fieldcat-seltext_m.     "Column Desc
        ls_fcat-ref_field = ls_fieldcat-ref_fieldname. "Reference field
        ls_fcat-ref_table = ls_fieldcat-ref_tabname.   "Reference table
        CASE  ls_fieldcat-fieldname.
          WHEN 'LUGGWEIGHT' OR 'FORCURAM'.
            ls_fcat-edit      = 'X'.
            ls_fcat-do_sum    = 'X'.
          WHEN 'URL'.
            ls_fcat-no_out = 'X'.
          WHEN OTHERS.
            ls_fcat-edit      = ' '.
            ls_fcat-do_sum    = ' '.
        ENDCASE.
        APPEND ls_fcat TO lt_fcat.
      ENDLOOP.
    ENDFORM.                    " build_field_catalgue
    check the programs bcalv_grid*.
    check this link for more detailed example.
    http://www.supinfo-projects.com/fr/2005/alv_display_fr/2/
    Regards
    Sruthi

  • Setting column names in JTable

    can n e one tell me how to set column names for JTable..
    i don't wanna use the JTable constructor ... cuz
    my column names change...

    this is how i did it once...hope it helps
    Vector columnNames = new Vector();
    JTable previewTable = new JTable();
    previewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    previewScrollPane.getViewport().add(previewTable, null);
    int colNo = 2; // i am displaying 2 columns
    columnNames.add("Col One");
    columnNames.add("Col Two");
    String[] tableColumnNames = {"Id Name","Type"};
    DefaultTableModel aModel = (DefaultTableModel) previewTable.getModel();
    aModel.setColumnIdentifiers(tableColumnNames);
    //add data to the table
    .//loop
    aModel.addRow(objects);
    previewTable.revalidate();
    previewTable.setModel(aModel);

  • AUTO_RESIZE jtable set column width by column header

    Do I need to use one of the AUTO_RESIZE methods, the TableColumnModel, or another method in order to set the default width for a column based on the width of the column header.

    This is a simple question with an answer. In a JTable, how do you set the width of a column depending on the width of the column header?

  • Can't set custom column widths in JTable

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

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

  • How to set the column width of JTable

    I want do remember the column width and write it to a file, when the window is started , the column width is read from the file and the table is set as that. I also want the column width is not fixed and can be changed by mouse.But I am always failded.
    How to do? would you please help me!
    Thanks a lots.

    To "remember" the column widths, add a mouse listener to the table header. Upon mouseReleased(), get the column widths and save them to your file. When the application starts next time, get the stored widths and set them using:
    table.getColumn("XXX").setPreferredWidth(...);
    By default, your columns are adjustable, but you can use:
    table.getTableHeader().setResizingAllowed(true);

  • Dynamically setting column width doesn't work all the time

    I wanted to dynamically set the width of a column in a JTable to be half of the width of a another column. This should happen whenever the frame is resized. But somehow I need to tell this twice to Java. If I don't then sometimes the column width isn't set new.
    Is this a Java bug or what?
    public void componentResized(ComponentEvent ce)
         try
              ref.table.getColumn(ref.rsmd.getColumnLabel(5)).setMaxWidth(ref.table.getColumn(ref.rsmd.getColumnLabel(1)).getWidth() / 2);
              ref.table.getColumn(ref.rsmd.getColumnLabel(5)).setMinWidth(ref.table.getColumn(ref.rsmd.getColumnLabel(1)).getWidth() / 2);
              // Again, or it won't work:
              ref.table.getColumn(ref.rsmd.getColumnLabel(5)).setMaxWidth(ref.table.getColumn(ref.rsmd.getColumnLabel(1)).getWidth() / 2);
              ref.table.getColumn(ref.rsmd.getColumnLabel(5)).setMinWidth(ref.table.getColumn(ref.rsmd.getColumnLabel(1)).getWidth() / 2);
         catch(SQLException e)
    }

    Is it possible that your call to
    ref.table.getColumn(ref.rsmd.getColumnLabel(5)).setMinWidth(ref.table.getColumn(ref.rsmd.getColumnLabel(1)).getWidth() / 2);
    is altering the response created by
    ref.table.getColumn(ref.rsmd.getColumnLabel(5)).setMaxWidth(ref.table.getColumn(ref.rsmd.getColumnLabel(1)).getWidth() / 2);
    ? Have you tried calling them once but in the other order? Or just calling the "setMaxWidth" call twice and leaving out the second "setMinWidth"?
    Good luck... :)

  • Column width in JTables.Help needed!!!!

    Hi
    I am trying to print out a JTable and have had a few problems along the way but have managed to solve them all so far apart from this one. When the JTable is shown on screen it doesn't make the columns wide enough . I ahev managed to find some code from these forums but it doesnt resize correctly if the Column headings contain more text than any of the data (If you know what i mean). Below is the code i am using
    public void sizeAllColumnsToFitData (JTable table)  {
        for (int col = 0; col < table.getColumnCount (); col++)  {
          TableColumn curColumn = table.getColumn (table.getColumnName (col));
          if (curColumn == null)
            continue; // not a valid column skip
    //  Translate to the model
          int modelColumn = curColumn.getModelIndex ();
    //  Loop for all rows in this column looking for the widest piece of data
          int maxColumnWidth = 0;
          for (int row = 0; row < table.getRowCount(); row++)  {
            TableCellRenderer curCellRenderer = table.getCellRenderer (row, modelColumn);
            Object value = table.getValueAt (row, modelColumn);
            Component curRenderComponent = curCellRenderer.getTableCellRendererComponent(table, value, true, true, row, modelColumn);
            Dimension cellDimension = curRenderComponent.getPreferredSize ();
            if (cellDimension.width > maxColumnWidth)
              maxColumnWidth = cellDimension.width;
    //  Set the column width to fit the maximum
          Dimension cellSpacing = table.getIntercellSpacing ();
          curColumn.setPreferredWidth (maxColumnWidth + (cellSpacing != null ? cellSpacing.width : 1));
      }I pass my table into here and it works fine apart from in doesnt take into consideration the size of the headings. Please Help ME!!!!

    java.lang.NullPointerException
         at database_testing.SLAMS.sizeAllColumnsToFitData(SLAMS.java:473)
         at database_testing.SLAMS.getInfo(SLAMS.java:364)
         at database_testing.SLAMS.getInfo_actionPerformed(SLAMS.java:434)
         at database_testing.SLAMS_getInfo_actionAdapter.actionPerformed(SLAMS.java:527)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1764)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1817)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
         at java.awt.Component.processMouseEvent(Component.java:5134)
         at java.awt.Component.processEvent(Component.java:4931)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3639)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Window.dispatchEventImpl(Window.java:1590)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)Also i think it may have something to do with my headerRenderer being null cus if i replace the line TableCellRenderer headerRenderer = curColumn.getHeaderRenderer(); with TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer(); then it doesnt come up with an error but only increase the size of the coluns (where neccessary by 2 characters)

  • Setting column widths in a PdfPTable at run time

    My web application is building PDF output using iText. The data is coming from a database through JDBC. At run time I will not know how many columns are being returned and I will not know the relative widths of each column, so I have to set this at run time to make it look good. This is the problem I am having.
    I am calling the data and returning an ArrayList of ArrayLists, each of the internal ArrayLists contains the data and the first one contains the column labels. The labels are going to be longer than the data so I can set the column widths to the labels and it should be fine. But how?
    Here is what I am trying so far, without success.
    ArrayList headRow = (ArrayList) mainList.get(0);
    float[] widths = new float[headRow.size()];
    for(int i=0;i<headRow.size();i++) {
    Chunk chunk = new Chunk((String) headRow.get(i));
    widths[i] = chunk.getWidthPoint();
    PdfPTable table=new PdfPTable(colCount);
    table.setWidthPercentage(100);
    table.setWidths(widths);
    As I said, this is not doing what I need, nor is any variation of this that I have tried. So how do I set the relative widths of the columns when I don't know how many columns I'm going to get back or how wide they need to be?
    Thanks

    It worked fine when I had a JTable associated to my table header.
    Any ideas as to why it no longer works or indeed, solutions?Not too sure if I understand the question or problem. Since when can you disassociate a tableheader from a table (or how can you create a tableheader without a table)?
    ;o)
    V.V.

  • How do I set Column Width in table displayed - have tried everything :-(

    Hi,
    I'm using Jdev 10.1.2, adf bc and jsp's.
    Simple problem, driving me nuts. In my app i display a number of different view objects in a number of jsp's. i want to set the width of the columns so that the info (if large) in each field will stay on one line. i.e. it wont continue onto the next line and take up two rows.
    i have tried setting the width property of the <th> & <td>, setting the disply width property in the entity object editor and the view object editor, nothing makes a bit of difference to how the column is displayed.
    this results in the tables looking messy and squised, which is totally unsatisfactory.
    so if anyone could shed any light on the subject, i would be most grateful.
    Thanks in advance......

    hi Newbe,
    if you set the option noWrap="true" on the column the text will not be wrapped;
    <af:column noWrap="true" sortable="false" headerText="col5">
    <af:outputText value="#{row.col5}"/>
    </af:column>
    Good luck
    Luc Bors

  • How do I set column widths in read/write rules?

    Hello structure experts,
    I am reading a set of DITA files into a specific FM template format, and there is one detail I cannot get to work properly. It should be possible to define column widths in a table, even if the DITA file does not include that information. But the Structure Application Developer Reference does not give the information on which string to pass to the column widths fm property. Does anyone out there have experience in doing this ?
    Thanks
    Jang

    Got it !!!
    Turned out to be simple, but the info was more or less hidden in the Dev Ref Guide: I had already put the "fm property column widths is value " line in but did not know the syntax for the values. Turns out you need to delimit the values by spaces, not commas. The parser does not give ANY useful information about this, just mentions 'syntax error near somewhere' or completely ignores the values you specify.
    This is how the rule for my DITA properties element now works out:
    element "properties" {
      is fm table element;
      fm property columns value is "3";
      fm property column widths value is "5cm 5cm 6cm";
    It works. I earn 10 points for answering my own question. :-)
    Ciao
    Jang

Maybe you are looking for

  • Connecting MIDI controller via USB

    Does anyone know how to connect a Roland SH-201 to a MacBook Pro via USB to use as a midi controller in Logic Express 8. I've installed the SH-201 driver, however I am getting a warning saying it is not compatible with an Intel based Macbook. Just so

  • 802.1x EAP type not configured

    Hi, a simple 802.1x test with XP client sp2, 3560 with IOS 12.2(35)SE5 and ACS 4.1(1) build 23. EAP MD5 selected on the client and enabled on the ACS but I receive in ACS an authentication failure message, with Authen-Failure-Code "EAP type not confi

  • I can't install AS10gNT_Disk1,2,3.zip-help-2

    I have launched the universal installer,then gave a new name and new path, then I get the following error messages. There was problem of accessing the stadging area. Pleased make sure the speciflied vlaues for source and destiantion are valid

  • I can't install any  apps from the AppStore on my MacBook, why?

    I can't install any  apps from the AppStore on my MacBook, why?

  • Problems setting up HP Officejet 8610

    I just bought an HP Officejet 8610 and when I got to the step to calibration, it won't do it.  I can't find out anything on my computer helpful.  Can someone tell me what to do?