JTable -  Horizontal Scrollbar - Column Width

I wish to add a horizontal scrollbar(which for some stupid reason Java has not included) to my JTable which is inside a JScrollPane and also make sure that the width of the fourth column is longer and can fit the String that i wish to display. Now, i have searched the forum for solutions but none of them seem to work. The setting of the column width with the help of TableColumnModel does not seem to work and not to mention the fact that when i turn auto rezise off for the JTable, the JTable does give me a horizontal scrollbar but then it makes the columns so less in width that i have gray area left on the right hand side and the setColumnsToFit method does not work. I have five columns and here is the code, any help would be greatly appreciated Thanks:
excepTable = new JTable(excepTableModel);
excepTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
int width = 100;
TableColumnModel tcm;
TableColumn tc;
for(int i = excepTable.getColumnCount(); i > 0; i--)
tcm = (TableColumnModel)excepTable.getColumnModel();
tc = tcm.getColumn(i);
if(i == 3)
width = 400;
tc.setWidth(width);
tc.setMinWidth(width);
tc.setMaxWidth(width);
tc.setPreferredWidth(width);
width = 100;
exScroller = new JScrollPane(excepTable);

.I've set a horizontal scrollbar by using 'table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);You are welcome.
i want the column widht to be adjusted according to the length of column names and record length.so please tell me how to do it?Search the forum. This question has been asked and answered before.

Similar Messages

  • JTable resizing the column width

    Have a JTable whose column width's are set using
    int width = ((String)getDataTbl().getColumnModel().getColumn(0).getHeaderValue()).length() + 32;
    getDataTbl().getColumnModel().getColumn(0).setPreferredWidth(width);
    int width1 = ((String)getDataTbl().getColumnModel().getColumn(1).getHeaderValue()).length()+207
    getDataTbl().getColumnModel().getColumn(1).setPreferredWidth(width1);
    Now depending on the data in column 1 the column width has to be increased if more than width1 and the scroll bar should apprear only in this case only?
    How to do this?
    Thanks.

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

  • JTable sum of column widths table size prob

    Hi there,
    At the moment I've encountered a problem with JTable (it may be a feature?) that I can't seem to work around.
    The problem is that I've got a JTable with a custom background color for the top row of cells. The problem is that the column widths are editable and if the user makes the last column narrower, than the background color of the top row bleeds into the background panel.
    I'll try to make a small app displaying the problem, if anyone has ideas though or understands what I'm talking about I'd definitely appreciated any advice.
    Thanks,
    eknight

    The problem is that I've got a JTable with a custom background color for the top row of cells. The problem is that the column widths are editable and if the >>user makes the last column narrower, than the background color of the top row bleeds into the background panel.It is difficult to say what you mean by the color bleeding. Because if you are using/overriding the tablecellrender to achieve the background coloring, it should be taken care off automatically.
    Post a Short, compilable piece of code

  • Jtable Horizontal ScrollBar problem

    Hi,
    I am having a Jtabel inside a JscrollPanel with horizontal and vertical scrollpane.
    My table model contains say 20 columns.But i am showing only 10 columns hiding the other 10.when i click on the table header i will show the rest of 10.so now the total columns are 20.but when i scroll thehorizantal bar to the see the other 10 coulmns the header for the latest 10 coulmns is not showing properly.
    Is there anybody to help me to sort out this problem.
    Thanks in advance.
    sree

    Hi,
    how ican saw Scrollbar with out Jtable.AUTO_RESIZR_OFF.That i already did.That not the actual problem.any how i solved this problem finally.It is something with TableHeaderRenderer..Any how thanks for ur help.
    sree

  • JTable horizontal scrollbars problems.

    When I create JTable component with colons that width more than ScrollPane object one, no horizontal bar is created and all colomns shrank so i can't view what is written in cells.
    If somebody know why horizontal bar is not created?
    Some problem with ScrollPane or I need do some trics?
    Thanx:))

    JPanel contentPane;
    XYLayout xYLayout1 = new XYLayout();
    JScrollPane jScrollPane1 = new JScrollPane();
    String[] cols = {"Name", "Type", "Weignt", "Height", "EyaColor", "EyaSkin"};
    String[][] rows = {{"dklfgjfghjfdjfghj","dkffghjfghjfgjjjd","dkffghjfghjfgjjjd,h,ffgdf","dfgdlhjklhjkhjlfgdfg","dfghjlhjlhjkhgjkdfg","dfghdfhgjklhjkgfkgfhjhdfgh"},
    {"dklfgjfghjfdjfghj","dkffghjfghjfgjjjd","dfgffgdf","dfgdfgdfg","dfgdfg","dfghdfhdfgh"},
    {"dklfgjfghjfdjfghj","dkffghjfghjfgjjjd","dfgffgdf","dfgdfgdfg","dfgdfg","dfghdfhdfgh"},
    JTable jTable1 = new JTable(rows,cols);
    //setIconImage(Toolkit.getDefaultToolkit().createImage(TestTableFrame.class.getResource("[Your Icon]")));
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(xYLayout1);
    this.setSize(new Dimension(639, 339));
    this.setTitle("Test Table");
    contentPane.add(jScrollPane1, new XYConstraints(21, 29, 570, 279));
    jScrollPane1.getViewport().add(jTable1, null);

  • Display a horizontal scrollbar in a JTable as to fit column width

    hi all,
    I am using JTable to display records.I've set a horizontal scrollbar by using 'table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);',but although i got a horizontal scrol bar the column width is constant for all the columns and not getting adjusted according to the lenght of the column names. As the column names and the records are of different size in the database i want the column widht to be adjusted according to the length of column names and record length.so please tell me how to do it?
    regards...

    .I've set a horizontal scrollbar by using 'table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);You are welcome.
    i want the column widht to be adjusted according to the length of column names and record length.so please tell me how to do it?Search the forum. This question has been asked and answered before.

  • How to make JTable use horizontal scrollbar

    My application uses a table to which data is added dynamically(both columns and rows). My problem is that when number of columns increase i want JTable to use horizontal scrollbar instead of resizing columns(which i achieve by setting resize mode to OFF state), But due to this if number of columns are less then there's alot of empty space left after showing columns(coz JTable cannot resize cols to fit Viewport area). To achieve both criteria i used following solution
    1. Set Auto resizing to OFF.
    2. Check if width of table is less than viewport width and if so then set auto
    auto resizing ON :) which will fit columns in viewport thereby occupying empty space.
    But this solution doesn't seem to be straight and simple to me. Is anyone aware of a simple solution to this problem.
    Dimension dm_Dm = new Dimension();
        RSBrowser.setModal(false);
        browseTable_Jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        // reqd o.w. JTable resizes column widths instead  of using horizontal
        // scrollbar
        RSBrowser.setVisible(true);
        browseTable_Jt.getSize(dm_Dm);
        // if table width is less than total viewport size then fill the extra
        // space by setting suto resize property to ON.
        if ( browseTable_Jt.getPreferredScrollableViewportSize().getWidth() >
             dm_Dm.getWidth() )
            browseTable_Jt.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
            browseTable_Jt.doLayout();
        RSBrowser.setModal(true);

    hi,
    with your problem statement it seems you should use javax.swing.JScrollPane like the one below
    JScrollPane tableScroller = new JScrollPane(yourTable);
    tableScroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    tableScroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);hope this helps you,
    regards,
    Afroze.

  • JTable resizing VS Horizontal scrollbar

    Heila',
    I have to show the content of a text file in a JTable; the JTable has 2 columns: the first contains the line number and the second column contains the text of the line.
    In order to allow the user to view and scroll the whole text line I added an horizontal scrollbar to the JTable.
    Here is the relevant code:
    gridVis.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    JPanGriglia = new JScrollPane(gridVis, JScrollPane.VERTICAL_SCROLLBAR_NEVER,
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    JPanGriglia.getViewport().putClientProperty("EnableWindowBlit", Boolean.TRUE);     
    The problem is that if I set the AutoResizeMode to JTable.AUTO_RESIZE_OFF then I can see the horz scrollbar but when I resize the JFrame containing the JTable the JTable doesn't resize itself.
    Viceversa if I comment the statement:
    gridVis.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    then the JTable resizes correctly but the scrollbar disappears.
    Does exists the way to obtain both this features ?(correct resizing AND horizontal scroll bar)
    Thanks
    Ciao

    Try overriding getScrollableTracksViewportWidth() in JTable. The method returns a boolean value indicating whether the table should resize when its viewport is resized. If you setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS) and add a check to getScrollableTracksViewportWidth() such that it returns true only if viewport.getExtentSize().width is greater than some minimum width, then your table will resize automatically unless it is scaled below the minimum width, in which case a scrollbar will appear. If you're going to do this you'll need your JTable subclass to store a pointer to its scroll pane's viewport so it can get the extent size.

  • Fitting JTable column widths

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

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

  • JTABLE - horizontal scrolling only for some columns

    Hi all,
    In my JTABLE I have to scroll the horizontal scrollbar only from column 5 to the last, the columns 0 - 4 should be fixed ! Is this possible ?
    Thanks in advance,
    Arpana

    Please see
    http://www.senun.com/Left/Programming/Java_old/Examples_swing/JTableExamples1.html
    http://www.senun.com/Left/Programming/Java_old/Examples_swing/src/examples/FixedColumnExample.java

  • Horizontal scrollbar for JTable

    Hi folks,
    I just created a JTable with 15 columns. As number of columns are more, I am not able to view all data. Probabaly I would need a Horizonatal scrollbar. I used setPreferredScrollableViewportSize(), but it doesn't help me. Can u pls any body help me to make it work out?
    Thanx in advance.
    Regards,
    Ayyappan.

    Hi chuanhaochiu,
    Thanx for immmediate reply. I have already put JTable in JScrollBar. I am comfortably getting the vertical scrollbars when more rows are added. I am not able to get only the horizontal bar.
    Ayyappan G.

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

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

  • JTable column widths - help

    Hi,
    I have a JTable and I am having problems with the column widths. Currently, I place my JTable in a JScrollPane, and that's it. What I want is this:
    1. When the table is initially displayed, I want all the columns to be of equal width and use the entire width of the table (so no empty space at the end of the table)
    2. When I resize a column I want the other columns to maintain their size, and just have the scroll bars appear.
    3. When I resize the frame/browser that my app is running in, I want the scroll bars to appear.
    I tried the different autoResizeModes but I cant get the entire result which I need..any suggestions? Below is a code example...
    import java.awt.BorderLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class Test1 extends JPanel {
         JScrollPane scroller;
         JTable table;
         String[][] rowData = new String[][] {
                   {"John", "18"},
                   {"Bill", "20"},
                   {"Alex", "17"}
         String[] columns = new String[] {
              "Name", "Age"     
         public Test1() {
              table = new JTable(rowData, columns);
              scroller = new JScrollPane(table);
              setLayout(new BorderLayout());
              add(scroller, BorderLayout.CENTER);
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Test1 t = new Test1();
              f.getContentPane().add(t);
              f.setSize(600, 600);
              f.setVisible(true);
    }

    Forget about my last post. The following code works but I guess you'll have to work on it to make it more elegant.import java.awt.BorderLayout;
    import javax.swing.*;
    public class Test1 extends JPanel {
         String[][] rowData = new String[][]{{"John", "18"}, {"Bill", "20"}, {"Alex", "17"}};
         String[] columns = new String[]{"Name", "Age"};
         JTable table;
         JScrollPane scrollPane;
         public Test1() {
              super(new BorderLayout());
              table = new JTable(rowData, columns);
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              scrollPane = new JScrollPane(table);
              add(scrollPane, BorderLayout.CENTER);
         public void pack() {
              System.out.println("pack");
              int columnCount = table.getColumnCount();
              if (columnCount == 0) {
                   System.out.println("columnCount = 0");
                   return;
              int width = scrollPane.getViewport().getSize().width;
              System.out.println("width = " + width);
              if (width == 0) return;
              int columnWidth = width / columnCount;
              System.out.println("columnWidth = " + columnWidth);
              for (int i = 0; i < columnCount; i++) {
                   table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth);
              table.revalidate();
              table.repaint();
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              final Test1 t = new Test1();
              f.setContentPane(t);
              f.setSize(600, 600);
              f.setVisible(true);
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        t.pack();
    }

  • Set JTable column width

    Hi,
    I would like to set the column width of JTable.
    ========================================
    JTable table;
    DefaultTableModel tableModel;
    tableModel = new DefaultTableModel();
    table = new JTable( tableModel);
    JScrollPane scrollPane = new JScrollPane(table);
    for(int i = 0; i < heading.length; i++)
    tableModel.addColumn( heading[ i ]);
    ========================================

    Did you run the tutorial code? Did it work?
    Now compare the tutorial code with your code to determine what is different.
    We can't tell you what is different based on the one line of code you posted:
    colModel.getColumn(i).setPreferredWidth(100);

Maybe you are looking for

  • How to access BAPI in enterprise portal perspective?

    hi,I am venkat new to the portal.can anyone plz tel me how to access BAPI in enterprise portal perspective?is done through JCo or any other database connection?I hav not seen in System Landscape about BAPI access.plz give guidance about BAPI interfac

  • How do I get save tabs to work on a mac in forefox 3.6.6?

    How do I get Firefox 3.6.6's Save Tabs feature to work on a newly wiped iBook on which only Firefox and the OS are installed? I have tried all the suggestions and continue to be unable to save my opened tabs when quitting Firefox.

  • Cannot accept the iOS Developer Program License Agreement in Member Center

    We would like to add our new application to App Store. Although when we click on "Add New App", we get the information from Apple saying we should "review and accept this agreement in the Contracts, Tax, and Banking module". After we reviewed this ag

  • Syntax for CASE / WHEN in SNP Macros.

    Dear APO Gurus, I'm having problems using CASE when in SNP macros, even though I've tried quite  a few syntaxes. could someone please tell me how to Use CASE WHEN (WHEN WHEN WHEN...) ENDCASE in macros ? this would save me an awful lot of IF Thanks in

  • Migrating BW Administrative Users to BI

    Hi Gurus, Iam almost done migrating Reporting Users so my next task will be migrating Administrative users. What stratergy can i follow to migrate the Administrative users like what are the main new objects(BI) other than DTP,Transformations to be ad