• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1051
  • Last Modified:

JTable in JScrollPane

Hi, I am using Java 1.4 swing package.
How can I make sure that a constant number of rows
(let's say 10) would be visible in the JTable?
I also need to set vertical scroll bar visible all the
time.

Thanks.
Sean
0
xzhang4
Asked:
xzhang4
  • 2
1 Solution
 
MirecXPCommented:
Hi Sean,

You must create Your own class inherited from JTable and then override method getPreferredScrollableViewportSize(), which returns preffered size of scrollable object. Typically it returns getPrefferedSize of component, so you must return your size. In this case we can return height of 10 rows.

Here is the class code:

class MyTable extends JTable {

  int rowsVisible = 10;

  MyTable (Object[][] rowData, Object[] columnNames) {
    super(rowData, columnNames);
  }

  public Dimension getPreferredScrollableViewportSize() {
    Dimension d = super.getPreferredScrollableViewportSize();
    d.height = rowsVisible * getRowHeight();
    return d;
  }

  public void setRowsVisible(int r) {
    rowsVisible = r;
  }

  public int getRowsVisible() {
    return rowsVisible;
  }

}


Now you can use it:
     ...
    Object[] myOptions = {
      "1","2","3"," 4"," 5"," 6"," 7"," 8"," 9"," 10",
      "11","12"," 13"," 14"," 15"," 16"," 17"," 18"," 19"," 20",
    };

    MyTable t = new MyTable(new Object[][] {
        {"1a", "1b"},
        {"2a", "2b"},
        {"3a", "3b"},
        {"4a", "4b"},
        {"5a", "5b"},
        {"6a", "6b"},
        {"7a", "7b"},
        {"8a", "8b"},
        {"9a", "9b"},
        {"10a", "10b"},
        {"11a", "11b"},
        {"12a", "12b"},
        {"13a", "13b"},
        {"14a", "14b"},
        {"15a", "15b"},
      }, new Object[] {"COL a", "COL b"}
    );

    //force vertical scrollbar using JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
    JScrollPane sp = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    sp.getViewport().add(t);
     ..
    insert sp into some panel...

I'm sure this helps.

Mirec
0
 
MirecXPCommented:
Hi Sean.

Are You still there ?

I think I've answered Your question, haven't I ?



0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now