我为 GameWindow 创建了一个类,它扩展了 JFrame; MainMenu 的类,它扩展了 JPanel;以及创建 GameWindow 并添加 MainMenu 的 UserInterface 类。添加MainMenu JPanel并将其添加到GameWindow JFrame并运行程序后,JFrame出现,但MainMenu JPanel不可见。
这是三个类。注意:每个类都在单独的文件中。
public class UserInterface {
public static void main(String[] args) {
GameWindow gameWindow = new GameWindow();
gameWindow.add(new MainMenu());
}
}
import javax.swing.*;
public class GameWindow extends JFrame {
GameWindow(){
this.setTitle("Brain Games");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
import java.awt.*;
import javax.swing.*;
public class MainMenu extends JPanel {
static final int SCREEN_WIDTH = 600;
static final int SREEN_HEIGHT = 600;
MainMenu(){
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SREEN_HEIGHT));
this.setBackground(Color.black);
this.setFocusable(true);
this.setVisible(true);
}
}
在
游戏窗口类
你必须声明
主菜单类
Jpanel mainMennu = new MainMenu;
并添加了
this.add(mainMenu);