我真的很困惑这个。我制作游戏“Microtrip”。这是手机游戏,但我正在为个人电脑做。我有一个扩展JPanel的背景类,它只绘制一个从0,0开始并具有屏幕大小(我的游戏是全屏)的矩形。我有一个扩展JPanel的主菜单类。我想为主菜单添加所有内容。然后,我将所有内容添加到扩展JFrame的GameFrame类中。我有一个主类,只是调用GameFrame类。这里是我的代码: 背景类:在将JPanel添加到JPanel时,第一个JPanel的大小变得更低
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Background extends JPanel{
int width, height;
Color backgroundBlue;
public Background(int width, int height){
this.width = width;
this.height = height;
backgroundBlue = new Color(25, 159, 229);
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(backgroundBlue);
g.fillRect(0, 0, this.width, this.height);
}
}
的MainMenu类:
import javax.swing.*;
@SuppressWarnings("serial")
public class MainMenu extends JPanel{
Background background;
public MainMenu(int WW, int WH){
//WW = window width
//WH = widow height
this.setLocation(0, 0);
this.setSize(WW, WH);
background = new Background(WW, WH);
this.add(background);
}
}
GameFrame类:
import main_menu.MainMenu;
import main_menu.*;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import javax.swing.JFrame;
import java.awt.event.*;
@SuppressWarnings("serial")
public class GameFrame extends JFrame{
private GraphicsDevice vc;
private MainMenu mainMenu;
//private Background background;
public GameFrame(){
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
mainMenu = new MainMenu((int)screenSize.getWidth(), (int) screenSize.getHeight());
/*background = new Background((int)screenSize.getWidth(), (int) screenSize.getHeight());*/
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc= e.getDefaultScreenDevice();
this.setTitle("Mictrotrip");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(0, 0, (int)screenSize.getWidth(), (int)screenSize.getHeight());
this.add(mainMenu);
//this.add(background);
this.setLocationRelativeTo(null);
this.setUndecorated(true);
this.setResizable(false);
vc.setFullScreenWindow(this);
addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
System.exit(0);
}
}
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
});
}
}
,我的主要类:
public class Main {
public static void main(String[] args) {
new GameFrame();
}
}
当我运行它只是表明顶部中心的一个小矩形。 我做了以下实验:
我忽略了mainmenu类,并直接在JFrame中添加背景(GameFrame中的注释行),并且一切正常。为什么? 我读过所有类似的问题,但没有人帮助我。
Thacks老兄,你帮了我很多! – FreakyOne