我看到了this video [ 10:00 ] 开始用 Java 创建 2d 游戏,我尝试使用他在视频中使用的代码,但出现错误,我不知道如何修复他。
package me.Kenig.game2d;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 160;
public static final int HEIGHT = WIDTH/12*9;
public static final int SCALE = 3;
public static final String NAME = "Game";
private JFrame frame; // error
public Game(){
setMinimumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
setMaximumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // error
@Override
public void run() {
// TODO Auto-generated method stub
}
}
最佳答案
1)你永远不会实例化你的 JFrame
尝试
this.frame = new JFrame();
在你的构造函数中
2)另一个问题:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
不在正确的位置:它应该在方法中。您还应该更喜欢 WindowConstants.EXIT_ON_CLOSE
而不是 JFrame.EXIT_ON_CLOSE
。
3)您还应该调用frame.pack()
来强制框架调整其大小以适应其所包含元素的大小。
这是一段代码:
public Game(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
setMaximumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
//Not really necessary because of frame.pack()
//setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
//You should add some elements here
JPanel panel=new JPanel();
panel.add(new JTextField(10));
frame.add(panel);
//Forces the frame to take the minimum-size to contain its elements
frame.pack();
frame.show();
}
您应该查看Visual guide to Swing components查看存在哪些组件以及它们的行为方式。
您还应该看看visual guide to layout managers了解码件的放置方式
祝你好运:)
关于java - JFrame 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16797476/