One JTable in a JScrollPane.

Hi all,
I have one JTable with JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
This table is in a JScrollPane. I want this JSrollPane to fit the table, not the JFrame that contains all of them.
The JTable is not big at all, only 4 columns, so when I resize the JFrame and I make it smaller enough to cover a piece of the JTable, the JScrollPane should show its scrollbars.
Thanks in advance.
Dani.

import javax.swing.*;
import java.awt.Dimension;
public class Test extends JFrame {
public Test() {
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
JTable table = new JTable(20,4);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scroll = new JScrollPane(table);
scroll.setMinimumSize(new Dimension(304,0));
JPanel panel = new JPanel();
// panel.add(...)
JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,scroll,panel);
split.setDividerLocation(304);
getContentPane().add(split);
public static void main(String [] args) {
new Test().show();

Similar Messages

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

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

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

  • Jtable inside a JscrollPane - Can't see the left hand side of my Jtable (th

    Jtable inside a JscrollPane - Can't see the left hand side of my Jtable (the border)from some reason - please help. This is my code:
    public class RecordSetPanel extends JPanel {
    private JTable rsTable;
    private JScrollPane tableScrollPane;
    public RecordSetPanel() {
    setLayout(new BorderLayout());
    rsTable = new JTable();
    rsTable.setBackground(getBackground());
    rsTable.setRowHeight(25);
    rsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    tableScrollPane = new JScrollPane(rsTable) {
    public Insets getInsets() {
    return new Insets(20, 20, 20, 20);
    tableScrollPane.setBorder(BorderFactory.createLineBorder(getBackground()));
    add(tableScrollPane, BorderLayout.CENTER);

    I've tested this code and it looks fine:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Dialog1
        extends JDialog {
      JPanel panel1 = new JPanel();
      BorderLayout borderLayout1 = new BorderLayout();
      public Dialog1(Frame frame, String title, boolean modal) {
        super(frame, title, modal);
        try {
          jbInit();
          pack();
        catch (Exception ex) {
          ex.printStackTrace();
      public Dialog1() {
        this(null, "", false);
      public static void main(String args[]) {
        new Dialog1().show();
      private void jbInit() throws Exception {
        panel1.setLayout(borderLayout1);
        panel1.add(new RecordSetPanel(), BorderLayout.CENTER);
        getContentPane().add(panel1);
      public class RecordSetPanel
          extends JPanel {
        private JTable rsTable;
        private JScrollPane tableScrollPane;
        public RecordSetPanel() {
          setLayout(new BorderLayout());
          TableModel dataModel = new AbstractTableModel() {
            public int getColumnCount() {
              return 10;
            public int getRowCount() {
              return 10;
            public Object getValueAt(int row, int col) {
              return new Integer(row * col);
          rsTable = new JTable(dataModel);
    //      rsTable.setBackground(getBackground());
          rsTable.setRowHeight(25);
          rsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //      tableScrollPane = new JScrollPane(rsTable) {
    //        public Insets getInsets() {
    //          return new Insets(20, 20, 20, 20);
    //      tableScrollPane.setBorder(BorderFactory.createLineBorder(getBackground()));
          add(new JScrollPane(rsTable), BorderLayout.CENTER);
    }

  • Displaying more than one JTable

    Hello people. I tried creating a JScrollPane with a JTable passed to its constructor. This worked fine but i cant add any more tables to the JScrollPane.
    I could use a new window for each table but I would preffer to keep all tables on one component. Should I be using something else instead of a JScrollPane?

    You'll need to nest components. Add each JTable to its own JScrollPane. You can then add each ScrollPane to a JPanel or JSplitPane.

  • Multiple JTables in a JScrollPane

    Hi,
    Hope someone can help...
    I have a JScrollPane, to which I want to add a series of JTable and JLabel objects (determined at run-time). I have added a JPanel with layout set to TableLayout. When I add the objects, I successfully get the objects showing one below each other. However the tables automatically resize to the same width as the widest one. Which is a bit frustrating when some of the tables have two or three small columns, and one has > 30 wide columns.
    There is probably something simple that I'm missing.
        JScrollPane newPane = new JScrollPane();
        newPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        newPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          JPanel p = new JPanel();
          double size[][] = {{2, TableLayout.PREFERRED}, {2, TableLayout.PREFERRED}};
          TableLayout t = new TableLayout(size);
          TableLayoutConstraints tlc = new TableLayoutConstraints();
          p.setLayout(t);
          int rowNumber = 1;
          while (true) {
                JLabel warninglabel = new JLabel(warnText);
                t.insertRow(rowNumber, warninglabel.getPreferredSize().getHeight() + padHeight);
                p.add(warninglabel, new String("1," + rowNumber));
                rowNumber++;
                //Add a spacer
                t.insertRow(rowNumber, border);
                rowNumber++;
                t.insertRow(rowNumber, table.getTableHeader().getPreferredSize().getHeight());
                p.add(table.getTableHeader(), new String("1," + rowNumber));
                rowNumber++;
                t.insertRow(rowNumber, table.getPreferredSize().getHeight() + padHeight);
                p.add(table, new String("1," + rowNumber));
                rowNumber++;
                //Add a spacer
                t.insertRow(rowNumber, border);
                rowNumber++;
          newpane.getViewport().add(p);

    I think this is going to take a while to do. Here's a suggestion though. Try to put a resize listener on each of the viewports in each of the two table scrollpanes. When the size of the viewport changes, set the size of the corresponding scrollpane to that same size.

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

  • JTable use in JScrollPane

    I have a JTable in JScrollPane which has about 116000 rows of data. I would like to get a status count of what rows are displayed at a time when I move down the scollPane. This is to keep a running track of rows displayed in status message when moving down the scrollpane.
    SAY : Displaying rows 10 to 40 of 116000 rows. Is there anyway to get this count.

    I would use a combination of:
    [JScrollPane.getViewport().getViewRect()|http://java.sun.com/javase/6/docs/api/javax/swing/JViewport.html#getViewRect%28%29]
    and
    [JTable.rowAtPoint()|http://java.sun.com/javase/6/docs/api/javax/swing/JTable.html#rowAtPoint%28java.awt.Point%29]

  • How to remove JTable header from JScrollPane?

    Hi!
    Does anyone know how to remove the JTable header from the JScrollPane the table is placed in? I tried calling
    scrollpane.setColumnHeader( null ) and
    scrollpane.setColumnHeaderView( null )
    but none of the above worked...
    Thanks!
    Fil

    Hi,
    The easiest way to do this is to put an extra layer between the table and the scrollpane as follows:-
    JPanel p = new JPanel(new BorderLayout());
    // Add it to the north rather than center so that the table background color
    // won't cover the empty part of the view port.
    p.add(table, BorderLayout.NORTH);
    JViewport v = tableScroll.getViewport();
    v.setView(p);
    where table is your JTable and tableScroll is your JScrollPane.
    Hope this helps,
    Ian

  • How to combine two dataModel in one JTable

    rs = stat.executeQuery(query);               
    model = new ResultSetTableModel(rs); <--- a class to create AbstractTable Model
    JTable table = new JTabel(model)
    will show only the data inside the model
    I want to append some new information
    How to do??

    Use the DefaultTableModel and then the addRow(...) method to add additional rows.

  • Reading big JTable from disk one page at a time

    Hi,
    I'm trying to display a JTable in its JScrollPane
    for a large amount of data (say 40'000 records).
    Scrolling is quite smart, since it does a relatively
    good job when the user drags the knob, e.g. in order
    to reach the bottom. However, it leaves something to
    be desired. Any pointer to some example implementation?
    In particular, the table model should know how many
    records are displayed at a time, and I found no easy
    way for determining it. (I didn't make the table
    editable yet, but the current page is needed whenever
    the table is repainted, so it better be cashed.)
    And, in some cases it would be better to not update
    the view and just display a tooltip while the knob
    is being dragged. That would cause much less reading.
    In general, I need to adjust the cashing strategy
    in order to accomplish what JScrollPane is doing.
    Should I subclass it? Or should I subclass JTable?
    TIA
    Ale

    In particular, the table model should know how many
    records are displayed at a time, and I found no easy
    way for determining it. (I didn't make the table
    editable yet, but the current page is needed whenever
    the table is repainted, so it better be cashed.)There are at least two ways of finding the beginning row/column and ending row/column of the viewport. One of which is by using the JScrollBar getValue() and the other is to use the JTable getVisibleRect() method -- with either method, you will need to convert it to Point and use the JTable rowAtPoint() and columnAtPoint() to translate the point to row/column index.
    And, in some cases it would be better to not update
    the view and just display a tooltip while the knob
    is being dragged. That would cause much less reading.The best way to do this is to extend the BasicScrollPaneUI and implement your own ChangeListeners for the vertical and horizontal scroll bars as well as the viewport.
    Good Luck!
    ;o)
    V.V.

  • How to enable JScrollPane in a cell of the JTable

    Hi,
    I am able to place the components into the cell of the JTable. But I am unable to interact with the components like JTable or JComboBox after inseting them into a cell of the JTable.
    This was the one of the Scenario:
    Step 1: I created One JTable named as "insertTable"and adding to JScrollPane
    Step 2: I'm able to inserted the newly created JTable ("insertTable") in to a cell of another JTable(like table inserting a table) using TableCellRenderer.
    here was the problem. I am able to insert the newly created table into the cell. the "insertTable" size is greater the Cell size. So, the "insertTable" is appering with Horizantal and Vertical Scrollbars because the "insertTable" is added to JScrollBar. but I am unable to move the scrollbars.
    please any one help me for this.

    you still didn't try to learn the difference between cellEditor vs cellRenderer - as you were advised to do more than once in recent posts.
    If you do, the answer will be obvious (to you :-). As long as you don't there's nothing to help
    Cheers
    Jeanette

  • JTable in jScrollPane

    Hello, I am developing an application in Netbeans (Swing) with JDBC to connect mySQL. I got a question about a jTable in a jScrollPane. I read from my database and put the resultSet into a dinamical jTable. In the same form, I got a jTextField, where the user can input a code or a name to search in the jTable. When I find the code in the jTable I can select the row to remark the result. The problem I got is when the found code is not showing in the view of the table. So what I want to do, if it is possible, is automatically move the scroll to show the row I have selected; this way, the user don't have to move the scroll along the table (which could have a lot of rows). I have thought another solution could be show another frame with the data of selected row, but I want to try the first one.
    If you know how can I do this please, help me.
    I am sorry if my english is not very well. I hope you can understand my question.
    Thanks

    scphan wrote:
    BigDaddyLoveHandles wrote:
    JScrollPane scroll = new JScrollPane(new JTable(...));
    or scroll.getViewport().setView( new JTable(...) );(no difference implied)So do it the simpler way.

  • Re: Using JScrollPane With JTable

    >
    myNamePane.setVisible(true);This is meaningless, a component becomes visible by default when you add it to a visible container
    if(e.getSource().equals(newStudent))
           JFrame newFrame = new JFrame("Please select a student");
           newFrame.setContentPane(myNamePane);
           newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           newFrame.setResizable(false);
           newFrame.pack();
           newFrame.setVisible(true);
         }Which brings us to the main issue, you need to add the JScrollPane to you frame
    newFrame.add(myNamePane);Read the tutorial: [Using Top-Level Containers|http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html]

    Hello Rodney,
    Thanks for the information and the tutorial.. I've worked with containers before but never got around to reading that one, which has clarified a few things for me.
    Unfortunately however, my problem persists. I obviously can't set the content pane as the JScrollPane and add it to the Frame, so rather than setting the JScrollPane as the content pane (which I did previously), I added it to the frame as you suggested:
    if(e.getSource().equals(newStudent))
         JFrame newFrame = new JFrame("Please select a student");
    //     newFrame.setContentPane(myNamePane);
         newFrame.add(myNamePane);
         newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         newFrame.setResizable(false);
         newFrame.pack();
         newFrame.setVisible(true);
    }But the same thing happens! All I see is a new, empty JFrame. I feel like my understanding of the JScrollPane may be flawed, but I'm really not sure :/
    Edit: In fact, it is most definitely a problem either with my JTable or my JScrollPane. I used the setPreferredSize() method to check if the JScrollPane was being displayed in the JFrame, and it is. There is no JTable in the pane however.
    Edit #2: The problem was, in fact, with my JTable. The ResultSet I was using was TYPE_FORWARD_ONLY, and I was trying to call studentNameSet.first(), which prevented the JTable from ever being created. Thanks for your help, Rodney. Although I do have one more question.. Do you know a better way for me to find the number of student names given that ResultSet? I can't iterate through it twice as I had done earlier, so now for testing purposes I've simply hardcoded the number in, but I'd rather have the program find the total number of entries dynamically.
    Edited by: Pheer on Jul 22, 2008 10:07 AM
    Edited by: Pheer on Jul 22, 2008 10:09 AM

Maybe you are looking for

  • How to Change Handling Unit User Status

    Hi All, I am trying to change the HU Status using FM 'STATUS_CHANGE_EXTERN' but its not working.              lx_huheader-hu_id  is the Internal Handling unit number.             CONCATENATE 'HU'                         lx_huheader-hu_id INTO        

  • Could not open a scratch file because the file is locked or you do not have the necessary access pri

    Photoshop does not start I get the error above. I uninstalled and reinstalled but the problem is still there.  It happens all the time with all files.  Please help  thanks

  • Steps to configuring log4j with plain text file

    can anyone help me with the steps involved with configuring log4j with a plain text configuration file...Where should log4j.properties file be stored?.....do you have a simple example of a config file using a file appender?.....do I have to make chan

  • Auto time setting is missing in my iphone

    I am travelling a lot and I have to adjust the time manually in each new city. I read that i can let iphone to update the time automatically but I did not find the option to do that under settings/general/date and time. is there any patch or update t

  • My I phone 4 ran out of battery and doesn't turn on.

    My I phone 4 ran out of battery and doesn't turn on. I did bring it to a repair shop and even after changing the tip and the battery it still doesn't work. Any help would be loved because I have 3 years of data in it. cheers