使用GridBagConstraints的奇怪布局

时间:2014-04-02 18:38:16

标签: java swing user-interface layout gridbaglayout

我有几种方法可以在JButton中创建自己的组件JLabelJPanel。然后我有一个单独的方法,将所有这些JPanels添加到JFrame。我还在JPanels上使用gridxgridy来定位他们我想要的方式。这是:看起来在左边,然后在标题的右上方和下面的2X2表中退出,重启,取件和你好。但是,我当前运行的代码显示一个奇怪的,随机的布局。

看起来是在左边,但是在右边是退出,一个空格,重新启动然后你好所有垂直。没有看到皮卡和头衔。我不知道为什么会这样。

请参阅下面的代码。:

public class GUI extends JPanel
{
/**
 * Creation of variables used throughout the GUI Class. 
 */
//JPanel panel = new JPanel(new GridBagLayout());

private static final long serialVersionUID = 1L;

public static void main(String[] args)
{
    GUI g = new GUI();

    g.create();
}

private void create()
{
    JFrame screen = new JFrame("Dungeon of Doom");
    screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    screen.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    //set size to full screen. 
    screen.setExtendedState(Frame.MAXIMIZED_BOTH);   

    //Add all JPanes to screen
    screen.add(lookReply(), c);
    c.gridy = 0;
    c.gridx = 0;

    screen.add(title(), c);
    c.gridy = 0;
    c.gridx = 1;
    c.gridwidth = 2;

    screen.add(quit(), c);
    c.gridy = 1;
    c.gridx = 1;

    screen.add(restart(), c);
    c.gridy = 1;
    c.gridx = 2;

    screen.add(pickup(), c);
    c.gridy = 2;
    c.gridx = 1;

    screen.add(hello(), c);
    c.gridy = 2;
    c.gridx = 2;

    screen.setVisible(true);
}

其中一种方法(退出)

private JPanel quit()
{
    JPanel quitPanel = new JPanel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    JButton quit = new JButton("QUIT");
    quitPanel.add(quit, c);


    return quitPanel;
}

除了标题是JLabel之外,所有其他方法几乎相同,并且表格迭代以在其5x5内创建JLabel JPanel表。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

我找到了这样做的原因。 如代码所示,我在设置布局之前添加了组件。

screen.add(lookReply(), c);
c.gridy = 0;
c.gridx = 0;

然而它应该是

c.gridy = 0;
c.gridx = 0;
screen.add(lookReply(), c);