使用其中一个面板内部的按钮切换面板

huangapple go评论78阅读模式
英文:

Switch between panels using a button inside one of them

问题

这是我的代码:

这是主面板

package Vista;

import javax.swing.JPanel;

/**
 *
 * 作者:harri
 */
public class MainPanel extends javax.swing.JFrame {

    /**
     * 创建一个新的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();//清空主面板以防有其他JFrame嵌套
        panelframes.add(p);
        panelframes.revalidate();//重新验证以防出现错误
        panelframes.repaint();//负责显示另一个面板的内容
    }
    public static void main(String args[]) {
        /* 设置Nimbus外观 */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* 如果Nimbus(在Java SE 6中引入)不可用,则使用默认外观。
         * 有关详细信息,请参见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>

        /* 创建并显示窗体 */
        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;

/**
 *
 * 作者:harri
 */
public class scene0 extends javax.swing.JPanel {

    /**
     * 创建一个新的scene0
     */
    public scene0() {
        
        initComponents();
        
    }

    /**
     * 此方法在构造函数内部调用以初始化表单。
     * 警告:不要修改此代码。该方法的内容始终由表单编辑器生成。
     */
    @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;

/**
 *
 * 作者:harri
 */
public class scene1 extends javax.swing.JPanel {

    /**
     * 创建一个新的scene1
     */
    public scene1() {
        initComponents();
    }

    /**
     * 此方法在构造函数内部调用以初始化表单。
     * 警告:不要修改此代码。该方法的内容始终由表单编辑器生成。
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();

        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("mamalon");
        add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 80, 190, 120));
    }// </editor-fold>                        


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

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(&quot;unchecked&quot;)
// &lt;editor-fold defaultstate=&quot;collapsed&quot; desc=&quot;Generated Code&quot;&gt;                          
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();
}// &lt;/editor-fold&gt;                        
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&#225;
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//&lt;editor-fold defaultstate=&quot;collapsed&quot; desc=&quot; Look and feel setting code (optional) &quot;&gt;
/* 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 (&quot;Nimbus&quot;.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);
}
//&lt;/editor-fold&gt;
/* 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(&quot;unchecked&quot;)
// &lt;editor-fold defaultstate=&quot;collapsed&quot; desc=&quot;Generated Code&quot;&gt;                          
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setLayout(new java.awt.BorderLayout());
jLabel1.setText(&quot;jLabel1&quot;);
jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel1MouseClicked(evt);
}
});
add(jLabel1, java.awt.BorderLayout.CENTER);
}// &lt;/editor-fold&gt;                        
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;

/**
*

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

    /**

    • Creates new form scene1
      */
      public scene1() {
      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 org.netbeans.lib.awtextra.AbsoluteLayout());

      jLabel1.setText("mamalon");
      add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 80, 190, 120));
      }// </editor-fold>

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

答案1

得分: 1

Your Program Works

也就是说,它会切换面板。

之所以在尝试使用按钮(通过按钮,您是指带有MouseListenerJLabel)在scene0类内部切换到另一个面板时没有任何反应,是因为在您的jLabel1MouseClicked方法中,实际上您正在创建MainPanel的新实例。

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

解决方案:

虽然还有其他解决方案,但我为长远考虑能够想到的解决方案是,在您的Vista包中创建一个Main类。在该类中,您应该创建所有面板的实例。无论何时运行程序,都应该运行此类,而不是运行MainPanel

Main类的示例代码:

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

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

英文:

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.

huangapple
  • 本文由 发表于 2020年7月29日 04:28:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63142279.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定