Java 使用GridBagConstraints的怪异布局
我有几种方法可以在Java 使用GridBagConstraints的怪异布局,java,swing,user-interface,layout,gridbaglayout,Java,Swing,User Interface,Layout,Gridbaglayout,我有几种方法可以在JPanel中创建自己的组件,JButton或JLabel。然后我有一个单独的方法将所有这些jpanel添加到JFrame。我还在jpanel上使用gridx和gridy来定位它们。这是:在左边看回复,然后在右上角看标题,在下面的2X2表格中看退出、重新启动、拾取和hello。然而,我当前的代码在运行时显示了一个奇怪的、随机的布局 lookreply在左侧,但在右侧是quit、空格、restart,然后hello all vertical。没有看到皮卡和标题。我不知道为什么会这
JPanel
中创建自己的组件,JButton
或JLabel
。然后我有一个单独的方法将所有这些jpanel
添加到JFrame
。我还在jpanel上使用gridx
和gridy
来定位它们。这是:在左边看回复,然后在右上角看标题,在下面的2X2
表格中看退出、重新启动、拾取和hello。然而,我当前的代码在运行时显示了一个奇怪的、随机的布局
lookreply在左侧,但在右侧是quit、空格、restart,然后hello all vertical。没有看到皮卡和标题。我不知道为什么会这样
请参阅下面我的代码:
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);
}
方法之一(退出)
除了标题是a
JLabel
外,所有其他方法几乎相同,并且该表在其自身的JPanel
内迭代创建5x5
JLabel表。感谢您的帮助 我已经找到了做这件事的原因。
如代码所示,我在设置布局之前添加了组件
screen.add(lookReply(), c);
c.gridy = 0;
c.gridx = 0;
然而它应该是
c.gridy = 0;
c.gridx = 0;
screen.add(lookReply(), c);
为什么你们的类要扩展JPanel?您有一个方法“create()”,该方法创建JFrame并将组件添加到框架中。您没有将GUI类添加到框架中,那么为什么它是JPanel呢?张贴您的文章,说明问题所在。@camickr我认为当使用GUI做任何事情时,您必须扩展JPanel?我一定错了。我该如何发布我的SSCCE?它就在曲里吗?
c.gridy = 0;
c.gridx = 0;
screen.add(lookReply(), c);