[英]How does one add a JScrollPane to a JPanel
我一直在尋找實現JScrollPlane
的簡單方法。 我正在嘗試將其添加到JPanel
,它將包含動態數量的JPanel
(它將填充其他內容)。
這是我(失敗的)嘗試使JScrollPane
:
final JPanel info = new JPanel();
final JScrollPane infoS = new JScrollPane(info,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
info.setLayout(new GridLayout(0,1));
info.setLocation(10,78);
info.setSize(420,490);
infoS.setPreferredSize(new Dimension(600, 600));
gui.add(infoS);
在此示例中 ,將一系列嵌套面板添加到具有BoxLayout
的面板中。 該面板用於創建JScrollPane
,然后將其添加到JFrame
。
public class BoxTest extends JPanel {
...
JScrollPane jsp = new JScrollPane(this,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
...
JFrame f = new JFrame();
f.add(jsp); // BorderLayout.CENTER, by default
您遇到的主要問題是默認布局管理器的布局設置為FlowLayout
,這意味着JScrollPane
將要使用其首選大小進行布局,這可能不會填滿整個面板。
而是使用BorderLayout
final JPanel info = new JPanel(new BorderLayout()); // <-- Change me :D
final JScrollPane infoS = new JScrollPane(info,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
// These are bad ideas, setLocation and setSize won't work, as the panel should be
// under the control of a layout manager
//info.setLocation(10,78);
//info.setSize(420,490);
//infoS.setPreferredSize(new Dimension(600, 600));
gui.add(infoS);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.