开发者

JScrollPane for a panel containing a set of labels with BoxLayout

开发者 https://www.devze.com 2022-12-20 16:42 出处:网络
I\'d like to use a JScrollPane for a panel which has an arbitrary l开发者_StackOverflow社区ist of labels in it using box layout.I\'m trying to get it so that the scrollbar would appear if there were t

I'd like to use a JScrollPane for a panel which has an arbitrary l开发者_StackOverflow社区ist of labels in it using box layout. I'm trying to get it so that the scrollbar would appear if there were too many items (labels) to display.

I tried adding a JScrollPane to the panel and then add the labels but then I don't see any scroll bar.

Any ideas?

TIA


For this kind of thing, you'd normally use a JList or JTable (if you need custom rendering).


Make sure that you call validate() or revalidate() on the JScrollPane after adding an item, to force the preferred size of the panel to be recalculated.


Here's how I did it.

JPanel midPanel = new JPanel();
midPanel.setLayout(new BoxLayout(midPanel, BoxLayout.Y_AXIS));
midPanel.add(new JLabel("<html><u>Label</u>"));
Box box = Box.createVerticalBox();
for (Item item : data.getInventory()) {
    inventory.add(box.add(new JLabel(item.getName())));
}

JScrollPane jscrlpBox = new JScrollPane(box);
midPanel.add(jscrlpBox);
add(midPanel, BorderLayout.CENTER);

From:

http://www.java2s.com/Code/Java/Swing-JFC/JScrollPanetoholdscrollablecomponent.htm


Did you remember to set the preferred size of the content panel?

    final JFrame frame = new JFrame("Scroll Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    final Box textArea = Box.createVerticalBox();
    final JScrollPane textAreaScroll = new JScrollPane(textArea);
    textAreaScroll.setPreferredSize(new Dimension(80,150)); /* essential! */
    JButton addButton = new JButton("ADD");
    addButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            textArea.add(new JLabel("abc"));
            textArea.revalidate();
        }
    });

    frame.getContentPane().add(textAreaScroll, BorderLayout.SOUTH);
    frame.getContentPane().add(Box.createRigidArea(new Dimension(10,10)), BorderLayout.CENTER);
    frame.getContentPane().add(addButton, BorderLayout.NORTH);

    frame.pack();
    frame.setVisible(true);

In this example, the scroll bar works correctly, but if you remove the line marked as "essential", it will not work anymore.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号