java 里的pack(),使用Java 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();

Class 2:

public class JavaGui extends javax.swing.JFrame

{

public JavaGui()

{

getContentPane().setLayout(null);

..

getContentPane().add(panelLeft);

...

getContentPane().add(panelRight);

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.

解决方案

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(...) and pack(). The layouts mostly respect the preferred sizes of components, not their sizes.

Instead:

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(), then setLocationByPlatform(true) (I think), then setVisible(true).

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:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值