问题描述
- 自己参照书本写了一个Java Swing中的容器类入门程序设计,但是运行结果不对,求大神帮帮忙!
- /*题目是这样的:创建一个窗体在其中摆放两个内容面板对两个面板进行边框个性化设置。
初始状态为第二个面板不可见,当单击第一个面板中的“打开”按钮时,第二个面板即可见;
当单击第一个面板中的“关闭”按钮时,第二个面板消失。以下是我结合书本写的代码,不知道为什么运行不了???*/
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EtchedBorder;
import java.awt.event.*;
public class PanelFrm extends javax.swing.JFrame {
public PanelFrm() { //构造函数
initialize();
// initComponents();
}
public static void main(String args[]) {// 程序入口
PanelFrm frm=new PanelFrm();
frm.setVisible(true);}
private void initialize(){// 初始化成员变量
setSize(300200);
setTitle(""Exerice"");
jButton1=getBtnAppear();
jButton2=getBtnDisappear();
jPanel1=getPnlPanel1();
jPanel2=getPnlPanel2();
jPanel3=getJContentPane();
add(jPanel3);}private JPanel getPnlPanel1(){ // 初始化容器1 if(jPanel1==null){ GridBagConstraints gridBagConstraints1=new GridBagConstraints(); gridBagConstraints1.gridx=2; gridBagConstraints1.gridy=1; GridBagConstraints gridBagConstraints=new GridBagConstraints(); gridBagConstraints.gridx=0; gridBagConstraints.gridy=1; jPanel1=new JPanel(); jPanel1.setVisible(true); jPanel1.setLayout(new GridBagLayout()); jPanel1.setBounds(new Rectangle(411821747)); jPanel1.setBorder(BorderFactory.createLineBorder(Color.red1)); jPanel1.add(getBtnAppear()gridBagConstraints); //往容器1添加两个按钮 jPanel1.add(getBtnDisappear()gridBagConstraints); } return jPanel1;}private JPanel getPnlPanel2(){ //初始化容器2 if(jPanel2==null){ jPanel2=new JPanel(); jPanel2.setLayout(new GridBagLayout()); jPanel2.setBounds(new Rectangle(418621752)); jPanel2.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED)); jPanel2.setVisible(false); } return jPanel2;}private JButton getBtnAppear(){ //按钮1 if(jButton1==null){ jButton1=new JButton(); jButton1.setText(""打开""); jButton1.setVisible(true); jButton1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ jPanel2.setVisible(true); jButton1.setVisible(false); jButton2.setVisible(true); } }); } return jButton1;} private JButton getBtnDisappear(){ //按钮2 if(jButton2==null){ jButton2=new JButton(); jButton2.setText(""关闭""); jButton1.setVisible(false); jButton1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ jPanel2.setVisible(false); jButton1.setVisible(true); jButton2.setVisible(false); } }); } return jButton2;}private JPanel getJContentPane(){ //容器3 if(jPanel3==null){ jPanel3=new JPanel(); jPanel3.setVisible(true); jPanel3.setLayout(null); jPanel3.add(getPnlPanel1()null); jPanel3.add(getPnlPanel2()null); } return jPanel3;}//类成员变量private JPanel jPanel1=null;private JPanel jPanel2=null;private JButton jButton1=null;private JButton jButton2=null;private JPanel jPanel3=null;// Variables declaration - do not modify private javax.swing.JProgressBar jProgressBar1;// End of variables declaration
}
时间: 2025-01-14 17:15:37