Resizing columns in a JTable in a JScrollpane

I have a JTable in a JScrollpane and I after I load the table, I resize the columns to fit the data (works well).
The problem is that I want the scrollpane to stay the same size and let the table scroll horizontally inside the viewport. The actual result is the scrollpane stretches to the width of the table causing the user to scroll the panel rather than the scrollpane.
I've tried setting the scrollbar policy but that didn't work.

I am passing the JTable to the constructor of the JScrollPane.
I have a JTable in a JScrollPane that sits on a JPanel which is in a JScrollPane itself.
After I load the data into the JTable, I resize all of the columns to fit the data.
The problem is that the JTable resizes wider than original size causing the whole panel to scroll horizontally. I would rather have the JScrollPane that the JTable is in scroll.

Similar Messages

  • Resize column width for JTable without column headers?

    Hi,
    I find that for me to resize columns of a JTable by using
    mouse dragging, I MUST have column headers and then drag
    column headers to resize them. Is my understanding correct?
    Actually, I need to have a table without header columns.
    How can I use mouse to resize column width by dragging?
    The background for this request is that I am putting a
    complex table as another table's column header and I hope to
    be able to resizing the complex table by mouse dragging.
    Thanks very much,
    David

    Hi,
    I think you have mistake there. Try
    <style type="text/css">
    table.apexir_WORKSHEET_DATA td {
    white-space:nowrap !important;
    td[headers="DESCR"] {
    width:300px !important;
    max-width:300px !important;
    #apexir_DESCR {
    width:10px;
    max-width:300px !important;
    </style>And you can try add
    table.apexir_WORKSHEET_DATA {
    width: 100% !important;
    table-layout: fixed !important;
    }Regards,
    Jari
    My Blog: http://dbswh.webhop.net/htmldb/f?p=BLOG:HOME:0
    Twitter: http://www.twitter.com/jariolai

  • Resizing columns in a JTable

    How can I know when a JComponent is valid? i.e. I need to execute some code after a table has resized its columns, but I can't use the method SwingUtilities.invokeLater. Is there any method that informs when the component has finished painting?
    Thank you very much in advance for your help.

    Well, I don't know about that "finished painting" thing, but components do fire events when they are resized.
    You need to register a ComponentListener to be notified of resize events ...

  • Remove Column Headers from a JTable in a JScrollPane

    Hi,
    I'm just wondering how to remove the column headers from a JTable in a JScrollPane.

    Here are two ways to do it, with different visual outcomes...
    import javax.swing.*;
    public class Test {
        public static void main(String[] args) {
            Object[][] rowData = {{"A", "B"}, {"C", "D"}};
            Object[] columnNames = {"col 1", "col 2"};
            JTable table1 = new JTable(rowData, columnNames);
            table1.getTableHeader().setVisible(false);
            JScrollPane sp1 = new JScrollPane(table1);
            JTable table2 = new JTable(rowData, columnNames);
            final JScrollPane sp2 = new JScrollPane(table2);
            JPanel contentPane = new JPanel();
            contentPane.add(sp1);
            contentPane.add(sp2);
            final JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(contentPane);
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    sp2.setColumnHeader(null);
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }

  • JTable user resize columns with grid?

    Is it possible to allow a user to resize columns not just through the table header, but with the vertical grid lines?

    There is no method that allows you to toggle this
    feature on/off if thats what you are asking.Yes, thats what I was asking.
    If you want to implement this type of functionality
    yourself then take a look at the source code for
    JTableHeader to see how its done.Thanks, I'll look into that - though it would be cool if that was already a feature of JTable.

  • Last few Columns disappear in JTable

    Hi Guys,
    I have put a JTable inside a JScrollPane. This table has 14 cols. When the page is displayed, it displays only 8 cols. If I resize a column width, then the next cols is displayed. My code goes like this :
    <CODE>
    this.m_tableModel = new DefaultTableModel(data, headers);
    this.jTableDriversInfo = new JTable(this.m_tableModel);
    this.jTableDriversInfo.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    this.jTableDriversInfo.getTableHeader().resizeAndRepaint();
    <CODE>
    Please help.

    If you turn AutoResize off then you have to manually set the size of your columns in order to get a correct look.

  • Resizing row header of jtable

    hi,
    Is there any way to resize row header column of a jtable just as other columns of jtable. i searched in forums and google but couldnt find any article with resizing row header.
    thanx

    If you want help in the future I suggest you remain a little more patient. It's the weekend. People don't hang around waiting for you to post a question. We answer questions if and when we have time and we know the answer.
    The general answer is yes, of course, it can be done. But we can't give you a specifice answer since you question is so general.
    For example, take a look at my code in this posting:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=639189
    I made the following changes:
    //          addColumn( new TableColumn() );
              TableColumn column = new TableColumn();
              column.setHeaderValue(" ");
              addColumn( column );And then I overrode the following method of the table:
    public void columnMarginChanged(ChangeEvent e)
         super.columnMarginChanged(e);
         TableColumn resizingColumn = getTableHeader().getResizingColumn();
         if (resizingColumn != null)
              Dimension d = getPreferredSize();
              d.width = resizingColumn.getWidth();
              setPreferredScrollableViewportSize(d);
    }and finally
    scrollPane.setRowHeaderView( lineTable );
    scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, lineTable.getTableHeader()); // newOf course we have no idea what component you are using for your row header so we can't give a detailed solution, but I suspect you would need to do something like the following:
    a) add a mouseListener to your component
    b) calculate the change in size of the component using the mouse location changes
    c) set the preferred size of your component
    d) notify the scroll pane of the change in size. I would look at the setPreferredScrollableViewportSize method of JTable to see what it does.

  • Problem with JTable in a JScrollPane

    Hello all,
    I have a problem using JTable, that the number of columns is very big,
    and the JScrollPane shows only vertical ScrollBar, isn't there any way to show a horizontal ScrollBar, to show the other columns without being bunched.
    Thanks in advance.

    table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

  • Resize cells in a JTable.

    I'd like to give some columns, in a jTable, an autoresize mode. It means fitting well with the content (being able to read the longest cell without having to resize the cell manualy by resizing the header).
    Some tables of other applications (like the Excel ones) hava this ability.
    Do S.O. have any idea of doing this?
    Thanks.

    extend a new class from javax.swing.table.DefaultTableCellRenderer
    and use setCellRenderer(...) on your JTable

  • Looking for component: flexible rows like columns in a JTable

    Hello,
    I need a swing component to display several rows which can be moved up and down, the height resized, interchanged with the mouse like the columns in a JTable. But there is no need for columns. I think there is no standard swing component.
    Any ideas, resource hints?
    Thanks, Ulrich

    One more piece of advice. It is not very easy to get "pre-written custom components". Most developers do things to meet their own needs and these may not be exactly what you are looking for. The best thing to do is to try to develop this yourself. It will give you loads of experience and in later programmes you may write, based on the experience you obtained from the "pain-staking" development process you'll know how to go round these problems quicker and may be able to help others also.
    So just start writing some stuff. You may end up finishing sooner than you think. And remember forum members are always ready to help with problems (accompanied by minimal code examples of the actual problem).
    ICE

  • Setting the Size of a Column in a JTable

    Hi there,
    does anybody knows a way how to set the size of a specified column in a JTable without changinge the size of the other columns?
    thx anyway
    Errraddicator

    You've got to change the JTable's column resizing policy to prevent the other columns resizing:
    JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)Otherwise all the columns will be adjusted to fit into the width of the table - changing one column would have to result in at least one other column changing!
    Hope this helps.

  • Setting tooltip for columns in a JTable

    Hi!
    I have a JTable inside a JScrollPane. How do I set tooltip for each columnheader of the JTable?
    I have noted that if I don�t have the JTable within the JScrollPane, the columnheaders are not shown.
    Regards
    Johan

    1) You need to set the tooptip text on the renderer for the column (yourTable.getColumnModel().getColumn(...).getHeaderRenderer()).
    2) The header is a separate component to the table. When you add a table to a scroll pane it automatically adds the header to the scroll pane too. You can get the component (yourTable.getTableHeader()) and add it to your own container if you wish.

  • Show hidden columns in a JTable

    Hi,
    I have a requirement for hiding some columns of a JTable and showing them back based on user actions.
    I have gone through some topics about hiding columns. which can be done by table.removeColumn();
    But when I use table.addColumn(); it adds the column at the end of the table.It should add in the same location as the previous column.
    How to show /reveal the hidden column back?.

    * Hide_Columns.java
    * This code contains a table model that allows you to
    * specify the columns to be hidden in a boolean array.
    * To use the model:
    *       model = new MyTableModel(data, columnNames);
    *       table.setModel(model);
    * The most important method in the model is "getNumber()", which converts a column number
    * into the number corresponding to the data to be displayed.
    * Visible columns can be dynamically changed with
    * model.setVisibleColumns(0, column0.isSelected());
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Hide_Columns extends JFrame {
        public Hide_Columns() {
            setTitle("Hide columns");
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            model = new MyTableModel(data, columnNames);
            table.setModel(model);
            getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
            for( int i=0; i<4; i++ ){
                final JCheckBox columnX = new JCheckBox("Column "+i);
                columnX.setSelected(true);
                final int col = i;
                columnX.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        model.setVisibleColumns(col, columnX.isSelected());
                toolBar.add(columnX);
            getContentPane().add(toolBar, BorderLayout.NORTH);
            setSize(400,300);
            setLocationRelativeTo(null);
            model.addRow(new Object[]{null,null,null,null});
            model.setValueAt("test0",0,0);
            model.setValueAt("test1",0,1);
            model.setValueAt("test2",0,2);
            model.setValueAt("test3",0,3);
        public static void main(String args[]) { new Hide_Columns().setVisible(true); }
        private JTable table = new JTable();
        private  JToolBar toolBar = new JToolBar();
        private   MyTableModel model;
        /** This is the data of the table*/
        private  Vector<Object> data = new Vector<Object>();
        /** Column names */
        Vector<String> columnNames = new Vector<String>();{
            columnNames.addElement("0");
            columnNames.addElement("1");
            columnNames.addElement("2");
            columnNames.addElement("3");
    class MyTableModel extends DefaultTableModel {
        /** Shows which columns are visible */
        private   boolean[] visibleColumns = new boolean[4];{
            visibleColumns[0] = true;
            visibleColumns[1] = true;
            visibleColumns[2] = true;
            visibleColumns[3] = true;
        public MyTableModel(Vector<Object> data, Vector<String> columnNames){
            super(data, columnNames);
        protected void setVisibleColumns(int col, boolean selection){
            visibleColumns[col] = selection;
            fireTableStructureChanged();
         * This function converts a column number of the table into
         * the right number of the data.
        protected int getNumber(int column) {
            int n = column;    // right number
            int i = 0;
            do {
                if (!(visibleColumns)) n++;
    i++;
    } while (i < n);
    // When we are on an invisible column,
    // we must go on one step
    while (!(visibleColumns[n])) n++;
    return n;
    // *** METHODS OF THE TABLE MODEL ***
    public int getColumnCount() {
    int n = 0;
    for (int i = 0; i < 4; i++)
    if (visibleColumns[i]) n++;
    return n;
    public Object getValueAt(int row, int column) {
    return super.getValueAt(row, getNumber(column));
    public void setValueAt(Object obj, int row, int column) {
    super.setValueAt(obj, row, getNumber(column));
    public String getColumnName(int column) {
    return super.getColumnName(getNumber(column));

  • JTextFields above column headers in JTable

    I am looking for a way to put a single row above (for filtering purposes) the table header in a JTable. Right now I am using JTextFields above my table for the filters, but as the columns are resized or moved so would the text fields have to be. So I am thinking putting a row above the table header would be appropriate.
    Any suggestions or examples in this area?

    Hello
    I've been working on something similar (filters above a JXTable) and i managed to get it working. So i'm putting it on this thread if someone find it with google :)
    The code for moving / resizing columns works fine, but the code for removing/adding columns doesn't work very well because it only allows one removed column at a time, or that you add the columns in the correct order.
    My solution is a bit different. I put a listener on the column property "visible", associated with the filter component above the column. That way, when i remove (hide) a column, the filter component removes itself from the panel, and when i reactivate the column, the component adds itself to the panel.
    Because the property change event is fired after the columnadded / columnmoved event, i have to use invokeLater thread to actually move the component at its right position.
    Here's the code for the moved/resized listener:
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.TableColumnModelEvent;
    import javax.swing.event.TableColumnModelListener;
    import javax.swing.table.TableColumnModel;
    import fr.dga.gesma.catalyse.ihm.beans.FilterPanel;
    public class ExternalHeaderColumnModelListener implements TableColumnModelListener {
        private JPanel filterRow;
        private JTable table;
        public ExternalHeaderColumnModelListener(JPanel header, JTable table) {
            filterRow = header;
            this.table = table;
        public void columnAdded(TableColumnModelEvent e) {
        public void columnRemoved(TableColumnModelEvent e) {
        public void columnMarginChanged(ChangeEvent e)
            TableColumnModel tcm = table.getColumnModel();
            int columns = tcm.getColumnCount();
            for (int i = 0; i < columns; i ++)
                FilterPanel filtre = (FilterPanel)filterRow.getComponent( i );
                Dimension d = filtre.getPreferredSize();
                d.width = tcm.getColumn(i).getWidth();
                filtre.setPreferredSize( d );
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    filterRow.revalidate();
        public void columnMoved(TableColumnModelEvent e)
            final int toIndex = e.getToIndex();
            final int fromIndex = e.getFromIndex();
            // Delaying so the component exists when we move it
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    Component moved = filterRow.getComponent(fromIndex);
                    if (moved != null) {
                        filterRow.remove(fromIndex);
                        filterRow.add(moved, toIndex);
                        filterRow.validate();
        public void columnSelectionChanged(ListSelectionEvent e) {}and the code for the filter component (listener part) :
        private Container parent = null;
        // Taken from ColumnControlButton (JXTable component)
        // This listener is added to the TableColumn associated to this filter component
        protected PropertyChangeListener createPropertyChangeListener() {
            return new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent evt) {
                    if ("visible".equals(evt.getPropertyName())) {
                        updateFromColumnVisible((Boolean) evt.getNewValue());
         * Hides or shows the filter component. This
         * is called on change of tablecolumn's <code>visible</code> property.
         * @param visible column visible state to synch to.
        private void updateFromColumnVisible(boolean visible) {
            if (visible) {
                if (parent != null) {
                    parent.add(this);
                    parent.validate();
            } else {
                parent = this.getParent();
                if (parent != null) {
                    parent.remove(this);
                    parent.validate();
        }Hope this helps someone :)

  • Unable to grow and shrink a JTable within a JScrollPane

    I need help with the following: I want to display a JTable component with a calendar like design. Dragging the size of the parent component (having a border to drag) should dynamically adapt the JTable' size and its cells. Since the JTable has a minimum size shrinking the parent component should show scrollbars if the minimum size is reached horizontal or vertical respectively.
    I have the JTable put ijnto the viewport of a scrollpane and the scrollpane is the child component of a JPanel. So dragging appears with the panel.
    The JTable cells do nicely but from a specific size on there is a grey area on the lower part of the JPanel which is not repainted. What is causing this? What do I have to do? I'm lost in the jungle of invalidate(), repaint(), update(), doLayout() etc.
    Here is my SSCCE (at least I hope it is one):
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.UIManager;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    //public class MyComponent extends JScrollPane
    public class MyComponent extends JPanel
    ///   class data
         static public final long serialVersionUID = -1L;
         static public final int c_ColWidth = 29;
         static public final int c_RowHeight = 18;
         static public final int c_TableWidth = 930;
         static public final int c_TableHeight = 234;
    ///   instance data
         private String[] m_strColHeader = {
              "01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
              "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
              "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",
              "31",
         private Object[][] m_Data = new Object[12][33];// data array
         private TableModel m_DataModel = new AbstractTableModel() {
              static public final long serialVersionUID = -1L;
              public int getColumnCount() { return m_strColHeader.length; }
              public int getRowCount() { return m_Data != null ? m_Data.length : 0; }
              public Object getValueAt(int row, int col) { return m_Data[row][col]; }
              public String getColumnName(int col) { return m_strColHeader[col]; }
              public Class getColumnClass(int col) { return String.class; }
              public boolean isCellEditable(int row, int col) { return false; }
              public void setValueAt(Object aValue, int row, int col) {
                   m_Data[row][col] = aValue;
         protected BorderLayout myLayout = new BorderLayout();
         protected JTable tableView = new JTable(m_DataModel);
         protected JScrollPane scrollPane = new JScrollPane(tableView);
    ///   public class methods
         static public void main(String[] args)
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch(Exception e)
                   e.printStackTrace();
              MyComponent comp1 = new MyComponent();
              JFrame frame = new JFrame("MyComponent");
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.getContentPane().add(comp1);
              frame.pack();
              frame.setVisible(true);
    ///   constructors
         public MyComponent()
              try
                   jbInit();
                   initTable();
              catch(Exception ex)
                   ex.printStackTrace();
    ///   protected instance methods
         protected void initTable()
              // do nor allow user interaction with calendar view
              tableView.getTableHeader().setReorderingAllowed(false);
              tableView.getTableHeader().setResizingAllowed(false);
              //tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              tableView.setRowHeight(c_RowHeight);
              // adapt all CellRenderers
              for (int i = 0; i < m_DataModel.getColumnCount(); i++)
                   TableColumn column = tableView.getColumn(tableView.getColumnName(i));
                   column.setMinWidth(c_ColWidth);
                   column.setPreferredWidth(c_ColWidth);
    ///   private instance methods
         private void jbInit() throws Exception
              this.setLayout(myLayout);
              this.add(scrollPane, BorderLayout.CENTER);
              scrollPane.getViewport().setMinimumSize(new Dimension(c_TableWidth, c_TableHeight));
              scrollPane.getViewport().setPreferredSize(new Dimension(c_TableWidth, c_TableHeight));
              tableView.setPreferredSize(new Dimension(c_TableWidth, c_TableHeight));
              addComponentListener(new MyComponent_componentAdapter(this));
    ///   event handling
         public void componentBoundsChanged(ComponentEvent e)
              scrollPane.setBounds(0, 0, getWidth(), getHeight());
              scrollPane.getViewport().setBounds(0, 0, getWidth(), getHeight());
              //tableView.setBounds(0, 0, getWidth(), getHeight());
              tableView.setSize(scrollPane.getViewport().getWidth(), scrollPane.getViewport().getHeight());
              tableView.setRowHeight(getBounds().height / 13 < c_RowHeight ?
                        c_RowHeight : getBounds().height / 13);
              System.out.println("componentBoundsChanged: getBounds() = " + getBounds());
              System.out.println("componentBoundsChanged: getSize() = " + getSize());
              System.out.println("componentBoundsChanged: getViewport().getBounds() = " + scrollPane.getViewport().getBounds());
              System.out.println("componentBoundsChanged: getViewport().getSize() = " + scrollPane.getViewport().getSize());
              System.out.println("componentBoundsChanged: tableView.getBounds() = " + tableView.getBounds());
              System.out.println("componentBoundsChanged: tableView.getSize() = " + tableView.getSize());
    ///   event adapters
    class MyComponent_componentAdapter extends ComponentAdapter
         protected MyComponent adaptee;
         MyComponent_componentAdapter(MyComponent adaptee)
              this.adaptee = adaptee;
         public void componentMoved(ComponentEvent e)
              adaptee.componentBoundsChanged(e);
         public void componentResized(ComponentEvent e)
              adaptee.componentBoundsChanged(e);
    }

    I guess i am facing exactly opposite problem.
    What i want to do is, I have nested tables in a scroll pane. So I don't want a scroll pane to show exactly whatever visible rows are there in Table (No extra space). If i expand any row, i want scroll pane to be able to show expanded.

Maybe you are looking for

  • In XI, None of the links(IB configuration, Integration Repository..) work.

    Hi, This issue was not there just one day back. Because of this issue, IB is also also not launching. It says: An error occurred while launching/running the application. Title: Integration Builder Vendor: SAP AG Category: Download Error; Unable to lo

  • ITunes 6 installed - Missing big chunk of library -HELP!

    I have been operating on iTunes 6 since July 05 as I had such horror issues trying to update to iTunes 6. I finally bit the bullet and just installed iTunes 6 so I could download episodes of 24. Well, all appeared to go well, exept when iTunes 6 open

  • How do I get ADE to recognize my ID?

    I have a Sony reader, migrated to Kobo last year, no problems downloading and reading until last week.  Now I get messages that items are DRM protected, and Adobe won't recognize my sign-n.  I have reloaded Adobe, changed my password, and not even Ko

  • Labview Driver for TPS 2014

    I am using Labview to control Oscilloscope TDS 2014. I downloaded the plug in and play driver from  http://sine.ni.com/apps/utf8/niid_web_display.model_page?p_model_id=540. I want to test the connection between the driver and the instrument. For this

  • DAC - drops indexes in the task but does not create them back

    DAC is dropping indexes for a task but not recreating them. The execution plan drop/create checkbox is checked and other tasks' index drop/create is working correctly. Index setup is checked for drop/create as well. Is there somewhere within DAC that