标题栏仅在我单击“运行”后才显示,框架不起作用...... 这是我的代码 我不知道发生了什么事! 有人能帮我吗?
import java.awt.Canvas;
import javax.swing.JFrame;
public class Display extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 800;
public static final int HEIGH = 600;
public static String TITLE = "3D Game";
private Thread thread;
private boolean running = false;
private void start(){
if(running) return;
running = true;
thread = new Thread();
thread.start();
System.out.println("Working");
}
private void stop(){
if(!running)
return;
running = false;
try{
thread.join();
}catch (Exception e){
e.printStackTrace();
System.exit(0);
}
}
public void run(){
while(running){
}
}
public static void main(String[] args){
Display game = new Display();
JFrame frame = new JFrame();
frame.add(game);
//frame.pack();
frame.setTitle(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH,HEIGHT);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
game.start();
}
}
最佳答案
看看两者的区别
public static final int HEIGH = 600;
和
frame.setSize(WIDTH, HEIGHT);
Canvas
间接定义两个public static
名为 WIDTH
的字段和HEIGHT
设置为1
和2
分别
更好的解决方案是覆盖 Canvas
getPreferredSize
方法并返回您想要的首选尺寸...
@Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
你可以只使用包
Display game = new Display();
JFrame frame = new JFrame();
frame.add(game);
frame.pack();
frame.setTitle(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
反对使用setSize
的一句话或警告在顶层容器上。窗口通常包含框架装饰,这些装饰包含在窗口边界内。如果您使用setSize
,您将通过窗口装饰的数量来减少内容区域,这将导致尺寸小于预期。相反,您应该覆盖 getPreferredSize
主容器的方法并调用 pack
。这允许窗口将自身“包装”在内容周围,但为框架装饰留出空间,从而保留您所请求的空间。
您还可以查看:
- How to get JPanel equal width and height
- How to get the EXACT middle of a screen, even when re-sized
- Graphics rendering in title bar
- How can I set in the midst?
了解更多详情
关于java - 仅显示标题栏,不显示 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43431689/