在使用Swing创建应用程序时,我看到人们会做两件事之一来创建JFrame.哪种方法更好,为什么?
我是Java和编程的初学者.我唯一的学习来源是书籍,YouTube和Stack Overflow.
import {imports};
public class GuiApp1 {
public static void main(String[] args) {
new GuiApp1();
}
public GuiApp1() {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Example GUI");
guiFrame.setSize(300,250);
................
}
Run Code Online (Sandbox Code Playgroud)
和
import {imports};
public class GuiApp1 extends JFrame {
public Execute() {
getContentPane().setBackground(Color.WHITE);
getContentPane().setLayout(null);
setSize(800, 600);
.............
}
public static void main(String[] args) {
Execute frame1 = new Execute();
frame1.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud) 所以我正在制作一个游戏,我有EnemyAI以及 ,player并且它们都扩展了JPanel。世界有一个null布局,所以我用来setBounds();“移动”(实际上我只是移动世界图像)entities(player和AI) 并正确放置它们。但是当我添加(看起来像是,我测试了可能的最小数字)5 时,它repaint()完全自行调用。这会导致玩家视觉上在原地行走。添加的实体越多,间隔就越快(即 5 个实体的调用repaint()比 500 个实体的调用慢得多)。
注意:window下面的类中只是一个JFrame.
主要类别:
public class Game(){
public static boolean fighting = false;
public static void startGame(){
WorldPanel game = new WorldPanel();
game.setPreferredSize(new Dimension(window.getWidth(), window.getHeight()));
PlayerPane player = new PlayerPane(32,32, "Player 1");
game.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent arg0) {
if(fighting == false){
move(player, game, arg0.isShiftDown(), arg0.getKeyCode());
} else {
System.out.println("Fighting …Run Code Online (Sandbox Code Playgroud)