ボックスレイアウトを使用してラベルの任意のリストを持つパネルに JScrollPane を使用したいと思います。表示するアイテム(ラベル)が多すぎる場合にスクロールバーが表示されるようにしようとしています。
パネルに JScrollPane を追加してからラベルを追加しようとしましたが、スクロール バーが表示されません。
何か案は?
ティア
ボックスレイアウトを使用してラベルの任意のリストを持つパネルに JScrollPane を使用したいと思います。表示するアイテム(ラベル)が多すぎる場合にスクロールバーが表示されるようにしようとしています。
パネルに JScrollPane を追加してからラベルを追加しようとしましたが、スクロール バーが表示されません。
何か案は?
ティア
項目を追加した後にvalidate()
またはを呼び出して、パネルの優先サイズを強制的に再計算するようにしてください。revalidate()
JScrollPane
このような場合、通常はJList
orを使用しJTable
ます (カスタム レンダリングが必要な場合)。
コンテンツパネルの希望のサイズを設定したことを覚えていますか?
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