2010-11-26 80 views
14

La aplicación que estoy desarrollando es un juego. Lo que quiero hacer es tener JPanels que aparezcan en el JFrame, como una ventana de texto o mensaje, y luego desaparecerán cuando ya no se usen. He diseñado estos JPanels en Netbeans como clases externas y quiero poder llamarlos en un método actionPerformed(). JOptionPanes u otros cuadros de diálogo emergentes no son una opción porque alejan el foco del juego. También vi a alguien sugerir un CardLayout en una pregunta similar. Esto no es lo que quiero porque no estoy tratando de cambiar los paneles. Deben desaparecer cuando el programa se lo indique. ¿Cómo haría esto, por ejemplo, al vincularlo a una Acción de JButton?Cómo mostrar/ocultar JPanels en un JFrame?

+0

+1 a su pregunta ... Los juegos a menudo tienen su propia interfaz de usuario personalizada. No hay muchos juegos por ahí que utilicen Java look'n'feel, al menos no los de buen aspecto. ¿Qué tipo de juego estás haciendo? ¿A qué plataforma (s) te diriges? (obviamente no es el iPhone/iPad) * [Descargo de responsabilidad: solía trabajar profesionalmente en la industria de los videojuegos] *. – SyntaxT3rr0r

+0

Gracias! Este es un juego muy simple, es un RPG en primera persona que usa imágenes estáticas como escenas. También espero descubrir cómo cargar múltiples imágenes en la pantalla. Quizás esta pregunta también responda. – aharlow

Respuesta

21

Puede ocultar un JPanel llamando al setVisible(false). Por ejemplo:

public static void main(String args[]){ 
    JFrame f = new JFrame(); 
    f.setLayout(new BorderLayout()); 
    final JPanel p = new JPanel(); 
    p.add(new JLabel("A Panel")); 
    f.add(p, BorderLayout.CENTER); 

    //create a button which will hide the panel when clicked. 
    JButton b = new JButton("HIDE"); 
    b.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e){ 
       p.setVisible(false); 
     } 
    }); 

    f.add(b,BorderLayout.SOUTH); 
    f.pack(); 
    f.setVisible(true); 
} 
+0

¡Creo que fue así de simple! – aharlow

+0

Solo hay un problema, cambie p.setVisible (falso); por f.setVisible (falso); para ocultar el Panel – bestyasser

1
/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 

/* 
* Style1.java 
* 
* Created on May 5, 2011, 6:31:16 AM 
*/ 
package Test; 

import javax.swing.JButton; 
import javax.swing.JFileChooser; 
import javax.swing.JOptionPane; 

/** 
* 
* @author Sameera 
*/ 
public class Style2 extends javax.swing.JFrame { 

    /** Creates new form Style1 */ 
    public Style2() { 
     initComponents(); 
    } 

    /** This method is called from within the constructor to 
    * initialize the form. 
    * WARNING: Do NOT modify this code. The content of this method is 
    * always regenerated by the Form Editor. 
    */ 
    @SuppressWarnings("unchecked") 
    // <editor-fold defaultstate="collapsed" desc="Generated Code"> 
    private void initComponents() { 

     jPanel1 = new javax.swing.JPanel(); 
     cmd_SH = new javax.swing.JButton(); 
     pnl_2 = new javax.swing.JPanel(); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

     jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); 

     cmd_SH.setText("Hide"); 
     cmd_SH.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       cmd_SHActionPerformed(evt); 
      } 
     }); 

     javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); 
     jPanel1.setLayout(jPanel1Layout); 
     jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() 
       .addContainerGap(558, Short.MAX_VALUE) 
       .addComponent(cmd_SH) 
       .addContainerGap()) 
     ); 
     jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() 
       .addContainerGap(236, Short.MAX_VALUE) 
       .addComponent(cmd_SH) 
       .addContainerGap()) 
     ); 

     pnl_2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); 

     javax.swing.GroupLayout pnl_2Layout = new javax.swing.GroupLayout(pnl_2); 
     pnl_2.setLayout(pnl_2Layout); 
     pnl_2Layout.setHorizontalGroup(
      pnl_2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGap(0, 621, Short.MAX_VALUE) 
     ); 
     pnl_2Layout.setVerticalGroup(
      pnl_2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGap(0, 270, Short.MAX_VALUE) 
     ); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(layout.createSequentialGroup() 
       .addContainerGap() 
       .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
        .addComponent(pnl_2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) 
       .addContainerGap()) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(layout.createSequentialGroup() 
       .addContainerGap() 
       .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
       .addComponent(pnl_2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addContainerGap(17, Short.MAX_VALUE)) 
     ); 

     pack(); 
    }// </editor-fold> 

    private void cmd_SHActionPerformed(java.awt.event.ActionEvent evt) {          


     System.out.println(evt.getActionCommand()); 
     if (evt.getActionCommand().equals("Hide")) { 
      pnl_2.setVisible(false); 
      cmd_SH.setText("Show"); 
      this.setSize(643, 294); 
      this.pack(); 


     } 
     if (evt.getActionCommand().equals("Show")) { 
      pnl_2.setVisible(true); 
      cmd_SH.setText("Hide"); 
      this.setSize(643, 583); 
      this.pack();  
     } 
    }          

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String args[]) { 
     java.awt.EventQueue.invokeLater(new Runnable() { 

      public void run() { 
       new Style1().setVisible(true); 
      } 
     }); 
    } 

    // Variables declaration - do not modify 
    private javax.swing.JButton cmd_SH; 
    private javax.swing.JPanel jPanel1; 
    private javax.swing.JPanel pnl_2; 
    // End of variables declaration 
} 
+4

No solo proporcione respuestas de solo código. –

0

llamada parent.remove(panel), donde parent es el contenedor que desea que el marco y panel es el panel que desee agregar.

Cuestiones relacionadas