【问题标题】:Change JFrame's visibility from another class从另一个类更改 JFrame 的可见性
【发布时间】:2023-04-02 16:20:01
【问题描述】:

我正在编写一个游戏,我在其中创建了一个暂停菜单类PausePanel。在那个类中,我希望能够设置不同类MainPanelJFrame,但是每当我创建一个方法来这样做时,我都会遇到不同的错误/问题。

  1. Game 类用于显示 PausePanel 初始化。
  2. 显示类 PausePanel 是因为我需要代码方面的帮助。
  3. MainPanel 类有 JFrame 我想更改其可见性。

     public class Game extends JFrame{ //Contains the game's panel
         public static void main( String[] args){
         Game g1 = new Game();
         g1.play();
     }
     public Game(){
         setVisible(true);
         //other stuff
     }
     //other methods
     private class Keys extends KeyAdapter {
         @Override
         public void keyPressed(KeyEvent e){
         if (e.getKeyCode() == KeyEvent.VK_ESCAPE){
             setVisible(false);
             MainPanel.pause();
             PausePanel pp = new PausePanel( );
             pp.setBackground( Color.BLACK );
             pp.setPreferredSize( new Dimension(WIDTH,HEIGHT) );
             pp.setLayout( null );
    }}}
    
    
    
    public class PausePanel extends JFrame{ //Title Screen
        public PausePanel(){
            //other stuff
        }
        private class ButtonListener implements ActionListener{
            public void actionPerformed(ActionEvent e) {
                if (e.getSource().equals(continu)){
                    visibility(true); <------The issue
                }
     }}} 
    
    
    
    public class MainPanel extends JPanel{ //Actual game
        private JPanel jp = new JPanel();
        public MainPanel(){
            //stuff
        }
        public void visibility( boolean b ){ <----This is the method I'd like to be able to use
            jp.setVisible( b );
        }
    }
    

【问题讨论】:

  • 你不能只靠自己做visibility(true)。您必须为您的PausePanel 实例提供MainPanel 的一些实例(我们称之为mp),以便您可以执行mp.visibility(true)。事实上,mp 可能需要成为 Game 类的实例变量。

标签: java methods jframe jpanel public


【解决方案1】:

您可以将Game 用作控制类,它侦听PausePanel 并调用MainPanel 中的方法。
或者,您可以将对MainPanel 实例的引用指向PasuePanel

PausePanel pp = new PausePanel(mainPanel)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 2020-04-07
    • 2023-03-10
    • 2020-08-25
    相关资源
    最近更新 更多