无法使用setLocationRelativeTo(null)将JFrame置于中心位置。

huangapple go评论105阅读模式
英文:

can't make Jframe in center using setLocationRelativeTo(null);

问题

我有一个 JFrame,当我使用

setLocationRelativeTo(null);

这个方法时,这个 JFrame 并没有出现在窗口的中间,为什么会这样呢?下面是我的完整代码:

JFrame ca = new JFrame("Start");
ca.setUndecorated(true);
ca.setLocationRelativeTo(null);
JLabel lab = new JLabel("   Space Invaders");
JButton bu = new JButton("START");
JButton bu2 = new JButton("QUIT");
lab.setFont(new Font("Serif Italic", Font.BOLD, 60));
lab.setForeground(Color.RED);
bu.setForeground(Color.WHITE);
bu.setBackground(Color.BLACK);
bu.setFont(new Font("serif", Font.BOLD, 50));
bu.setBorderPainted(false);
bu2.setForeground(Color.WHITE);
bu2.setBackground(Color.BLACK);
bu2.setFont(new Font("serif", Font.BOLD, 50));
bu2.setBorderPainted(false);

我的输出是这样的:

无法使用setLocationRelativeTo(null)将JFrame置于中心位置。

英文:

I have a jframe when i use

setLocationRelativeTo(null);

the JFrame does not appear at the middle of window why it is so
my full code-

JFrame ca = new JFrame("Start");
ca.setUndecorated(true);
ca.setLocationRelativeTo(null);
JLabel lab = new JLabel("   Space Invaders");
JButton bu = new JButton("START");
JButton bu2 = new JButton("QUIT");
lab.setFont(new Font("Serif Italic", Font.BOLD, 60));
lab.setForeground(Color.RED);
bu.setForeground(Color.WHITE);
bu.setBackground(Color.BLACK);
bu.setFont(new Font("serif", Font.BOLD, 50));
bu.setBorderPainted(false);
bu2.setForeground(Color.WHITE);
bu2.setBackground(Color.BLACK);
bu2.setFont(new Font("serif", Font.BOLD, 50));
bu2.setBorderPainted(false);

My Output is this-无法使用setLocationRelativeTo(null)将JFrame置于中心位置。

答案1

得分: 1

setLocationRelativeTo(null);

必须在向框架添加组件并对框架调用 pack() 之后调用,否则框架的大小为 (0, 0),无法正确居中。

编辑:

JFrame frame = new JFrame(...);
frame.add(someComponent);
frame.add(anotherComponent);
frame.pack(); // 现在框架的宽度/高度大于 0。
frame.setLocationRelativeTo( null );
frame.setVisible( true );
英文:
setLocationRelativeTo(null);

Must be invoked AFTER you have added components to the frame and invoked pack() on the frame, otherwise the frame has a size of (0, 0) so it can't be centered properly.

Edit:

JFrame frame = new JFrame(...);
frame.add(someComponent);
frame.add(anotherComponent);
frame.pack(); // now the frame width/height is greater than 0.
frame.setLocationRelativeTo( null );
frame.setVisible( true );

huangapple
  • 本文由 发表于 2020年10月15日 00:19:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/64357544.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定