2012-05-25 69 views
0

我已经添加了一些组件到JPanel,它被设置为网格布局,我将它添加到设置为边框布局的JFrame。但我想修复面板的大小。当我的窗口最大化时,所有组件的大小都在增加。我想要在窗口的中心的面板,与固定大小即使窗口最大化。框架中面板的固定大小

+0

*“请帮助我一些编码”*请帮助自己解决问题和任何努力的迹象。 SO不是代码生成机器。顺便说一句 - 不要使用代码格式的文本,并检查预期的后期格式。投票结束。 –

+0

如果你提供了一些代码,它会更好。例如,我会查看你的代码,看看你是否在哪里调用'setPreferredSize'。 –

+0

如果面板包含人类可读的文本,请不要这样做!字体指标因平台而异。 – trashgod

回答

3

GridLayout作为单个组件放置到GridBagLayout而没有限制 - 它将居中。将带有GBL的面板添加到BorderLayoutCENTER

参见this example用于上述图像。


Nested Layout Example还使用GBL在右侧涡旋窗格的下部居中图像。

+0

对于漂亮的图片和简短的解决方案+1。 – brimborium

0
JFrame frame = new JFrame(); 
    frame.setSize(500, 500); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().setLayout(new BorderLayout()); 

    JPanel rootPanel = new JPanel(); 
    frame.getContentPane().add(rootPanel, BorderLayout.CENTER); 
    rootPanel.setLayout(new GridBagLayout()); 

    JPanel contentPanel = new JPanel(); 

    Dimension dimension = new Dimension(300, 300); 
    contentPanel.setMaximumSize(dimension); 
    contentPanel.setMinimumSize(dimension); 
    contentPanel.setPreferredSize(dimension); 
    contentPanel.setBackground(Color.YELLOW); 

    GridBagConstraints g = new GridBagConstraints(); 
    g.gridx = 0; 
    g.gridy = 0; 
    g.anchor = GridBagConstraints.CENTER; 
    rootPanel.add(contentPanel, g); 

    frame.setVisible(true); 
+0

1)使用代码格式2)这是很少,如果有的话,答案。 -1 –

+0

至少在这种情况下不会起作用。 – brimborium

1

那么,你不应该使用BorderLayout的,因为这正好适合其子组件。如果你仍然想,因为你需要一些侧面板或类似的东西使用BoderLayout上的JFrame( ),你可以将你的JPanel(使用GridLayout)封装到另一个带有GridBagLayout或BoxLayout或类似东西的JPanel中,然后将其他JPanel放入JFrame中。

JPanel innerPanel = new JPanel(); 
innerPanel.setLayout(new GridLayout()); 
// fill and set your innerPanel 

JPanel middlePanel = new JPanel(); 
middlePanel.setLayout(new GridBagLayout()); 
middlePanel.add(innerPanel, constraintsThatPlaceItWhereYouWantIt); 

JFrame yourFrame = new JFrame(); 
yourFrame.setLayout(new BorderLayout()); 
yourFrame.add(middlePanel, BorderLayout.CENTER); 
+0

'middlePanel.add(innerPanel,constraintsThatPlaceItWhereYouWantIt);'查看我的答案,为什么'constraintsThatPlaceItWhereYouWantIt'对于将组件集中到GBL中是多余的。它链接到示例代码。 –

+0

你是对的,但由于可读性的原因,我在添加时仍然总是给出约束。他可能会在安置方面做更多更先进的工作。 – brimborium

+0

'middlePanel.add(innerPanel/*放在中间* /);';) –