2つの列に配置された4つのコンポーネントで構成されるJPanelを作成したいとします。左側の列の上部コンポーネントは垂直スペースの60%を占め、残りのコンポーネントは残りの40%を占める必要があります。右の列では、それは逆の方法でなければなりません。上位コンポーネントは40%、下位コンポーネントは60%です。GridBagLayoutの不均一な列
だから、基本的に私は私のコンポーネントは、この絵のようにレイアウトされているしたいと思います:私はGridBagLayout
と、この動作を実現しようとしている
。
public class Test extends JFrame {
JPanel testPanel = new JPanel();
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new Test().setVisible(true);
});
}
Test() {
prepareTestPanel();
setContentPane(testPanel);
setSize(500, 500);
setTitle("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void prepareTestPanel() {
testPanel.setLayout(new GridBagLayout());
addComp(makeUpperLeft());
addComp(makeLowerLeft());
addComp(makeUpperRight());
addComp(makeLowerRight());
}
private void addComp(Pair p) {
testPanel.add(p.comp, p.gbc);
}
private Pair makeUpperLeft() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Upper Left"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 60;
gbc.gridwidth = 50;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.weightx = 0.5;
gbc.weighty = 0.6;
return new Pair(panel, gbc);
}
private Pair makeLowerLeft() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Lower Left"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 60;
gbc.gridheight = 40;
gbc.gridwidth = 50;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.weightx = 0.5;
gbc.weighty = 0.4;
return new Pair(panel, gbc);
}
private Pair makeUpperRight() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Upper Right"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 50;
gbc.gridy = 0;
gbc.gridheight = 40;
gbc.gridwidth = 50;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.weightx = 0.5;
gbc.weighty = 0.4;
return new Pair(panel, gbc);
}
private Pair makeLowerRight() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Lower Right"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 50;
gbc.gridy = 40;
gbc.gridheight = 60;
gbc.gridwidth = 50;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.weightx = 0.5;
gbc.weighty = 0.6;
return new Pair(panel, gbc);
}
private class Pair {
Component comp;
GridBagConstraints gbc;
public Pair(Component comp, GridBagConstraints gbc) {
this.comp = comp;
this.gbc = gbc;
}
}
}
は、残念ながら、私が得るものです:
私は自分のコードを修正する必要がありますどのように?また、ウィンドウのサイズを変更する方法に関係なく、この比率を残しておきたいと思います。 weighty
はどのように設定する必要がありますか?
RelativeLayout、非常に有用であると考えられます。私はそれをチェックします、ありがとう! –