嗨我想尝试将2个JPanel添加到JFrame中,该JFrame占用JFrame的全部宽度和高度 . 我设法使用GridBagLayout()添加它们但我似乎无法使用setsize()设置JPanel的大小 . 我也尝试过使用ipady和ipadx,但是当我按下一些按钮后整个布局变得一团糟时,它似乎起作用了 . 这是我的代码:
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setVisible(true);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
tradeframe.setLayout(new GridBagLayout());
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
GridBagConstraints a = new GridBagConstraints();
a.gridx = 0;
a.gridy = 0;
a.weightx = 360;
a.weighty = 300;
//a.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P1panel , a);
GridBagConstraints b = new GridBagConstraints();
b.gridx = 1;
b.gridy = 0;
b.weightx = 360;
b.weighty = 300;
// b.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P2panel , b);
如何使每个JPanel的宽度为300px,高度为400px?
5 回答
这是这样做的方法:
输出:
对于GridBaglayout你必须设置
填
锚
weightx和重量
gridx / gridy(取决于方向)
那么例如是可能的
在大多数情况下将更好地使用另一个
LayoutManager
在面板对象上调用
setPreferredSize(new Dimension(int width, int height));
方法 .您正在使用
setSize()
而不是setPreferredSize()
. 差异有点误导,我认为这是java中的问题 . 关于两者之间的区别的更多信息可以找到here.我链接的文章有一些其他的陷阱/陷阱和一个有用的读取,如果你是Java的新手 .