2017-08-06 79 views
2

我想用java编写一个简单的文本编辑器。如何使用GridBagLayout创建3个可变高度的JPanels顶部

我组织了我的布局,并得出结论,我基本上需要3个JPanel,一个在另一个之上。第一个和第二个将是非常短的高度,因为它们将分别是菜单栏和JPanel,分别包含2个JLabels。 中间一个需要是最高的那个,因为所有的文本都会包含在其中。

我想我需要使用一个GridBagLayout,但这不起作用,我需要它们占据比小数据大10倍的大数据。它们都将利用JFrame提供的宽度。

到目前为止的代码片段 -

GridBagConstraints gbc = new GridBagConstraints 
gbc.fill = GridBagConstraints.HORIZONTAL; 
gbc.gridx = 0; 
gbc.gridy = 0; 
mainFrame.add(upperGrid, gbc); 
gbc.gridx = 0; 
gbc.gridy = 1; 
gbc.gridheight = 10; 
mainFrame.add(upperGrid, gbc); 
gbc.gridx = 0; 
gbc.gridy = 11; 
mainFrame.add(upperGrid, GBC); 

我得到的结果是这样的 -

Distorted GridBagLayout

+0

1)为了更好地帮助越早,张贴[MCVE]或[简短,独立,正确的例子](http://www.sscce.org/)。 2)以最小尺寸提供ASCII艺术或简单的GUI图形*图形,并且如果可调整大小,则具有更大的宽度和高度。 –

+0

我认为你可以通过为['gbc.weighty'](https://docs.oracle.com/javase/8/docs/api/java/awt/GridBagConstraints.html#weighty)使用不同的值来达到目的。 –

+2

当设置gbc.weighty = 1.0时,组件之间的垂直间距'增加'了一点,但我希望它们坚持JFrame的边框,它们应该拼凑所有空间,但增加组件内部的区域,而不是在其他组件的边界之间。 – Thomas

回答

3

我建议你放下网格布局的想法。我会做以下代替:

  1. 使用JMenuBar为菜单栏(https://docs.oracle.com/javase/tutorial/uiswing/components/menu.html

  2. 使用的BorderLayout:

    JFrame frame = new JFrame(); 
    JPanel topPanel = new JPanel(); 
    topPanel.setLayout(new FlowLayout()); 
    topPanel.add(new JLabel("Label 1")); 
    topPanel.add(new JLabel("Label 2")); 
    frame.add(topPanel, BorderLayout.NORTH); 
    JPanel bigPanel = new JPanel(); 
    frame.add(bigPanel, BorderLayout.CENTER); 
    

时,你可以使用一个网格布局需要安排一个包含大量文本字段的对话框。但对于这个“更粗糙”的东西,BorderLayout更好,也因为它可能更快。 (也许,我不知道肯定)

编辑:如果你绝对必须使用GridBagLayout的,那么你可以做到以下几点:

JPanel panel = new JPanel(); 
GridBagLayout layout = new GridBagLayout(); 
layout.columnWidths = new int[] { 0, 0 }; 
layout.rowHeights = new int[] { 0, 0, 0, 0 }; 
layout.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; 
layout.rowWeights = new double[] { 0.0, 0.0, 1.0, Double.MIN_VALUE }; 
panel.setLayout(layout); 

JPanel menuBar = new JPanel(); 
GridBagConstraints contraints = new GridBagConstraints(); 
contraints.fill = GridBagConstraints.BOTH; 
contraints.gridx = 0; 
contraints.gridy = 0; 
panel.add(menuBar, contraints); 

JPanel panelForLabels = new JPanel(); 
contraints = new GridBagConstraints(); 
contraints.fill = GridBagConstraints.BOTH; 
contraints.gridx = 0; 
contraints.gridy = 1; 
panel.add(panelForLabels, contraints); 

JPanel bigPanel = new JPanel(); 
contraints = new GridBagConstraints(); 
contraints.fill = GridBagConstraints.BOTH; 
contraints.gridx = 0; 
contraints.gridy = 2; 
panel.add(bigPanel, contraints); 
+2

是的,这是完美的作品。但是我不能接受这个答案,因为我必须在将来的项目中使用GridBagLayout,并且我需要知道我做错了什么。 – Thomas

+0

我编辑了我的答案,也许它会帮助你。 – Professor901

+2

嘿它工作我记得我不得不修改一个非常小的部分,但它确实工作得很好。谢谢 – Thomas

相关问题