我试图让带有两个面板的 GridBagLayout 分别占框架的 40% 和 60%,同时能够在其中包含组件,这很麻烦。
当我没有将按钮放在面板内时,它就像我想要的那样工作。
不太确定我做错了什么,我尝试将按钮的创建移动到创建 GridBagLayout 面板的位置,但它仍然不起作用。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test{
public void display(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,650);
frame.setVisible(true);
JPanel test = new JPanel();
test.setLayout(new GridBagLayout());
GridBagConstraints c= new GridBagConstraints();
JPanel left= new JPanel();
JPanel right= new JPanel();
c.fill = GridBagConstraints.VERTICAL - GridBagConstraints.HORIZONTAL;
c.weightx = 0.4;
c.gridx = 1;
c.weighty = 1;
test.add(left,c);
c.weightx = .6;
c.gridx = 2;
test.add(right,c);
JButton button= new JButton("A button");
left.add(button,c);//If I do not add this, then it shows how I want it to be
frame.add(test);
}
}