Search code examples
javaswingpaneljscrollpanelayout-manager

Absolute Layout Panel within JScrollPane


I'am using panel with absolute layout (don't ask why) and I need to add elements on it programmatically. I done that part, but now I want to surround panel with JScrollPane so that when user add more items, scroll bar does its job. But surrounding panel with scroll bar doesn't work. What can I do here.

JFrame frame = new JFrame();
    frame.setSize(582, 451);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(10, 11, 546, 391);
    frame.getContentPane().add(scrollPane);

    JPanel panel = new JPanel();
    scrollPane.setViewportView(panel);
    panel.setLayout(null);




for(int i=0;i<labelList.size();i++){
        if(a==4){
            a=0;
            b++;
        }
        labelList.get(i).setBounds(10+120*a+10*a, 10+130*b+10*b, 120, 130);
        labelList.get(i).setOpaque(true);
        labelList.get(i).setBackground(Color.WHITE);
        labelList.get(i).setText(Integer.toString(i));
        panel.add(labelList.get(i));
        a++;
    }

Solution

  • You're not going to like my answer, but I feel that we should be compelled to give you the best answer, which is not always what you want to hear. And that is this: use layout managers to do your component layouts. Yes while it might seem to newbies that null layouts are the easiest to use, as you gain more experience you will find that exactly the opposite is true. Null layout use makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain. Instead you will want to study and learn the layout managers and then nest JPanels, each using its own layout manager to create pleasing and complex GUI's that look good on all OS's.

    As for ease of use, I invite you to create a complex GUI with your null layout, and then later try to add a component in the middle of this GUI. This will require you to manually re-calculate all the positions and sizes of components added to the left or below the new component, which is prone to many errors. The layout managers will all do this automatically for you.

    Specifically use of valid layout managers will update your JPanel's preferredSize automatically increase as more components are added and as the JPanel is revalidated (the layouts are told to re-layout their components). Your null JPanel will not do this, and so the JScrollPane will not work. Yes, a work around is for you to manually calculate and set your JPanel's preferredSize, but this is dangerous and not recommended for the same reasons noted above.