设置JPanel的大小

OiR*_*iRc 6 java swing

我正在编写一个与swing组件一起工作的应用程序,我注意到一件事,我会解释我有这些类:

  1. 这个枚举我实例化了gui维度

    public  enum GuiDimension {
     WIDTH(700), HEIGHT(400);
     private final int value;
         private GuiDimension(int value) {
    this.value = value;
         }
         public int getValue(){
    return value;
     }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 这个启动应用程序的类

    private GamePanel gamePanel = new GamePanel();
      public static void main(String[] args) {
       new MainFrame();
    }
       public MainFrame() {
        initGameFrame();
        }
    
        private void initGameFrame() {
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         add(gamePanel);
         setResizable(false);
         setUndecorated(true);
         pack();
         setVisible(true);
         setLocationRelativeTo(null);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 这个类设置了面板的大小

    public class GamePanel extends JPanel {
     public GamePanel() {
    setPreferredSize(new Dimension(GuiDimension.WIDTH.getValue(),GuiDimension.HEIGHT.getValue()));
    
    //it makes other stuff that are not of interest for this contest
         }
    
     }
    
    Run Code Online (Sandbox Code Playgroud)

    我注意到的是,枚举确实不是整数而是对象,但是当我回来时

    • GuiDimension.WIDTH.getValue()

    • GuiDimension.HEIGHT.getValue()

它们返回的整数一旦被采用就可以用于其他目的.

现在,如果我插入:

SetSize (new Dimension (GuiDimension.WIDTH.getValue (), GuiDimension.HEIGHT.getValue ())); 
Run Code Online (Sandbox Code Playgroud)

要么

SetSize (GuiDimension.WIDTH.getValue (), GuiDimension.HEIGHT.getValue ()); 
Run Code Online (Sandbox Code Playgroud)

而不是这个,我在示例中插入

setPreferredSize(new Dimension(GuiDimension.WIDTH.getValue(),GuiDimension.HEIGHT.getValue()));
Run Code Online (Sandbox Code Playgroud)

框架显示的尺寸错误,我不明白为什么.如果GuiDimension.WIDTH.getValue ()并且GuiDimension.WIDTH.getValue ())是正确的setPreferredSize (...),

为什么是不一样的setSize (int,int)setSize(Dimension)

在测试这个简单的代码时,您可以看到.

Hov*_*els 7

大多数布局管理器会忽略调用组件的大小,但会尊重其preferredSize,有时会考虑最小值和最大值,因此当您调用时pack(),您的大小将更改为布局管理器和组件组件首选大小认为应该是最佳的尺寸.

顺便提一下,按照kleopatra(Jeanette)的说法,如果你绝对需要设置一个组件的首选大小,那么你最好getPreferredSize()不要通过调用来覆盖setPreferredSize(...).后者可以通过setPreferredSize(...)在其他地方调用相同的组件来覆盖,而前者则不能.

顺便说一句,在您的示例代码中,您使用WIDTH两次并且似乎没有使用HEIGHT.


编辑
您有关于包和组件大小的删除注释.我的答复是:

pack()方法要求布局管理器对组件进行布局,并且布局管理器在这里很重要 - 它们看起来是什么,大小与preferredSizes相比.如果您阅读了大多数布局管理器的javadoc和教程,您会发现它们最符合首选大小.有些像BoxLayout一样,也会考虑最大尺寸和最小尺寸.