使用GridBagConstraints的怪异布局 [英] Weird layout using GridBagConstraints
问题描述
我有几种方法可以在JPanel
中创建自己的组件JButton
或JLabel
.然后,我有一个单独的方法,将所有这些JPanels
和JFrame
相加.我还在JPanels上使用gridx
和gridy
来按我的意愿放置它们.这是:在左侧的lookreply,然后在标题的右上角,并在2X2
表中的下方,退出,重新启动,拾取并打个招呼.但是我当前的代码在运行时显示了一个奇怪的,随机的布局.
I have several methods which create their own component, JButton
or JLabel
in a JPanel
. Then I have a separate method which adds all these JPanels
the the JFrame
. I also use gridx
and gridy
on the JPanels to position them how I want. This is: lookreply on the left, then top right the title and below in a 2X2
table quit, restart, pickup and hello. However my current code when run displays a weird, random layout.
lookreply在左侧,但在右侧则退出,留一个空格,重新启动,然后全部垂直打招呼.看不到皮卡和标题.我不知道为什么会这样.
The lookreply is on the left, but then to the right is quit, a space, restart then hello all vertical. pickup and title aren't seen. I dont know why this is happening.
请在下面查看我的代码.
Please see my code below.:
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
中创建JLabel
的5x5
表.感谢您的帮助!
All the other methods are pretty much the same except the title is a a JLabel
and the table iterates to create a 5x5
table of JLabel
within its own JPanel
. Any help is appreciated!
推荐答案
我已经找到了正在执行的操作. 如代码所示,我是在设置布局之前添加组件的.
I have found what was doing this. As seen in the code I was adding the component before setting the layout.
screen.add(lookReply(), c);
c.gridy = 0;
c.gridx = 0;
应该是
c.gridy = 0;
c.gridx = 0;
screen.add(lookReply(), c);
这篇关于使用GridBagConstraints的怪异布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!