Java JPanel和GridBagLayout
我想在JPanel中动态地放置按钮。为此,我选择将GridBagLayout应用于此面板(包含按钮的面板) 问题是我的按钮出现在面板中央,而我希望它们从上到下放置 这是我的密码:Java JPanel和GridBagLayout,java,swing,jpanel,layout-manager,gridbaglayout,Java,Swing,Jpanel,Layout Manager,Gridbaglayout,我想在JPanel中动态地放置按钮。为此,我选择将GridBagLayout应用于此面板(包含按钮的面板) 问题是我的按钮出现在面板中央,而我希望它们从上到下放置 这是我的密码: void placerListeUsers(){ jPanel49.setLayout(new GridBagLayout()); //jPanel49 est le panel sur lequel je place mes boutons. //jPanel49 est placé dans une
void placerListeUsers(){
jPanel49.setLayout(new GridBagLayout());
//jPanel49 est le panel sur lequel je place mes boutons.
//jPanel49 est placé dans une JScrollPane
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
//c.anchor=GridBagConstraints.NORTH;
c.weightx = 1;
//c.weighty = 0;
for (int i = 0; i < 5; i++) {
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridy = i;
jPanel49.add(new JButton("Super"), c);
}
void placerListeUsers(){
setLayout(新的GridBagLayout());
//jPanel49位于布顿广场附近的lequel je panel。
//jPanel49是一个很好的例子
GridBagConstraints c=新的GridBagConstraints();
c、 gridx=0;
c、 填充=GridBagConstraints.HORIZONTAL;
//c、 锚点=GridBagConstraints.NORTH;
c、 权重x=1;
//c、 权重=0;
对于(int i=0;i<5;i++){
c、 gridwidth=GridBagConstraints.rements;
c、 gridy=i;
jPanel49.add(新的JButton(“Super”),c);
}
他所生产的:
谢谢你帮我解决这个问题
问题是我的按钮出现在面板中央,而我希望它们从上到下放置
需要指定WexIx/y约束,否则组件会聚集在中间。
阅读上的Swing教程。上的部分将为您提供更多信息在我看来,您似乎只有垂直按钮。可能在
边框布局中添加了网格布局
或框布局
。框架的页面开始
会更容易。即使您没有按要求提供MCVE。我尝试为您的布局提供解决方案…;)
问题是,正如camickr已经提到的,在计算按钮大小后,您需要告诉GridBagLayout将面板的所有额外空间放在哪里:
- 锚点必须为GridBagConstraints.NORTH
- weight需要为添加到面板的最后一个按钮设置为1
public static void main(String[] args) { JFrame frame = new JFrame(); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); Container content = frame.getContentPane(); GridBagLayout layout = new GridBagLayout(); JPanel panel = new JPanel(layout); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.NORTH; c.weightx = 1; int buttonCount = 5; for (int i = 0; i < buttonCount; i++) { c.weighty = i == buttonCount - 1 ? 1 : 0; c.gridwidth = GridBagConstraints.REMAINDER; c.gridy = i; JButton button = new JButton("Super"); panel.add(button, c); } content.add(new JScrollPane(panel)); frame.pack(); frame.setSize(400, 400); frame.setVisible(true); }
publicstaticvoidmain(字符串[]args){ JFrame=新JFrame(); frame.addWindowListener(新的WindowAdapter(){ @凌驾 公共无效窗口关闭(WindowEvent e){ 系统出口(0); } }); 容器内容=frame.getContentPane(); GridBagLayout=新的GridBagLayout(); JPanel面板=新JPanel(布局); GridBagConstraints c=新的GridBagConstraints(); c、 gridx=0; c、 填充=GridBagConstraints.HORIZONTAL; c、 锚点=GridBagConstraints.NORTH; c、 权重x=1; int buttonCount=5; 对于(int i=0;i
MCVE
。