简体   繁体   English

将GridLayout JPanel放置到GridBagLayout JFrame上

[英]Placing GridLayout JPanels onto a GridBagLayout JFrame

I'm trying to place two JPanels onto a JFrame using GridBagLayout. 我正在尝试使用GridBagLayout将两个JPanels放置到JFrame上。 The first JPanel uses gridLayout to create 35 columns and 27 rows of JButtons, and should have a width of 3/4 of the JFrame. 第一个JPanel使用gridLayout创建35列和27行的JButton,并且其宽度应为JFrame的3/4。 This panel needs to fill the vertical space available to it. 该面板需要填充可用的垂直空间。 The second JPanel also uses gridLayout and should fill the last 1/4 of the main JFrame. 第二个JPanel也使用gridLayout,并且应填充主JFrame的最后1/4。

Unfortunately, my first JPanel (sPan) isn't even fitting properly on the screen, and is forcing the whole second JPanel (cPan) off of the screen. 不幸的是,我的第一个JPanel(sPan)甚至无法正确地显示在屏幕上,并且将整个第二个JPanel(cPan)强制从屏幕上移开。 How can I constrain these values to take up only their allowed proportion on the screen without them moving each other around? 如何限制这些值只占据它们在屏幕上允许的比例,而不让它们彼此移动?

If I use a blank JPanel with a background colour with my code, everything works out perfectly fine: 如果我在代码中使用具有背景颜色的空白JPanel,则一切工作都很好:

空白的JPanel比例 [1] [1]

However, when I use my JPanel consisting of JButtons, the proportions get completely messed up: 但是,当我使用由JButton组成的JPanel时,比例完全混乱了:

JButtons JPanel比例 [2] [2]

I speculate that when I instantiate my sPan object, it's sizing each button to accommodate the size of the whole JFrame. 我推测当实例化我的sPan对象时,它正在调整每个按钮的大小以适应整个JFrame的大小。 Then when I instantiate the cPan object and try to place it next to the sPan object, the buttons aren't resizing themselves to accommodate the additional panel in the main JFrame. 然后,当我实例化cPan对象并尝试将其放置在sPan对象旁边时,按钮不会自动调整大小以适应主JFrame中的其他面板。 Does anybody know how I can fix this? 有人知道我该如何解决吗?

I have to use GridBagLayout for this assignment, so using normal gridLayout isn't an option. 我必须使用GridBagLayout进行此分配,因此不能使用常规的gridLayout。 Any tips regarding what's happening would be appreciated. 关于正在发生的事情的任何提示将不胜感激。

Could you simply deal with two columns ? 您可以简单地处理两列吗? The first one taking 5/6 of the available width and the second one taking the 1/6th remaining ? 第一个占可用宽度的5/6,第二个占剩余 宽度1/6

You could try the following: 您可以尝试以下方法:

final JPanel sPan = new JPanel();
sPan.setBackground(Color.RED);
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 5 / 6f;  // change this value...
constraints.weighty = 1.00;
add(sPan, constraints);

final JPanel cPan = new JPanel();
cPan.setBackground(Color.BLUE);
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1 / 6f;  // ... and this one.
constraints.weighty = 1.00;
add(cPan, constraints);

Please note: I replaced your JPanels by some empty JPanels with a background color , so even like this you can see what's going on. 请注意:我用一些带有背景色的JPanels替换了您的JPanels ,所以即使这样您也可以看到发生了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM