2010-11-19 77 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的大小,它们将保持一致。那是你在找什么?