3

I have JList that grows in size along with the JFrame. I have the following code:

defaultListModel = new DefaultListModel<SData>();
for (String string: listOfStrings) {
    defaultListModel.addElement(string);
}
jList = new JList<String>(defaultListModel);
jList.setCellRenderer(jListCellRenderer);
jList.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent arg0) {
        //codes to go
    }
});
jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
jList.setLayoutOrientation(JList.VERTICAL_WRAP);
scrollPane = new JScrollPane(jList);

If I set some value for setVisibleRowCount method, the row number becomes fixed and If I don't set value, default value of 8 comes to play. I want to have this value dynamically changing.

Ahamed
  • 39,245
  • 13
  • 40
  • 68

2 Answers2

4

I just found that jList.setVisibleRowCount(0) makes it self adjustable, when resizing JList.

Ahamed
  • 39,245
  • 13
  • 40
  • 68
  • 1
    +1 A negative value works, too. See also [`getPreferredScrollableViewportSize()`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#getPreferredScrollableViewportSize%28%29). – trashgod Mar 01 '12 at 22:42
  • 1
    @trashgod, inside the `setVisibleRowCount` method, they were checking for `max(0,paramRowCount)`, so sending negative value or zero doesn't matter. It will take zero only. :) – Ahamed Mar 02 '12 at 13:19
1

Echoing @kleopatras's comment, it's not clear what controls setVisibleRowCount(). This example grows the enclosing Window as rows are added, up to a predefined limit, then the scrollbar takes over. It might give you some ideas, or you can use it as the basis of your sscce as @Andrew suggests.

Addendum: If the size of JList will control the count, I'd start with half of the model's size(). Then add one visible row for every n added to the model, in a fixed ratio that is pinned to a predefined limit. To maintain a reliable count, you'll have to implement your own ListModel or override the mutators in DefaultListModel.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045