使用其中一个面板内的按钮在面板之间切换

Switch between panels using a button inside one of them

我有一个接收 jpanel 的 JFrame,当程序启动时,它接收一个添加成功的 jpanel,但是在这个面板中,当我尝试使用里面的按钮切换到另一个面板时,没有任何反应。

这是我的代码:

这是主面板

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

这是另外两个面板

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                   


}

打包 Vista;

/** *


您的程序有效

即切换面板。

当您尝试使用 scene0 class 中的按钮(您指的是 JLabelMouseListener)切换到另一个面板时没有任何反应的原因是,在您的 jLabel1MouseClicked 方法中,您实际上是在创建 MainPanel.

的新实例

因此,您不是在已经可见的 MainPanel 中更改面板,而是在新的 MainPanel 框架中更改面板。

解决方案:

虽然还有其他解决方案,但我可以长期考虑的解决方案 运行 是,您应该在您的 Main class Vista 包。在那个 class 中,您应该创建所有面板的实例。无论何时,你 运行 你的程序,运行 这个 class 而不是 运行ning MainPanel class .

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

现在,每当您尝试访问 MainPanelscene0scene1 时,请使用 Main.mainPanelMain.scene0Main.scene1.

以这种方式修改您的 jLabel1MouseClicked 方法:

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

您还应该以这种方式修改 sol()loadscene1() 方法:

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

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

注意:代码未经过测试,但我相信它会起作用。