【问题标题】:Switching between jpanels implementing actionListener [duplicate]在实现actionListener的jpanels之间切换[重复]
【发布时间】:2019-05-15 01:15:42
【问题描述】:

我正在为我的 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 将被清除。我试图重新粉刷它没有帮助。任何帮助表示赞赏。谢谢

【问题讨论】:

标签: java jframe jpanel


【解决方案1】:

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

【讨论】:

  • 我尝试重新验证,但没有成功。我通过删除实现动作侦听器来修复它,但这会切断部分功能。
猜你喜欢
  • 2014-09-18
  • 2013-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多