使用Java pack()方法 [英] Using Java pack() method
问题描述
我无法使pack()方法有效。我尝试了几件事。我的代码目前看起来像这样:
I can't make the pack() method work. I tried several things. My code looks like this at the moment:
Class 1:
public static void main( String[] args )
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run()
{
JavaGui mygui = new JavaGui();
// mygui.setSize(1154, 753);
mygui.setVisible(true);
mygui.pack();
第2类:
public class JavaGui extends javax.swing.JFrame
{
public JavaGui()
{
getContentPane().setLayout(null);
..
getContentPane().add(panelLeft);
...
getContentPane().add(panelRight);
我尝试将pack方法放在任何地方,但它不能用这种添加gui元素的方式。任何建议为什么?我也尝试将所有内容添加到JFrame而不是getContentPane() ,不我无法做到这一点。
I tried putting the pack method in everywhere, but it's not going to work with this way of adding gui elements. Any suggestions why? I also tried adding everything to a JFrame instead of the getContentPane(), but I can't make that work either.
推荐答案
- 不要将null布局与
pack()的
。 pack方法告诉布局管理器和组件以最佳方式调整自己的大小,如果你使用null布局,那么gui可能会缩小到最小的大小,因为没有布局可以将它们组合在一起。 - 大多数情况下根本不使用空布局。利用这些风险,您可以创建几乎无法扩展,改进和调试的严格GUI。
- 不要使用
setSize(...)
和pack()
。布局主要考虑组件的首选尺寸,而不是尺寸。
- Don't use null layouts together with
pack()
. The pack method tells the layout managers and components to size themselves optimally, and if you instead use null layouts, then the gui risks shrinking to a minimal size, since there is no layout to hold it together. - Don't use null layouts at all for the most part. Using these risk your creating rigid GUI's that are almost impossible to extend, improve, debug.
- Don't use
setSize(...)
andpack()
. The layouts mostly respect the preferred sizes of components, not their sizes.
相反:
- 使用令人愉悦且合理的嵌套JPanel组合,每个组合使用自己的布局管理器。
- 让组件和布局管理器自行调整大小。
- 然后打包应该有帮助。
- 我做的一般订单是将所有组件添加到GUI,然后调用
pack ()
,然后setLocationByPlatform(true)
(我认为),然后setVisible(true)
。
- Use a pleasing and sensible combination of nested JPanels, each using its own layout manager.
- Let the components and the layout managers size themselves.
- Then pack should help.
- The general order that I do is to add all components to the GUI, then call
pack()
, thensetLocationByPlatform(true)
(I think), thensetVisible(true)
.
如需更好的帮助,请查看 Swing布局管理器教程。
For better help, please check out the Swing Layout Manager Tutorials.
以下是关于其他问题的几个例子此网站使用各种布局管理器:
Here are a couple examples to other questions on this site that use various layout managers:
- BorderLayout和GridLayout的组合o创建计算器
- 标签和JTextFields的BorderLayout和BoxLayout组合
- 使用GridBagLayout创建灵活的标签/文本字段网格
- A combination of BorderLayout and GridLayout to create a calculator
- BorderLayout and BoxLayout Combination for labels and JTextFields
- Using GridBagLayout to create flexible label/textfield grid
这篇关于使用Java pack()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!