Java,JFrame:getWidth()返回0 [英] Java, JFrame: getWidth() returns 0

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

问题描述

setExtendedState(getExtendedState()|JFrame.MAXIMIZED_BOTH);
setResizable(false);
setUndecorated(true);
System.out.println("--------> "+getContentPane().getWidth()); //----> 0 why is this happening?

我正在尝试确定JFrame的大小。我在谷歌搜索并检查了文档,我仍然不知道为什么它不会工作
它可以正常使用任何其他控件我试用它

I'm trying to determine the size of a JFrame. I've searched on google and checked the documentation and I still don't know why it won't work It works fine on about any other control I try it on

编辑:
frame.getWidth()在类外部调用时工作(扩展JFrame)
仍然,如果我替换

frame.getWidth() works when called outside of the class (that extends JFrame) still, if I replace

System.out.println("--------> "+getContentPane().getWidth());

with

System.out.println("--------> "+this.getWidth());

getWidth仍将返回0

getWidth will still return 0

EDIT2 :
我需要框架的大小才能将其设置为可见和东西。我需要为框架添加其他控件,它们的坐标和大小取决于框架的大小。

I need the frame's size before setting it visible and stuff. I need to add other controls to the frame and their coordinates and size depend on the frame's size.

推荐答案

你之所以得到它0是因为你没有调用pack(),setSize(int,int)或setSize(Dimension)中的任何一个。这只是在调用其中一种方法时才会计算帧的布局。

The reason why you got 0 is because you didn't call any of the pack(), setSize(int, int) or setSize(Dimension). This is only when calling one of these method that the layout of your frame will be computed.

JFrame frame = new JFrame("My Frame");
frame.setExtendedState(getExtendedState()|JFrame.MAXIMIZED_BOTH);
frame.setResizable(false);
frame.setUndecorated(true);
frame.pack(); // Important line!!! 
frame.setVisible(true);
System.out.println("--------> "+getContentPane().getWidth());

这篇关于Java,JFrame:getWidth()返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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