使用GridBagConstraint的奇怪布局



我有几个方法可以在JPanel中创建自己的组件、JButtonJLabel。然后我有一个单独的方法,它将所有这些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并且表迭代以在其自己的JPanel中创建5x5 JLabel表。任何帮助不胜感激!

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

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

而它应该是

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

相关内容

  • 没有找到相关文章

最新更新