java - Adding JScrollPane to a JPanel without a Layout Manager

Before I start, I'm aware that its a bad idea to not use a Layout Manager and usually I do use one, however, I also have all my components automatically re-size and relocate based on the size of the window. In addition the program I'm working on is only intended to run on 1 machine throughout its entire lifetime. Please don't downvote me just because of lack of layout manager, I found it to be what I need for this particular program.

To my issue, I found a similar post on stackoverflow but a solution was never achieved. I'm adding a dynamic amount of JLabels to my JPanel, I've noticed that when not using a layout manager, the scroller doesn't work.

This is a simplified version of my initialization code.

JPanel mypanel = new JPanel();
mypanel.setLayout(null);
mypanel.setSize(800,450);
mypanel.setForeground(Color.WHITE);
mypanel.setBackground(Color.BLACK);
scrollablePanel = new JScrollPane(mypanel);
scrollablePanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollablePanel.setPreferredSize(new Dimension(800,300));
scrollablePanel.setSize(800,300);
scrollablePanel.setLocation(250,156);
myContainer.add(scrollablePanel);

where myContainer would be the container (also without a layout manager). The JLabels are added later on to the JPanel with:

enter code heremypanel.add(label1);

after some basic settings are set for the labels such as setForeground and setBackground.

Unfortunately when run, the scrollbar appears as if its not required (see image)

http://i.imgur.com/zp0QKGG.png

The table text seen in the image is made up of multiple JLabels. If it's not possible to resolve the issue without using a Layout Manager I will switch to BoxLayout, I was just hoping there would be a solution.

1 Answer

  1. Joseph- Reply

    2019-11-13

    The problem is JScrollPanel needs the preferred size of the view component to determine when the view exceeds the scroll pane's viewable area.

    The preferred size of a component is normally determined via the layout manager. While you can use setPreferredSize, it is typically discouraged and you will simply run into the same problem as the content exceeds what ever value you decide to set.

    A better solution would be to use a LayoutManager or compound layout (using multiple layout managers over multiple containers) to achieve the result you desired...or write your own...

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>