简体   繁体   English

从另一个类更改JFrame的可见性

[英]Change JFrame's visibility from another class

I am coding a game in which I created a pause menu class PausePanel . 我正在编写一个游戏,在其中创建了一个暂停菜单类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. 在该类中,我希望能够设置另一个类MainPanelJFrame ,但是每当我创建一个这样做的方法时,都会遇到不同的错误/问题。

  1. Class Game is there to show the PausePanel initialization. Game在那里显示PausePanel初始化。
  2. Class PausePanel is shown because that's where I need help with the code. 显示了PausePanel类,因为这是我需要代码帮助的地方。
  3. Class MainPanel has the JFrame I want to change the visibility of. 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 ); } } 

You can use Game as a control class, that listens to PausePanel and invokes methods in MainPanel . 您可以将Game用作控件类,该类侦听PausePanel并调用MainPanel方法。
Alternatively you can path a reference to MainPanel instance to PasuePanel : 或者,您可以MainPanel实例的引用路径MainPanelPasuePanel

PausePanel pp = new PausePanel(mainPanel)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM