尝试自学Java GUI(Swing)应该是一个简单的解决方案

时间:2015-07-31 04:42:51

标签: java swing layout-manager gridbaglayout

好吧,就像标题所说的那样,这应该是一个简单的问题,但我很擅长做gui而且我有一点问题。
我正试图将我的窗口分成3个有边框的部分(水平)。到目前为止,我有两个,但是,中间的那个延伸到窗口的底部,阻挡了底部。我猜这与我使用NORTH,CENTER和SOUTH有关?我附上了窗口的图片和我的一些代码,如果你需要更多,请告诉我!

[img]http://i.imgur.com/K3pWxvl.png[/img]

顶部

public NamePanel(){
    Dimension size = getPreferredSize();
    size.height = 125;
    setPreferredSize(size);
    //setBorder(BorderFactory.createTitledBorder("Who owes who money?"));
    setBorder(BorderFactory.createTitledBorder("Who?"));

    JRadioButton button;
    setLayout(new GridBagLayout());
    GridBagConstraints gc = new GridBagConstraints();

    button = new JRadioButton("Bob");
    gc.anchor = GridBagConstraints.CENTER;
    gc.weightx = 0.5;
    gc.weighty = 0.0;
    gc.gridx = 1;
    gc.gridy = 0;
    add(button, gc);

    button = new JRadioButton("Sue");
    gc.weighty = 0.5;
    gc.gridx = 3;
    gc.gridy = 0;
    add(button, gc);

中段

public ActionsPanel(){
    Dimension size = getPreferredSize();
    size.height = 75;
    setPreferredSize(size);
    setBorder(BorderFactory.createTitledBorder("What would you like to do?"));

    JRadioButton button;
    setLayout(new GridBagLayout());
    GridBagConstraints gc = new GridBagConstraints();

    button = new JRadioButton("Add");
    gc.anchor = GridBagConstraints.NORTH;
    gc.weightx = 0.5;
    gc.weighty = 0.0;
    gc.gridx = 1;
    gc.gridy = 0;
    add(button, gc);

底部(隐藏在图片中)

public EntryPanel(){
     Dimension size = getPreferredSize();
     size.height = 75;
     setPreferredSize(size);
     setBorder(BorderFactory.createTitledBorder("Enter the transaction"));

     JLabel why = new JLabel("Why?: ");

     JTextField transName = new JTextField(10);
     setLayout(new GridBagLayout());
     GridBagConstraints gc = new GridBagConstraints();
     gc.anchor = GridBagConstraints.SOUTH;
     add(transName, gc);

1 个答案:

答案 0 :(得分:5)

这几乎是BorderLayout的工作原理。 BorderLayout有五个位置可以显示组件,但只有一个组件可以占据每个位置。有关详细信息,请查看How to Use BorderLayout

根据您的需要,您可以使用GridBagLayout,例如......

Form

setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;

add(namePanel, gbc);
add(actionsPanel, gbc);
add(entryPanel, gbc);

这将在容器内垂直布置三个组件,但只尊重那里的首选高度,因此不会扩展以垂直填充整个容器

有关详细信息,请查看Laying Out Components Within a ContainerHow to Use GridBagLayout

别忘了,您可以使用多种布局(通过使用多个容器)来生成所需的结果

您应该避免使用setPreferredSize,只需让容器和布局管理器来处理它。有关详细信息,请参阅Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

您还应该尝试在pack上使用JFrame来允许窗口围绕内容进行打包