我有 2 个 JPanel 和 1 个 JFrame,当我单击一个按钮时,我试图在面板之间切换。我不想使用 CardLayout,因为我想要不同的面板,而使用 CardLayouts,我只能为两者使用相同的按钮. 我的代码是:
package javaapplication2;
import javax.swing.JPanel;
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
public NewJFrame() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(121, 183, 60));
setSize(200, 300);
setResizable(false);
/**panel1**/
jButton1 = new javax.swing.JButton();
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jButton1.setText("jButton1");
panel1.setBackground(new java.awt.Color(121, 183, 60));
panel1.setMaximumSize(new java.awt.Dimension(100, 200));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(panel1);
panel1.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(164, 164, 164)
.addComponent(jButton1)
.addContainerGap(172, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(115, 115, 115)
.addComponent(jButton1)
.addContainerGap(158, Short.MAX_VALUE))
);
/**panel2**/
jButton2 = new javax.swing.JButton();
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton2MouseClicked(evt);
}
});
jButton2.setText("jButton2");
panel2.setBackground(new java.awt.Color(101, 13, 61));
panel2.setMaximumSize(new java.awt.Dimension(100, 200));
javax.swing.GroupLayout layout2 = new javax.swing.GroupLayout(panel2);
panel2.setLayout(layout2);
layout2.setHorizontalGroup(
layout2.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout2.createSequentialGroup()
.addGap(164, 164, 164)
.addComponent(jButton2)
.addContainerGap(172, Short.MAX_VALUE))
);
layout2.setVerticalGroup(
layout2.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout2.createSequentialGroup()
.addGap(115, 115, 115)
.addComponent(jButton2)
.addContainerGap(158, Short.MAX_VALUE))
);
add(panel2);
pack();
}
public void changePanel(){
getContentPane().removeAll();
add(panel1);
invalidate();
repaint();
}
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
changePanel();
}
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
changePanel();
}
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
}