我正在为Java游戏构建一个菜单,当我单击按钮时,我需要能够切换到我的游戏JPanel。这就是我所拥有的
public class Menu extends JPanel implements ActionListener {
protected JFrame frame;
JButton btnStart = new JButton();
public Menu(JFrame j) {
super();
frame = j;
//creating and styling button
btnStart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
StartGame();
}
});
}
private void StartGame(){
frame.getContentPane().removeAll();
frame.getContentPane().add(new Main(frame));
frame.repaint();
}
` 公共类Main扩展Universe实现ActionListener {
Timer timer = new Timer(75, this);
JFrame frame;
//@Override
public void actionPerformed(ActionEvent e) {
repaint();;
if(isLoss()){
timer.stop();
}
//update cretures
}
public Main(JFrame frame) {
super();
frame.setLayout(null);
frame.setLayout(null);
//frame.getContentPane().setLayout(null);
this.setBackground(Color.BLACK);
this.map = new Map();
StartUpHeight = 100;
this.Size = 30;
//this.playerCol = new Collision(map, pacman, Size);
pacman = new Player(1*Size, 4*Size, Size / 5, map, this.Size);
red = new RedGhost(9*Size, 8*Size, Size / 6, map, pacman, this.Size);
pinky = new PinkGhost(8*Size, 10*Size, Size / 6, map, pacman, this.Size);
inky = new BlueGhost(9*Size, 10*Size, Size / 6, map, pacman, this.Size, red);
clyde = new YellowGhost(10*Size, 10*Size, Size/6, map, pacman, this.Size);
timer.start();
this.frame = frame;
this.frame.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
pacman.keyPressed(e, Size);
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
pacman.keyReleased(e);
}
});
setUpPanel();
}
@Override
public void paint(Graphics g) {
//drawing map
//drawing pacman
//drawing ghosts
}
`
我尝试了到目前为止在互联网上找到的所有内容。 Main从jpanel扩展而来,并像Menu一样实现了动作监听器。执行此代码后,我的jframe便清除了。我试图重新粉刷它没有帮助。任何帮助表示赞赏。谢谢
答案 0 :(得分:0)
调用repaint()方法时,还应该调用revalidate()方法。 另外,您可以显示您的主班代码吗? 并将按钮添加到框架中吗?