使用Java pack()方法 [英] Using Java pack() method

查看:370
本文介绍了使用Java pack()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使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.

推荐答案


  1. 不要将null布局与 pack()的。 pack方法告诉布局管理器和组件以最佳方式调整自己的大小,如果你使用null布局,那么gui可能会缩小到最小的大小,因为没有布局可以将它们组合在一起。

  2. 大多数情况下根本不使用空布局。利用这些风险,您可以创建几乎无法扩展,改进和调试的严格GUI。

  3. 不要使用 setSize(...) pack()。布局主要考虑组件的首选尺寸,而不是尺寸。

  1. 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.
  2. 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.
  3. Don't use setSize(...) and pack(). The layouts mostly respect the preferred sizes of components, not their sizes.

相反:


  1. 使用令人愉悦且合理的嵌套JPanel组合,每个组合使用自己的布局管理器。

  2. 让组件和布局管理器自行调整大小。

  3. 然后打包应该有帮助。

  4. 我做的一般订单是将所有组件添加到GUI,然后调用 pack (),然后 setLocationByPlatform(true)(我认为),然后 setVisible(true)

  1. Use a pleasing and sensible combination of nested JPanels, each using its own layout manager.
  2. Let the components and the layout managers size themselves.
  3. Then pack should help.
  4. 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).

如需更好的帮助,请查看 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:

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆