Adding JScrollPane to a JPanel without a Layout Manager

泪湿孤枕 提交于 2019-12-02 09:21:09

问题


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:


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...



来源:https://stackoverflow.com/questions/22371039/adding-jscrollpane-to-a-jpanel-without-a-layout-manager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!