Harrison 01233
Harrison 01233

Reputation: 15

Switch between panels using a button inside one of them

I have a JFrame that recive the jpanels, when the program start, it recive a jpanel that add succesfuly, but in this panel when i try to switch to another one using a button inside, nothing happens.

This my code:

this is the mainpanel

package Vista;


import javax.swing.JPanel;

/**
 *
 * @author harri
 */
public class MainPanel extends javax.swing.JFrame {

    /**
     * Creates new form MainPanel
     */
    public MainPanel() {
        initComponents();
        sol();
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        panelframes = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        panelframes.setLayout(new java.awt.BorderLayout());

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelframes, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1280, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelframes, javax.swing.GroupLayout.DEFAULT_SIZE, 720, Short.MAX_VALUE)
        );

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

    
    public void mostrarPanel(JPanel p) {
        panelframes.removeAll();//el panel principal se limpia en caso de que tenga otro jframe metido
        panelframes.add(p);
        panelframes.revalidate();//validacion en caso de error
        panelframes.repaint();//se encarga de imprimir ya lo del otro frame, acá
    }
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainPanel().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    public javax.swing.JPanel panelframes;
    // End of variables declaration                   

    
   
    
    
    public void sol() {
       mostrarPanel(new scene0());
       
       
       
    }
    
    public void loadscene1(){
        
        
    mostrarPanel(new scene1());
    
    }
}

this is the other 2 panles

package Vista;

import Vista.MainPanel;
import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;

/**
 *
 * @author harri
 */
public class scene0 extends javax.swing.JPanel {

    /**
     * Creates new form scene0
     */
    public scene0() {
        
        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() {

        jLabel1 = new javax.swing.JLabel();

        setLayout(new java.awt.BorderLayout());

        jLabel1.setText("jLabel1");
        jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel1MouseClicked(evt);
            }
        });
        add(jLabel1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>                        

    private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {                                     
       MainPanel s = new MainPanel();
        scene1 r = new scene1();
        
        s.panelframes.removeAll();
        s.panelframes.revalidate();
        s.panelframes.repaint();
        
        
       s.loadscene1();
           
    }                                    


    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   


}

package Vista;

/** *

Upvotes: 0

Views: 999

Answers (1)

Peter Parker
Peter Parker

Reputation: 46

Your Program Works

That is, it switches panels.

The reason nothing happens when you try to switch to another panel using a button (by button you mean, JLabel with MouseListener) inside the scene0 class is that, in your jLabel1MouseClicked method, you are actually creating a new instance of MainPanel.

So, instead of changing panels in the already visible MainPanel, you are changing panels in a new MainPanel frame.

Solution:

Although there are other solutions, the solution that I could think for the long run is that, you should create a Main class in your Vista package. In that class you should create the instances of all your panels. Whenever, you run your program, run this class instead of running MainPanel class.

Demo-code of the Main class:

public class Main
{
 public static MainPanel mainPanel;
 public static scene0 firstScene  = new scene0();
 public static scene1 secondScene = new scene1();

 public static void main(String[] args)
 {
  java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
     mainPanel = new MainPanel()
   }
  });
 }
}

Now, whenever you are trying to access MainPanel,scene0 or scene1, access it using Main.mainPanel or Main.scene0 or Main.scene1.

Modify your jLabel1MouseClicked method in this manner :

private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {                                     
  Main.mainPanel.loadscene1();         
}  

You should also modify the sol() and loadscene1() method in this manner:

public void sol() {
 mostrarPanel(Main.firstScene);
}

public void loadscene1(){
 mostrarPanel(Main.secondScene);
}

Note: The code is not tested but I am sure it will work.

Upvotes: 1

Related Questions