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

时间:2014-03-30 17:32:11

标签: java swing user-interface netbeans jcombobox

这是我第一次在堆栈溢出时,我发现它几乎对我遇到的每一个问题都有帮助。我终于需要得到一个帐户,因为我终于有一个我无法找到答案的问题。我现在正在使用Netbeans 7.3,我第一次使用GUI编辑器。我需要精确的定位,所以我无法手动完成GUI。我的问题是我有一个添加了JPanel表单的JFrame表单(我只是把它放到窗口上它似乎工作正常)我想添加第二个JPanel,但是我是否这样做是基于第一个JPanel中的jcombobox选择。我开始在第一个JFrame中向jcombobox添加一个动作监听器。我的计划是从与该jcombobox绑定的动作执行方法中添加第二个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                   
}

这是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                   
}

这是第二个JPanel代码(我想根据JPanel 1中的组合框添加到JFrame中)。

/*
 * 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                   
}

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

Hej,我为你做了一个非常简单的例子。我创建了&#34; GUI&#34; programmtically。

JFrame我放置一个名为JPanel的{​​{1}},在此面板上,您会找到firstPanel,如果您选择{{1} }},另一个JComboBox将添加到add new JPanel,如果您选择JPanel,则第二个面板将被删除,仅用于演示JFrame方法。

MainFrame类

hide JPanel

启动应用

actionPerformed()

我认为这将是您感兴趣的一部分:

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

帕特里克。