简体   繁体   English

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

[英]How To Add A JPanel Form To JFrame Form Using ActionListener?

This is my first time on stack overflow, and I really have found it helpful for pretty much every issue I have had. 这是我第一次遇到堆栈溢出问题,我确实发现它对我遇到的几乎所有问题都很有帮助。 I finally just needed to get an account since I finally have a question that I cannot find an answer to. 最后我只需要得到一个帐户,因为我终于有我无法找到问题的答案。 I am using Netbeans 7.3 now, and I am using the GUI editor for the first time. 我使用NetBeans 7.3,现在,我使用的第一次的GUI编辑器。 I needed the precise positioning so I couldn't do the GUI's manually. 我需要精确的定位,因此无法手动进行GUI。 My issue is that I have a JFrame form with a JPanel form added to it (I just drug it onto the window and it seemed to work fine) and i want to add a second JPanel as well, but whether i do it or not is based upon a jcombobox selection in the first JPanel. 我的问题是我有一个JFrame表单,其中添加了一个JPanel表单(我只是将其放到窗口中,而且看起来工作正常),我也想添加第二个JPanel,但是我是否这样做是基于第一个JPanel中的jcombobox选择。 I started by adding an action listener to the jcombobox in the first JFrame. 我开始在第一JFrame中添加动作监听JComboBox时。 My plan was to add the second JPanel from within that action performed method tied to that jcombobox, but i don't know how to add it. 我的计划是从绑到JComboBox将执行的操作方法中添加第二个JPanel的,但我不知道如何添加它。 I apologize if i am not making much since. 如果那以后我没赚多少钱,我深表歉意。 I am a beginner. 我是初学者。 Also from reading my code you might find out what I'm trying to do, but to be honest i can't even get there until i figure out the gui. 另外从阅读我的代码,你可能会发现什么,我试图做的,但说实话,我甚至不能在那里,直到我想出的GUI。 Perhaps some code might help: 也许一些代码可能会有所帮助:

This is the JFrame Code: 这是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                   
}

This is the JPanel 1 code: 这是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                   
}

And this is the Second JPanel code (the one i want to add to the JFrame based upon the combo box in JPanel 1). 这是第二个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                   
}

Thank you very much for the help. 非常感谢你的帮助。

Hej, i made a very simple example for you. Hej,我为您举了一个非常简单的例子。 I created the "GUI" programmtically. 我以编程方式创建了“ GUI”。

On the JFrame i placed one JPanel , called firstPanel , on this Panel you'll find a JComboBox and if you choose the option add new JPanel , another JPanel will be added to the JFrame , if you choose hide JPanel , the secondPanel will be removed, only for demonstration of the actionPerformed() method. 我在JFrame放置了一个名为firstPanel JPanel ,在此面板上会找到一个JComboBox ,如果选择add new JPanel选项,则另一个JPanel将添加到JFrame ;如果选择hide JPanel ,则将删除secondPanel ,仅用于演示actionPerformed()方法。

MainFrame class MainFrame类

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

Start the App 启动应用

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

}

I think this will be the part of your interest: 我认为这将是您感兴趣的部分:

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

Patrick. 帕特里克

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM