我正在创建一个小游戏,并且有一个带有按钮的菜单方法可以启动实际游戏。我只想要一个帧来完成所有这些,但是当我将jframe作为参数传递给游戏方法时,游戏就变成了一个空白帧。
这是我的代码。我使用调试器,发现从不调用paint方法。
public class GameMenu
{
public void start()
{
JFrame frame = new JFrame();
frame.setSize(480,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
Background background = new Background(frame);
}
}
public class Background extends JPanel implements KeyListener , ActionListener
{
private JFrame frame;
private Player player1;
private ObstacleControl obsControl;
private SpeedBuffControl spdBuffControl;
private ExtraLifeControl lifeControl;
private Timer timer;
private int lifeCount;
private int xLeft;
private int xRight;
private int yDown;
private int yUp;
public Background(JFrame frame)
{
frame.add(this);
startGame();
}
public void startGame()
{
timer = new Timer(20000,this);
obsControl = new ObstacleControl(this);
spdBuffControl = new SpeedBuffControl(this);
lifeControl = new ExtraLifeControl(this);
timer.start();
player1 = new Player(this);
lifeCount = 3;
xLeft = -4;
xRight = 4;
yDown = 4;
yUp = -4;
}
public void resetPlayer()
{
if(lifeCount>1)
{
player1 = new Player(this);
obsControl.resetObstacle();
lifeCount--;
}
else
System.out.println("you are dead");
}
public void actionPerformed(ActionEvent event)
{
obsControl.increaseDifficulty();
spdBuffControl.addBuff();
lifeControl.addExtraLife();
}
public void paint(Graphics g)
{
g.setColor(new Color(149,146,240));
g.fillRect(0,0,480,600);
player1.draw(g);
obsControl.draw(g);
spdBuffControl.draw(g);
lifeControl.draw(g);
g.dispose();
repaint();
}
答案 0 :(得分:2)
Swing在更新布局时很懒惰
而不是
frame.setVisible(true);
Background background = new Background(frame);
你应该做......
Background background = new Background(frame);
frame.setVisible(true);
但这引出了为什么你要打扰的问题,相反,你真的应该这样做......
JFrame frame = new JFrame();
frame.setResizable(false);
frame.setSize(480,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Background());
frame.setVisible(true);
并且没有将JFrame
传递给Background
,它不需要它
这在很多层面都是错的......
public void paint(Graphics g)
{
g.setColor(new Color(149,146,240));
g.fillRect(0,0,480,600);
player1.draw(g);
obsControl.draw(g);
spdBuffControl.draw(g);
lifeControl.draw(g);
g.dispose();
repaint();
}
paintComponent
代替paint
super
方法dispose
上下文中调用Graphics
repaint
(或调用任何可能调用repaint
的方法)有关详细信息,请查看Painting in AWT and Swing和Performing Custom Painting