【问题标题】:Weird layout using GridBagConstraints使用 GridBagConstraints 的奇怪布局
【发布时间】:2014-05-14 06:01:51
【问题描述】:

我有几种方法可以创建自己的组件,JButtonJLabelJPanel 中。然后我有一个单独的方法来添加所有这些JPanelsJFrame。我还在 JPanel 上使用 gridxgridy 来定位它们我想要的位置。这是:在左侧查找回复,然后在 2X2 表中的右上角和下面的标题退出、重新启动、拾取和你好。但是,我当前的代码在运行时会显示一个奇怪的随机布局。

lookreply 是在左边,然后右边是 quit,一个空格,restart 然后 hello all 垂直。没有看到拾取和标题。我不知道为什么会这样。

请看下面我的代码:

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 中迭代以创建JLabel5x5 表。任何帮助表示赞赏!

【问题讨论】:

  • 为什么你的类要扩展 JPanel?您有一个创建 JFrame 并将组件添加到框架的方法“create()”。您没有将 GUI 类添加到框架中,那么为什么它是 JPanel?发布您的 SSCCE 来证明问题。
  • @camickr 我想当你用 GUI 做任何事情时,你必须扩展 JPanel?我一定是错的。我该如何发布我的 SSCCE?只是在曲子里吗?

标签: java swing user-interface layout gridbaglayout


【解决方案1】:

我找到了这样做的原因。 从代码中可以看出,我在设置布局之前添加了组件。

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

应该是这样的

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

【讨论】:

    猜你喜欢
    • 2012-11-27
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 2014-02-25
    • 2010-10-07
    • 2014-11-10
    相关资源
    最近更新 更多