Search code examples
javaswingsynchronize

Java JScrollPane sometimes not successful resized


I have next part of code:

    final JList<String> list = new JList<String>(strings);
    list.setLayoutOrientation(JList.VERTICAL);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    /* Create scroll pane instance */
    JScrollPane scroll = new JScrollPane(list) {
         @Override
         public Dimension getPreferredSize()
         {
             BookFrame frame = BookFrame.instance();

             Container parent = getParent();

             return new Dimension(frame.getWidth(), parent.getHeight() - parent.getComponent(parent.getComponentCount() - 1).getHeight() - 14);
         }
    };

    /* Create button instance */
    JButton button = new JButton("Add Directory");

    /* Add new panel */
    JPanel panel = new JPanel();
    panel.add(scroll);
    panel.add(button);

This code runs when program starts and sometimes button height is a normal value (ex. 15) but sometimes it's 0. I think the problem is with JScrollPane instance - it was created before JButton instance - but I can't synchronize. I tried also to add JButton button = ... before JScrollPane scroll = ... but it's not working too.

I'm newby in Java so please tell me what I do wrong.


Solution

  • I don't see any reason you need to override the getPreferredSize() method. I would guess this is the problem.

    JScrollPane scroll = new JScrollPane(list)
    

    I don't know what "list" is, but assuming you are using a JList then you can use:

    list.setVisibleRowCount(...);
    

    to indicate the number of rows for the size of the list. The scrollpane will then be that size and scrollbars will appear if needed.