我想将 JScrollPane 用于面板,该面板使用框布局在其中包含任意标签列表。我正在尝试获取它,以便在要显示的项目(标签)过多时出现滚动条。
我尝试将 JScrollPane 添加到面板,然后添加标签,但我没有看到任何滚动条。
有任何想法吗?
TIA
我想将 JScrollPane 用于面板,该面板使用框布局在其中包含任意标签列表。我正在尝试获取它,以便在要显示的项目(标签)过多时出现滚动条。
我尝试将 JScrollPane 添加到面板,然后添加标签,但我没有看到任何滚动条。
有任何想法吗?
TIA
对于这种事情,您通常会使用JList
or JTable
(如果您需要自定义渲染)。
确保在添加项目后调用或validate()
,以强制重新计算面板的首选大小。revalidate()
JScrollPane
你记得设置内容面板的首选大小吗?
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);
在这个例子中,滚动条可以正常工作,但是如果您删除标记为“必要”的行,它将不再工作。
这就是我的做法。
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);
从:
http://www.java2s.com/Code/Java/Swing-JFC/JScrollPanetoholdscrollablecomponent.htm