2010-11-19 138 views
3

我有一個類擴展名爲Row的JPanel。我已經加入到JLabel一堆行,代碼如下:設置JPanel的大小

JFrame f=new JFrame(); 

JPanel rowPanel = new JPanel(); 
//southReviewPanel.setPreferredSize(new Dimension(400,130)); 
rowPanel.setLayout(new BoxLayout(rowPanel, BoxLayout.Y_AXIS)); 
rowPanel.add(test1); 
rowPanel.add(test1); 
rowPanel.add(test2); 
rowPanel.add(test3); 
rowPanel.add(test4); 
rowPanel.setPreferredSize(new Dimension(600, 400)); 
rowPanel.setMaximumSize(rowPanel.getPreferredSize()); 
rowPanel.setMinimumSize(rowPanel.getPreferredSize()); 

f.setSize(new Dimension(300,600)); 

JScrollPane sp = new JScrollPane(rowPanel); 
sp.setSize(new Dimension(300,600)); 
f.add(sp); 

f.setVisible(true); 

test1的地方...等是行。但是,當我調整窗口的大小時,該行的佈局會變得混亂(它也會調整大小)......我怎樣才能防止這種情況發生?

回答

3

閱讀有關Using Layout Managers的Swing教程。每個佈局管理器都有自己的規則,關於容器調整大小時會發生什麼。試玩和玩。如果你需要你的後證實SSCCE問題更多的幫助

childPanel.setMaximumSize(childPanel.getPreferredSize()); 

在BoxLayout的它的情況下,應尊重添加到面板,所以你可以做組件的最大尺寸。

+0

我改變了使用getPreferredSize和setMaximumSize如上所示(請參閱我的編輯的代碼)...仍然,因爲代碼甚至不存在。如果我有邊界佈局呢?我如何設置尺寸?它沒有提到你上面給出的鏈接上的BorderLayout – aherlambang 2010-11-19 04:57:26

+0

http://download.oracle.com/javase/tutorial/uiswing/layout/border.html – Cesar 2010-11-19 05:01:09

+0

你編輯的代碼不是SSCCE。是的,鏈接確實提到了BorderLayout。您無法在6分鐘內閱讀完整部分!佈局管理器處理添加到面板的組件,而不是面板本身。 – camickr 2010-11-19 05:07:32

1

我把代碼http://download.oracle.com/javase/tutorial/uiswing/examples/layout/BoxLayoutDemoProject/src/layout/BoxLayoutDemo.java,並與你正在嘗試做的適應它,只有使用按鈕,而不是定製JPanels:

public class BoxLayoutDemo { 
    public static void addComponentsToPane(Container pane) { 
     JPanel rowPanel = new JPanel(); 
     pane.add(rowPanel); 

     rowPanel.setLayout(new BoxLayout(rowPanel, BoxLayout.Y_AXIS)); 
     rowPanel.add(addAButton("Button 1")); 
     rowPanel.add(addAButton("Button 2")); 
     rowPanel.add(addAButton("Button 3")); 
     rowPanel.add(addAButton("Button 4")); 
     rowPanel.add(addAButton("5")); 
     rowPanel.setPreferredSize(new Dimension(600, 400)); 
     rowPanel.setMaximumSize(rowPanel.getPreferredSize()); 
     rowPanel.setMinimumSize(rowPanel.getPreferredSize()); 
    } 

    private static JButton addAButton(String text) { 
     JButton button = new JButton(text); 
     button.setAlignmentX(Component.CENTER_ALIGNMENT); 
     return button; 
    } 

    private static void createAndShowGUI() { 
     JFrame frame = new JFrame("BoxLayoutDemo"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     //Set up the content pane. 
     addComponentsToPane(frame.getContentPane()); 

     //Display the window. 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 
} 

最終的結果是這樣的: alt text

正如你可以看到,按鈕行完全對齊。如果您調整JFrame的大小,它們將保持一致。那是你在找什麼?