this.rootComponent.setLayout(new GridBagLayout());
GridBagConstraints gbc=new GridBagConstraints();
//gbc.gridwidth=2;
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=8;
gbc.anchor=GridBagConstraints.FIRST_LINE_START;
this.rootComponent.add(new JLabel("Test label 1"),gbc);
gbc.gridx=8;
gbc.gridy=12;
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbc.anchor=GridBagConstraints.FIRST_LINE_START;
this.rootComponent.add(new JLabel("Test label"),gbc);
想要像这样格式化。灰色部分显示了jpanel部分。最初我想正确布局前2个jpanel。这是行不通的。如何解决?
答案 0 :(得分:3)
您未能为weightx
指定任何weighty
和GridBagConstraints
值。此外,您的gridwidth
值是错误的,因为最低2
只需要JPanel
,其余的1
。JPanel
。
解释我在做什么:
考虑BLUE
s RED
和70:30
,它们将按比例放在 X-AXIS 上
weightx
,相对于彼此(因此他们的0.7
将分别为0.3
和1.0
。因为 X-AXIS 的总面积是BLUE
)。
现在,这两个RED JPanel
和GREEN JPanel
都将沿着 Y-AXIS 放置,相对于比率{中的第三个90:10
{1}}因此,BLUE
和RED
都有weighty = 0.9
,而GREEN JPanel
会有weighty = 0.1
,但是GREEN JPanel
}假设占据整个区域(相对于 X-AXIS ),由BLUE
和RED JPanel
s占据,就此而言,gridwidth = 2
和weightx = 1.0
。
试试这个代码示例:
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutExample
{
private GridBagConstraints gbc;
public GridBagLayoutExample()
{
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
}
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = getPanel(Color.WHITE);
contentPane.setLayout(new GridBagLayout());
JPanel leftPanel = getPanel(Color.BLUE);
JPanel rightPanel = getPanel(Color.RED);
JPanel bottomPanel = getPanel(Color.GREEN.darker());
addComp(contentPane, leftPanel
, 0, 0, 0.7, 0.9, 1, 1, GridBagConstraints.BOTH);
addComp(contentPane, rightPanel
, 1, 0, 0.3, 0.9, 1, 1, GridBagConstraints.BOTH);
addComp(contentPane, bottomPanel
, 0, 1, 1.0, 0.1, 2, 1, GridBagConstraints.BOTH);
frame.setContentPane(contentPane);
//frame.pack();
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void addComp(JPanel panel, JComponent comp
, int gridX, int gridY
, double weightX, double weightY
, int gridWidth, int gridHeight, int fill)
{
gbc.gridx = gridX;
gbc.gridy = gridY;
gbc.weightx = weightX;
gbc.weighty = weightY;
gbc.gridwidth = gridWidth;
gbc.gridheight = gridHeight;
gbc.fill = fill;
panel.add(comp, gbc);
}
private JPanel getPanel(Color backColour)
{
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(backColour);
panel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
return panel;
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
new GridBagLayoutExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
以下是OUTPUT: