[英]JLabel doesn't display anything in JFrame
I think and hope this is a minor issue. 我认为并希望这是一个小问题。
I have a JFrame
which gets displayed in a snake game. 我有一个在蛇游戏中显示的
JFrame
。 The text, eg "Game Over, your snake is crashed"
or something, will display in a JLabel
. 诸如
"Game Over, your snake is crashed"
的文本将显示在JLabel
。
The problem is my JLabel
is always empty! 问题是我的
JLabel
总是空的!
Here's the code: 这是代码:
package ch.gibb.snake1;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class endFrame extends JFrame {
/**
* Auto-generated VersionUID
*/
private static final long serialVersionUID = -6535942219723507798L;
public static void main(String[] args) {
displayFrame();
}
public static void displayFrame() {
JFrame frame = new JFrame("Game Over");
JLabel info = new JLabel("My 127.0.0.1 is my castle", JLabel.CENTER);
int height = 670;
int width = 630;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int ex = (screen.width / 2) - (width / 4); // Center horizontally.
int ey = (screen.height / 2) - (height / 4); // Center vertically.
frame.setTitle("Game Over");
frame.setBounds(ex, ey, width / 2, height / 2);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
info.setBounds(ex, ey, width/2, height/2);
frame.add(info);
frame.setVisible(true);
}
}
frame.setTitle("Game Over");
frame.setBounds(ex, ey, width / 2, height / 2);
//frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//info.setBounds(ex, ey, width / 2, height / 2);
End result: 最终结果:
The JLabel
doesnt display as you have set the X & Y co-ordinates to be outside of the JFrames
dimensions here: 当您在此处将X和Y坐标设置为不在
JFrames
尺寸之外时, JLabel
不会显示:
info.setBounds(ex, ey, width / 2, height / 2);
You need to set make this call on the JFrame
. 您需要在
JFrame
上设置进行此调用。
frame.setBounds(ex, ey, width / 2, height / 2);
Also using a layout manager will remove the need to set bounds on child components themselves. 同样,使用布局管理器将消除对子组件本身设置边界的需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.