Colby Stahl
Colby Stahl

Reputation: 67

Change JFrame's visibility from another class

I am coding a game in which I created a pause menu class PausePanel. In that class, I want to be able to set the JFrame of a different class, MainPanel, but whenever I make a method to do so, I get different errors/issues.

  1. Class Game is there to show the PausePanel initialization.
  2. Class PausePanel is shown because that's where I need help with the code.
  3. Class MainPanel has the JFrame I want to change the visibility of.

     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 );
        }
    }
    

Upvotes: 1

Views: 227

Answers (1)

c0der
c0der

Reputation: 18792

You can use Game as a control class, that listens to PausePanel and invokes methods in MainPanel.
Alternatively you can path a reference to MainPanel instance to PasuePanel:

PausePanel pp = new PausePanel(mainPanel)

Upvotes: 2

Related Questions