Continuing my exploration of the Java JList, here's some sample JList/JScrollPane code, showing how I add a JList to a JScrollPane.
To get started, somewhere at the top of my class I declare my JList and JScrollPane, like this:
private JList menuList; private JScrollPane menuScrollPane;
Later in my Java class I then set up my JList, like this:
// set up the menu list (a jlist) String[] menuItems = { "Ping", "Traceroute", "Netstat", "Dig" }; menuList = new JList(menuItems); menuList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); menuList.setLayoutOrientation(JList.VERTICAL);
After setting up my JList like that, I then add it to a JScrollPane, as shown here:
// add the jlist to the jscrollpane menuScrollPane = new JScrollPane(menuList); menuScrollPane.setMinimumSize(new Dimension(100, 50));
In my current Swing code -- where I'm using a JList as a single-column menu wrapped in a JScrollPane -- the only other thing I had to do to display my JList menu was to add it to the left-hand side of a JSplitPane, which I did like this:
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, menuScrollPane, contentPanel);
JList visible row count
Note that if you're creating some code where you want to make sure there are always something like four rows of your JList visible to the user, just add a line of code like this:
menuList.setVisibleRowCount(4);
I worded that a little loosely, so to help tighten it up, here's some text from the JList setVisibleRowCount method Javadoc:
visibleRowCount - an integer specifying the preferred number of rows to display without requiring scrolling.
setVisibleRowCount() - sets the visibleRowCount property, which has different meanings depending on the layout orientation: For a VERTICAL layout orientation, this sets the preferred number of rows to display without requiring scrolling; for other orientations, it affects the wrapping of cells.
In VERTICAL orientation: Setting this property affects the return value of the getPreferredScrollableViewportSize() method, which is used to calculate the preferred size of an enclosing viewport. See that method's documentation for more details.