我正在编写一个使用 swing 组件的应用程序,我注意到一件事我需要解释一下 我有这些类(class):
我在其上实例化 gui 维度的枚举
public enum GuiDimension { WIDTH(700), HEIGHT(400); private final int value; private GuiDimension(int value) { this.value = value; } public int getValue(){ return value; } }
启动应用程序的此类
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); } }
和这个设置面板大小的类
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 } }
我注意到,枚举确实不是整数而是对象,但是当我返回时
GuiDimension.WIDTH.getValue()
GuiDimension.HEIGHT.getValue()
它们返回整数,这些整数一旦被采用就可以很好地用于其他目的。
现在如果我将这个插入:
SetSize (new Dimension (GuiDimension.WIDTH.getValue (), GuiDimension.HEIGHT.getValue ()));
或
SetSize (GuiDimension.WIDTH.getValue (), GuiDimension.HEIGHT.getValue ());
代替我在示例中插入的这个
setPreferredSize(new Dimension(GuiDimension.WIDTH.getValue(),GuiDimension.HEIGHT.getValue()));
框架显示的尺寸错误,我不明白为什么。
如果GuiDimension.WIDTH.getValue ()
和 GuiDimension.WIDTH.getValue ())
对 setPreferredSize (...)
是正确的,
为什么 setSize (int,int)
不一样和 setSize(Dimension)
?
当测试这个简单的代码时,您可以看到这一点。
最佳答案
大多数布局管理器会忽略调用组件的大小,但会尊重其首选大小,有时还有最小值和最大值,因此当您调用 pack()
时,您的大小将更改为布局管理器和构成组件的首选尺寸认为应该是最佳尺寸。
顺便说一下,根据 kleopatra (Jeanette),如果您确实需要设置组件的首选大小,那么最好覆盖 getPreferredSize()
而不是调用 setPreferredSize(...)
。后者可以通过在其他地方的同一组件上调用 setPreferredSize(...)
来覆盖,而前者不能。
顺便说一句,在您的示例代码中,您使用了 WIDTH 两次并且似乎没有使用 HEIGHT。
编辑
您有一条关于包装和组件尺寸的评论已被删除。我的回复是:
pack()
方法请求布局管理器对组件进行布局,布局管理器在这里很重要——他们看什么,大小与 preferredSizes。如果您阅读了大多数布局管理器的 javadoc 和教程,您会发现它们最尊重首选大小。有些,例如 BoxLayout,也会查看最大尺寸和最小尺寸。
关于java - 设置JPanel的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22430308/