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.

Similar Messages

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

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

  • Printing multiple JTables

    I need to print multiple JTables with a single print dialog...
    right now I am using JTable.print() to print one table at a time
    can someone please guide me as to how I can print all the tables at once with a single click
    thnx

    please help

  • Multiple JTables for One TableModel

    i have 3 tabs, and 5 tables, they arent that big mind you...the biggest table is about 150rows, 10cols, and the rest are about 10-20rows, 15cols
    they update every 5 secs, so i create a new datavector and set the tables model to the new data vector, every time
    this probably isnt the best way to do it :P
    the thing is, the last 4 table's data depends on the first (big) table's data, what is the best way to have multiple jtables displaying different data from the same data source, this way i just have to create and update the main datavector once while the other 4 just change their views
    take advantage of MVC alittle better...
    thanks

    Here is a simple [url http://forum.java.sun.com/thread.jsp?forum=31&thread=411506]example of a TableModel being shared by two tables.
    After you update the main data vector you would need to fireTableDataChanged(...); This should cause all views to be updated.

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

  • Ask for suggestion: merge cell or multiple jtable

    I would like to have a jtable like this:
    +----------+------+------+------+-----+
    | 1.Item no|2.Desc|3.Type|4.Size|5.Qty|
    +----------+------+------+------+-----+
    |    001   |  ... |  A1  |  3   |  5  |
    |          |      |------|------|-----|
    |          |      |  A2  |  2   |  6  |
    +----------+------+------+------+-----+
    |    002   |  ... |  A1  |  4   |  4  |
    |          |      |------|------|-----|
    |          |      |  A3  |  2   |  6  |
    +----------+------+------+------+-----+For each item, it would have say, 2 types (2 rows beginning from the third column).
    The question is, I'm now considering whether 1)i should use multiple jtables, one from column 1 -2 and the other from column 3 to 5. OR 2)merge cells
    In fact, i just have thought of this 2 methods and not yet implemented them yet. Any suggestion?
    Many thanks,
    Pippen

    Thanks thahn2 but I 've tried out the examples before and found them not so useful for me. And some of them even have problems running on jdk1.4.
    Any suggestion on either choice will be welcomed. (or even other suggestions)

  • Multiple Components in a JScrollPane

    Hi all,
    I'm trying to create a JScrollPane with multiple components in it, inside a TabPane. However I keep running into problems getting the display working.
    The contents of the ScrollPane will be determined at runtime and will consist of "n" tables and JLabels, in no particular order. The only constraint is that I want to have the components displayed in rows (one column per row). The number of rows and columns in each of the JTables (and therefore their size) will also be determined at runtime.
    I've run into problems where the JScrollPane only shows the last JTable added. I've tried adding a JPanel to the JScrollPane and then adding the tables to that, but the display doesn't work - maybe something I've missed on the sizing?
    Any clues on where I should focus will be most appreciated.
    Thanks

    Hi,
    Thanks for the suggestion - I've tried using the following test code, but I cannot get it to display anything:
    public class AFrame extends JFrame {
      private JScrollPane jScrollPane1 = new JScrollPane();
      public AFrame() {
        try {
          this.getContentPane().setLayout(new BorderLayout());
          this.setTitle("Test Frame");
          this.setSize(500, 500);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          this.getContentPane().add(jScrollPane1, null);
          jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
          jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          //create a table   
          JTable table1 = new JTable();
          table1.setModel(new TestTableModel());
          TableColumnModel colmod = table1.getColumnModel();
          for (int i=0; i < table1.getColumnCount(); i++) {
            TableColumn col = colmod.getColumn(i);
            col.setPreferredWidth(50);
          //create an edit field
          JEditorPane jep1 = new JEditorPane();
          jep1.setPreferredSize(new Dimension(100, 20));
          //create the panel & add two components
          JPanel p = new JPanel();
          p.setPreferredSize(this.getSize());
          double size[][] =
            {{10, TableLayout.PREFERRED, 10},  // Columns
             {10, TableLayout.PREFERRED, 10}}; // Rows
          TableLayout tl = new TableLayout(size);
          p.setLayout(tl);
          p.add(table1, "1, 1");
          p.add(jep1, "1, 2");
          validate();
          setVisible(true);
        catch(Exception e) {
          e.printStackTrace();
      public static void main(String[] args) { new AFrame(); }
    //The TestTableModel dummy class for testing
    public class TestTableModel extends AbstractTableModel  {
      public TestTableModel() {
      public int getRowCount() {
        return 2;
      public int getColumnCount() {
        return 10;
      public Object getValueAt(int row, int col) {
        return "Test value";
    }

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

  • Right-click multiple JTable rows at once?

    Hi everyone,
    Haven't posted for a while but I've been trawling through Google and these forums looking for anyone who has implemented a JTable that allows the user to right-click multiple rows after selecting the multiple rows with a left-click. Currently the JTable allows multiple rows to be selected (MULTIPLE_SELECTION policy enabled) yet when you right-click on any of the highlighted rows it only right-clicks on the one out of the group you happened to click on and deselects all the other previously selected rows. Does anyone know of a way of enabling the right-click of multiple items (new listener or just a simple parameter change?)
    Any help would be much appreciated.

    I just have a mouse listener which, on a right-click, selects the row if it's not currently selected and does nothing if the row is already selected; then pops up the menu.

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

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

  • Urgent need of your help for multiple JTables Print from a single JPanel

    I need your help to print multiple table content from JPanel
    JTables are generated dynamically in a JPanel or JPanels. I need to take print as it is in JPanel

    Alternatively you could write a simple class to print JTables with a series of calls to paintString( myString), and various calls to fillRect(...) tfor asthetics. It is quite simple. I currently use such a class that I wrote in under 200 lines of code that has a very professional look, and the print jobs are less than half the size of printing the JTable directly.
    The idea being that it takes a JTable as a parameter ( and maybe other params to control color, style, font, etc... ). It would have one primary method, print() which actually handles the printing, It may also uses other methods to control the look of the application.
    A problem I have faced with printing a JTable directly is ensuring that the botom row on each page and the top row on every page after the first one lines up correctly. After a while it was simply easier, and more customizable, to write my own print class.
    AC

  • 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

Maybe you are looking for