【发布时间】:2012-02-10 14:52:32
【问题描述】:
我试图让带有两个面板的 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);
}
}
【问题讨论】:
-
createVector是什么? -
对不起,重命名为按钮,来自别的东西。
-
当我运行它时,它看起来像两个面板,有 40/60% 的分割,有或没有按钮。究竟是什么问题?
-
另外,除了
GridBagConstraints.VERTICAL - GridBagConstraints.HORIZONTAL,你确定你不只是想要GridBagConstraints.BOTH吗? -
docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html 大约在页面下方的 2/3 处应该可以帮助您。此外,正如文章所述,如果您难以手动操作,则始终可以使用 NetBeans,然后只需查看源代码。
标签: java swing grid jcomponent gridbaglayout