2010-02-21 92 views
2

我想使用JScrollPane作爲一個面板,其中使用框佈局具有任意的標籤列表。我試圖獲取它,以便在顯示太多項目(標籤)的情況下顯示滾動條。JScrollPane面板包含一組標籤BoxLayout

我嘗試添加一個JScrollPane到面板,然後添加標籤,但我沒有看到任何滾動條。

任何想法?

TIA

回答

1

對於這種事情,你通常使用JListJTable(如果你需要自定義的渲染)。

+0

是的,我可以。我正在考慮這一點。在我的情況下,這是一個面向鍵盤的遊戲,因此在一組標籤上使用列表實現更多的代碼。但你是對的。我可以這樣做。 – sproketboy 2010-02-22 01:14:02

1

請確保在添加項目後在JScrollPane上致電validate()revalidate()以強制重新計算面板的首選大小。

+0

這似乎不適合我。見下文。 – sproketboy 2010-02-22 01:14:30

0

下面是我做到的。

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

0

你記得設置內容面板的首選大小?

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); 

在這個例子中,滾動條工作正常,但如果您刪除標記爲「重要的」行了,就不再工作了。