Java 如何使用ActionListener将JPanel表单添加到JFrame表单?

Java 如何使用ActionListener将JPanel表单添加到JFrame表单?,java,swing,user-interface,netbeans,jcombobox,Java,Swing,User Interface,Netbeans,Jcombobox,这是我第一次研究堆栈溢出,我真的发现它对我遇到的几乎所有问题都有帮助。我终于需要一个帐户,因为我终于有一个问题,我找不到答案。我现在使用的是Netbeans 7.3,这是我第一次使用GUI编辑器。我需要精确的定位,因此无法手动执行GUI。我的问题是我有一个JFrame表单,其中添加了一个JPanel表单(我只是把它放到窗口上,它似乎工作得很好),我还想添加第二个JPanel,但我是否这样做取决于第一个JPanel中的jcombobox选择。我首先在第一个JFrame中向jcombobox添加了一

这是我第一次研究堆栈溢出,我真的发现它对我遇到的几乎所有问题都有帮助。我终于需要一个帐户,因为我终于有一个问题,我找不到答案。我现在使用的是Netbeans 7.3,这是我第一次使用GUI编辑器。我需要精确的定位,因此无法手动执行GUI。我的问题是我有一个JFrame表单,其中添加了一个JPanel表单(我只是把它放到窗口上,它似乎工作得很好),我还想添加第二个JPanel,但我是否这样做取决于第一个JPanel中的jcombobox选择。我首先在第一个JFrame中向jcombobox添加了一个动作侦听器。我的计划是在与jcombobox关联的action performed方法中添加第二个JPanel,但我不知道如何添加它。如果我从那以后没有挣多少钱,我道歉。我是初学者。另外,通过阅读我的代码,您可能会发现我正在尝试做什么,但老实说,在我弄明白gui之前,我甚至无法做到这一点。也许一些代码可能会有所帮助:

这是JFrame代码:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package geometry.program;

import javax.swing.JPanel;

/**
 *
 * @author maxwellparker
 */
public class Main extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    public Main() {
        super("Geometry Sucks");
        initComponents();
        this.setLocationRelativeTo(null);
    }

    public void addPanel(JPanel j){
        //i was going to call this method from the first jpanel on this JFrame already to add the second one.
    }

    /**
     * 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() {

        rP1 = new geometry.program.RP();
        control1 = new geometry.program.Control();
        rP2 = new geometry.program.RP();
        rP3 = new geometry.program.RP();
        control2 = new geometry.program.Control();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(control2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(92, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(control2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(189, Short.MAX_VALUE))
        );

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

    /**
     * @param args the command line arguments
     */
    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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.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 Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private geometry.program.Control control1;
    private geometry.program.Control control2;
    private geometry.program.RP rP1;
    private geometry.program.RP rP2;
    private geometry.program.RP rP3;
    // End of variables declaration                   
}
/*
*要更改此模板,请选择工具|模板
*然后在编辑器中打开模板。
*/
包装几何程序;
导入javax.swing.JPanel;
/**
*
*@作者麦克斯韦·帕克
*/
公共类Main扩展了javax.swing.JFrame{
/**
*创建新窗体主窗体
*/
公用干管(){
超级(“几何糟糕”);
初始化组件();
此.setLocationRelativeTo(空);
}
公共无效添加面板(JPanel j){
//我本来打算在这个JFrame上从第一个jpanel调用这个方法来添加第二个。
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//                           
私有组件(){
rP1=新几何体.program.RP();
control1=新几何体.program.Control();
rP2=新几何体.program.RP();
rP3=新几何体.program.RP();
control2=新几何体.program.Control();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
org.jdesktop.layout.GroupLayout=new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(control2,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(92,简称最大值))
);
layout.setVerticalGroup(
createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(control2,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(189,简称最大值))
);
包装();
}//                         
/**
*@param指定命令行参数
*/
公共静态void main(字符串参数[]){
/*设置Nimbus的外观和感觉*/
//
/*如果Nimbus(在JavaSE6中引入)不可用,请使用默认的外观。
*详情请参阅http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
*/
试一试{
for(javax.swing.UIManager.LookAndFeelInfo:javax.swing.UIManager.getInstalledLookAndFeels()){
if(“Nimbus”.equals(info.getName())){
setLookAndFeel(info.getClassName());
打破
}
}
}捕获(ClassNotFoundException ex){
getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(实例化异常){
getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}捕获(非法访问例外){
getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(javax.swing.UnsupportedLookAndFeelException ex){
getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}
//
/*创建并显示表单*/
invokeLater(new Runnable()){
公开募捐{
new Main().setVisible(true);
}
});
}
//变量声明-不修改
专用几何.程序.控制1;
专用几何.程序.控制2;
private geometry.program.RP rP1;
private geometry.program.RP rP2;
private geometry.program.RP rP3;
//变量结束声明
}
这是JPanel 1代码:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package geometry.program;

/**
 *
 * @author maxwellparker
 */
public class Control extends javax.swing.JPanel {

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

        Mode = new javax.swing.JLabel();
        ModeComboBox = new javax.swing.JComboBox();
        Var = new javax.swing.JLabel();
        VarField = new javax.swing.JTextField();
        Val = new javax.swing.JLabel();
        ValField = new javax.swing.JTextField();
        CustomVar = new javax.swing.JLabel();

        Mode.setText("Mode:");

        ModeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Regular Polygons", "Second", "Third", "Fourth" }));
        ModeComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ModeComboBoxActionPerformed(evt);
            }
        });

        Var.setText("Variable:");

        Val.setText("Value:");

        CustomVar.setText("Custom Variable (Optional):");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(CustomVar)
                    .add(layout.createSequentialGroup()
                        .add(Var)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(VarField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(Val)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(ValField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 59, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(Mode)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(ModeComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(Mode)
                    .add(ModeComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(CustomVar)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(Var)
                    .add(Val)
                    .add(VarField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(ValField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>                        

    private void ModeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {                                             
        if(ModeComboBox.getSelectedIndex()==0){
            //run option 1
            System.out.println("Add corresponding option Panel To JFrame.");
        }else if(ModeComboBox.getSelectedIndex()==1){
            System.out.println("Add corresponding option Panel To JFrame.");
        }else if(ModeComboBox.getSelectedIndex()==2){
            System.out.println("Add corresponding option Panel To JFrame.");
        }else if(ModeComboBox.getSelectedIndex()==3){
            System.out.println("Add corresponding option Panel To JFrame.");
        }
    }                                            

    // Variables declaration - do not modify                     
    private javax.swing.JLabel CustomVar;
    private javax.swing.JLabel Mode;
    private javax.swing.JComboBox ModeComboBox;
    private javax.swing.JLabel Val;
    private javax.swing.JTextField ValField;
    private javax.swing.JLabel Var;
    private javax.swing.JTextField VarField;
    // End of variables declaration                   
}
/*
*要更改此模板,请选择工具|模板
*然后在编辑器中打开模板。
*/
包装几何程序;
/**
*
*@作者麦克斯韦·帕克
*/
公共类控件扩展了javax.swing.JPanel{
/**
*创建新的表单控件
*/
公共控制(){
初始化组件();
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package geometry.program;

/**
 *
 * @author maxwellparker
 */
public class Control extends javax.swing.JPanel {

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

        Mode = new javax.swing.JLabel();
        ModeComboBox = new javax.swing.JComboBox();
        Var = new javax.swing.JLabel();
        VarField = new javax.swing.JTextField();
        Val = new javax.swing.JLabel();
        ValField = new javax.swing.JTextField();
        CustomVar = new javax.swing.JLabel();

        Mode.setText("Mode:");

        ModeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Regular Polygons", "Second", "Third", "Fourth" }));
        ModeComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ModeComboBoxActionPerformed(evt);
            }
        });

        Var.setText("Variable:");

        Val.setText("Value:");

        CustomVar.setText("Custom Variable (Optional):");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(CustomVar)
                    .add(layout.createSequentialGroup()
                        .add(Var)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(VarField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(Val)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(ValField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 59, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(Mode)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(ModeComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(Mode)
                    .add(ModeComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(CustomVar)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(Var)
                    .add(Val)
                    .add(VarField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(ValField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>                        

    private void ModeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {                                             
        if(ModeComboBox.getSelectedIndex()==0){
            //run option 1
            System.out.println("Add corresponding option Panel To JFrame.");
        }else if(ModeComboBox.getSelectedIndex()==1){
            System.out.println("Add corresponding option Panel To JFrame.");
        }else if(ModeComboBox.getSelectedIndex()==2){
            System.out.println("Add corresponding option Panel To JFrame.");
        }else if(ModeComboBox.getSelectedIndex()==3){
            System.out.println("Add corresponding option Panel To JFrame.");
        }
    }                                            

    // Variables declaration - do not modify                     
    private javax.swing.JLabel CustomVar;
    private javax.swing.JLabel Mode;
    private javax.swing.JComboBox ModeComboBox;
    private javax.swing.JLabel Val;
    private javax.swing.JTextField ValField;
    private javax.swing.JLabel Var;
    private javax.swing.JTextField VarField;
    // End of variables declaration                   
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MainFrame extends JFrame {

    JPanel firstPanel;
    JComboBox<String> comboBox;
    String[] items = {"choose an option", "hide JPanel", "add new JPanel"};


    public MainFrame() {

    }

    public void createAndShowGui() {

        initComponents();
        this.setTitle("Add new JPanel with ComboBox");
        this.setSize(new Dimension(1024, 768));
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.getContentPane().add(firstPanel, BorderLayout.NORTH);
        this.setVisible(true);
    }

    private void initComponents() {
        firstPanel = new JPanel(new GridLayout(3, 1));
        firstPanel.add(new JLabel("First Panel"));
        comboBox = new JComboBox<>(items);
        JPanel panel = new JPanel();
        comboBox.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(comboBox.getSelectedItem().toString().equalsIgnoreCase("add new JPanel")) {

                    panel.setBackground(Color.ORANGE);
                    panel.setSize(new Dimension(500, 300));

                    getContentPane().add(panel, BorderLayout.SOUTH);
                }

                if(comboBox.getSelectedItem().toString().equalsIgnoreCase("hide JPanel")) {
                    getContentPane().remove(panel);
                }
            }
        });

        firstPanel.add(comboBox);
    }
}
import de.professional_webworkx.blog.swingjpanel.frame.MainFrame;
import java.awt.EventQueue;

public class SwingJPanel {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                MainFrame mainFrame = new MainFrame();
                mainFrame.createAndShowGui();
            }
        });
    }

}
comboBox.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(comboBox.getSelectedItem().toString().equalsIgnoreCase("add new JPanel")) {

                    panel.setBackground(Color.ORANGE);
                    panel.setSize(new Dimension(500, 300));

                    getContentPane().add(panel, BorderLayout.SOUTH);
                }

                if(comboBox.getSelectedItem().toString().equalsIgnoreCase("hide JPanel")) {
                    getContentPane().remove(panel);
                }
            }
        });