简体   繁体   中英

add dynamic checkbox in java windowbuilder

I want to add a dynamic checkbox after selecting an item in combo box. I am working on eclipse and design my frame on window builder.

    final JComboBox<String> comboBox = new JComboBox<String>();
    comboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String typeName = comboBox.getSelectedItem().toString();
            for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
                JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
                c.setVisible(true);
                coursePanel.add(c);

                frame.repaint();
                frame.validate();

                System.out.println(c.getText());
            }
        }
    });
    comboBox.setBounds(208, 221, 91, 20);
    frame.getContentPane().add(comboBox);

edit: thats my full code.

public class registerForm { 
private JFrame frame;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtPassword;
private JTextField txtEmail;

List<Integer> coursesId; // ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ן¿½

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                registerForm window = new registerForm();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public registerForm() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 442);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JLabel lblNewLabel = new JLabel("\u05D4\u05E8\u05E9\u05DE\u05D4");
    lblNewLabel.setBounds(165, 11, 91, 29);
    lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 24));
    frame.getContentPane().add(lblNewLabel);

    JLabel label = new JLabel("\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9:");
    label.setBounds(363, 55, 61, 14);
    label.setFont(new Font("Tahoma", Font.PLAIN, 14));
    frame.getContentPane().add(label);

    txtFirstName = new JTextField();
    txtFirstName.setBounds(75, 51, 221, 20);
    frame.getContentPane().add(txtFirstName);
    txtFirstName.setColumns(10);

    JLabel label_1 = new JLabel("\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4:");
    label_1.setBounds(344, 80, 80, 14);
    label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
    frame.getContentPane().add(label_1);

    txtLastName = new JTextField();
    txtLastName.setBounds(75, 82, 221, 20);
    txtLastName.setColumns(10);
    frame.getContentPane().add(txtLastName);

    txtPassword = new JTextField();
    txtPassword.setBounds(75, 140, 221, 20);
    txtPassword.setColumns(10);
    frame.getContentPane().add(txtPassword);

    JLabel label_2 = new JLabel("\u05DE\u05D9\u05D9\u05DC:");
    label_2.setBounds(392, 110, 32, 14);
    label_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
    frame.getContentPane().add(label_2);

    txtEmail = new JTextField();
    txtEmail.setBounds(75, 109, 221, 20);
    txtEmail.setColumns(10);
    frame.getContentPane().add(txtEmail);

    JLabel label_3 = new JLabel("\u05E1\u05D9\u05E1\u05DE\u05D0:");
    label_3.setBounds(373, 141, 51, 14);
    label_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
    frame.getContentPane().add(label_3);

    final JDateChooser dateChooser = new JDateChooser();
    dateChooser.setBounds(75, 171, 221, 39);
    frame.getContentPane().add(dateChooser);

    JLabel label_4 = new JLabel("\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4:");
    label_4.setBounds(344, 167, 90, 14);
    label_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
    frame.getContentPane().add(label_4);

    JButton btnSend = new JButton("\u05E9\u05DC\u05D7");
    btnSend.setBounds(258, 334, 61, 58);
    btnSend.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            // date
            Date date = new Date(dateChooser.getDate().getTime());
        }
    });
    frame.getContentPane().add(btnSend);

    JButton button = new JButton("\u05E0\u05E7\u05D4");
    button.setBounds(175, 334, 61, 58);
    frame.getContentPane().add(button);

    JLabel label_5 = new JLabel("\u05DE\u05D2\u05DE\u05D4:");
    label_5.setFont(new Font("Tahoma", Font.PLAIN, 14));
    label_5.setBounds(382, 218, 42, 14);
    frame.getContentPane().add(label_5);

    final JPanel coursePanel = new JPanel();
    coursePanel.setBounds(10, 249, 286, 74);
    frame.getContentPane().add(coursePanel);
    coursePanel.setLayout(null);

    final JComboBox<String> comboBox = new JComboBox<String>();
    comboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String typeName = comboBox.getSelectedItem().toString();
            for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
                JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
                int selectedIndex = comboBox.getSelectedIndex();
                boolean isInPanel = c.getParent() == coursePanel;
                if (selectedIndex == 1 && !isInPanel) {
                    coursePanel.add(c);
                    coursePanel.repaint(); //Repaint the proper panel that has this component.
                    coursePanel.revalidate();
                } else if (isInPanel && selectedIndex != 1) {
                    coursePanel.remove(c);
                    coursePanel.repaint(); //Repaint the proper panel that has this component.
                    coursePanel.revalidate();
                }
                coursePanel.repaint();
                coursePanel.validate();

                System.out.println(c.getText());
            }
        }
    });
    comboBox.setBounds(208, 221, 91, 20);
    frame.getContentPane().add(comboBox);
    // fill comboBox
    List<String> lst = SqlQuery.getTypes();
    for (int i = 0; i < lst.size(); i++)
        comboBox.addItem(lst.get(i));

    JLabel label_6 = new JLabel("\u05E9\u05DC\u05D9\u05D8\u05D4 \u05D1\u05E7\u05D5\u05E8\u05E1\u05D9\u05DD");
    label_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
    label_6.setBounds(321, 245, 103, 14);
    frame.getContentPane().add(label_6);



}

}

Hope you understand what I wrote. I want to show a list of coursesName after click on the comboBox. Why the frame does'nt show the checkbox? Thank you.

First and foremost. The comboBox.setBounds() is a very bad practice. Take some time and see Layout Managers . Also add 'swing' tag in your post since you are referring to Swing library.

The frame doesn't show the component because you repaint the wrong one. You add the checkbox in coursePanel, which means you have to repaint() & revalidate() coursePanel. So coursePanel.repaint() instead of frame.repaint() will help you.

Also checkBox.setVisible(true) is not required, since checkBox is visible by default.

Finally i have added the way of how i would do it.

package test;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {

    private JFrame frame;
    private JCheckBox checkBox;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Test window = new Test();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Test() {
        frame = new JFrame();
        frame.setPreferredSize(new Dimension(300, 300));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(createPanel());
        frame.pack();
    }

    private JPanel createPanel() {
        JPanel p = new JPanel(new FlowLayout());
        checkBox = new JCheckBox("I am a checkbox"); //Create the checkbox
        JComboBox<String> combo = new JComboBox<>();
        combo.addItem("Hello");
        combo.addItem("Stack");
        combo.addItem("OverFlow");
        combo.addActionListener(e -> {
            //Its better to handle indices when there is not dynmic data to your combobox
            int selectedIndex = combo.getSelectedIndex();
            boolean isInPanel = checkBox.getParent() == p;
            if (selectedIndex == 1 && !isInPanel) {
                p.add(checkBox);
                p.repaint(); //Repaint the proper panel that has this component.
                p.revalidate();
            } else if (isInPanel && selectedIndex != 1) {
                p.remove(checkBox);
                p.repaint(); //Repaint the proper panel that has this component.
                p.revalidate();
            }

        });
        p.add(combo);
        return p;
    }
}

The answer to your problem (make the checkbox visible) after comments:

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class registerForm {
    private JFrame frame;
    private JTextField txtFirstName;
    private JTextField txtLastName;
    private JTextField txtPassword;
    private JTextField txtEmail;
    private JCheckBox checkBox;

    List<Integer> coursesId; // ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ן¿½

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    registerForm window = new registerForm();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public registerForm() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 442);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JLabel lblNewLabel = new JLabel("\u05D4\u05E8\u05E9\u05DE\u05D4");
        lblNewLabel.setBounds(165, 11, 91, 29);
        lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 24));
        frame.getContentPane().add(lblNewLabel);

        JLabel label = new JLabel("\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9:");
        label.setBounds(363, 55, 61, 14);
        label.setFont(new Font("Tahoma", Font.PLAIN, 14));
        frame.getContentPane().add(label);

        txtFirstName = new JTextField();
        txtFirstName.setBounds(75, 51, 221, 20);
        frame.getContentPane().add(txtFirstName);
        txtFirstName.setColumns(10);

        JLabel label_1 = new JLabel("\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4:");
        label_1.setBounds(344, 80, 80, 14);
        label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
        frame.getContentPane().add(label_1);

        txtLastName = new JTextField();
        txtLastName.setBounds(75, 82, 221, 20);
        txtLastName.setColumns(10);
        frame.getContentPane().add(txtLastName);

        txtPassword = new JTextField();
        txtPassword.setBounds(75, 140, 221, 20);
        txtPassword.setColumns(10);
        frame.getContentPane().add(txtPassword);

        JLabel label_2 = new JLabel("\u05DE\u05D9\u05D9\u05DC:");
        label_2.setBounds(392, 110, 32, 14);
        label_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
        frame.getContentPane().add(label_2);

        txtEmail = new JTextField();
        txtEmail.setBounds(75, 109, 221, 20);
        txtEmail.setColumns(10);
        frame.getContentPane().add(txtEmail);

        JLabel label_3 = new JLabel("\u05E1\u05D9\u05E1\u05DE\u05D0:");
        label_3.setBounds(373, 141, 51, 14);
        label_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
        frame.getContentPane().add(label_3);


        JLabel label_4 = new JLabel("\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4:");
        label_4.setBounds(344, 167, 90, 14);
        label_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
        frame.getContentPane().add(label_4);


        JButton button = new JButton("\u05E0\u05E7\u05D4");
        button.setBounds(175, 334, 61, 58);
        frame.getContentPane().add(button);

        JLabel label_5 = new JLabel("\u05DE\u05D2\u05DE\u05D4:");
        label_5.setFont(new Font("Tahoma", Font.PLAIN, 14));
        label_5.setBounds(382, 218, 42, 14);
        frame.getContentPane().add(label_5);

        final JPanel coursePanel = new JPanel();
        coursePanel.setBounds(10, 249, 286, 74);
        frame.getContentPane().add(coursePanel);
        coursePanel.setLayout(null);
        List<String> lst = new ArrayList<>();
        lst.add("Hello");
        lst.add("Stack");
        lst.add("Over");
        lst.add("Flow");
        //Prepare the checkBox
        checkBox = new JCheckBox("nothing");
        final JComboBox<String> comboBox = new JComboBox<String>();
        comboBox.addActionListener(new ActionListener() {


            public void actionPerformed(ActionEvent e) {
                String typeName = comboBox.getSelectedItem().toString();
                for (int i = 0; i < lst.size(); i++) {
                    checkBox.setText(typeName);
                    //set the same bounds as comboBox but reduce its X by 80.
                    //Compare checkBoxbounds and combobox bounds
                    //Remind: setBounds is baaaaad practice.
                    checkBox.setBounds(128, 221, 91, 20);
                    //if you want to add it in coursePanel, change all frame.getContentPane() to coursePanel
                    int selectedIndex = comboBox.getSelectedIndex();
                    boolean isInPanel = checkBox.getParent() == frame.getContentPane(); 
                    if (selectedIndex == 1 && !isInPanel) {

                        frame.getContentPane().add(checkBox);
                    } else if (isInPanel && selectedIndex != 1) {
                        frame.getContentPane().remove(checkBox);
                    }
                    frame.getContentPane().repaint();
                    frame.getContentPane().validate();

                    System.out.println(checkBox.getText());
                }
            }
        });
        comboBox.setBounds(208, 221, 91, 20);
        frame.getContentPane().add(comboBox);
        // fill comboBox

        for (int i = 0; i < lst.size(); i++)
            comboBox.addItem(lst.get(i));

        JLabel label_6 = new JLabel("\u05E9\u05DC\u05D9\u05D8\u05D4 \u05D1\u05E7\u05D5\u05E8\u05E1\u05D9\u05DD");
        label_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
        label_6.setBounds(321, 245, 103, 14);
        frame.getContentPane().add(label_6);

    }
}

Another option is to create the checkbox as a field outside of the actionlistener (like i did) and set its bounds with window builder and use setVisible(false). Then on your listener, setVisible(true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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