gpt4 book ai didi

java - 在实现actionListener的jpanels之间切换

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:47 25 4
gpt4 key购买 nike

我正在为我的 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();

}

`公共(public)类 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 就会清除。我尝试重新绘制它没有帮助。任何帮助表示赞赏。谢谢

最佳答案

当你调用 repaint() 方法时,你还应该调用 revalidate() 方法。另外,你能展示一下你的主类代码吗?您是否已将按钮添加到框架中?

关于java - 在实现actionListener的jpanels之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53768340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com