Search code examples
javaswingwindowbuilderjcheckbox

How to automatically remove an item in jcombobox when I already select it?


This is the submit button code:

JComboBox cb1 = new JComboBox();
    Object[] row = new Object [4];
    JButton btnSubmit = new JButton("SUBMIT");
    btnSubmit.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
    btnSubmit.setBounds(35, 153, 84, 23);
    panel_1.add(btnSubmit);
    btnSubmit.addActionListener(new ActionListener() {
        
        public void actionPerformed(ActionEvent e) {
            row[0] = txtfieldname.getText();
            row[1] = txtfieldemail.getText();
            row[2] = txtfieldphone.getText();
            row[3] = cb1.getSelectedItem();
            model.addRow(row);
        }
            
        
    });

This is the table code:

table_5 = new JTable();
    scrollPane.setViewportView(table_5);
    model = new DefaultTableModel();
    Object[] column = {"Name","Employeed ID", "Phone No.", "Schedule"};
    model.setColumnIdentifiers(column);
    table_5.setModel(model);

This is the data of jcombobox:

cb1.setBounds(114, 113, 94, 22);
    panel_1.add(cb1);
    cb1.addItem("6:00-8:00 AM");
    cb1.addItem("8:00-10:00 AM");
    cb1.addItem("10:00-11:00 AM");

My concern is if i select the first option in the jcheckbox I want to removed it completely so It will not choose again.


Solution

  • After you clarified that you actually meant JComboBox instead of JCheckBox this clearly makes more sense. I quickly put together a minimal reproducible example, which contains a JComboBox including your timeframes and a submit button. On the click of the submit button the currently selected timeframe will be removed from the combobox.

    public static void main(String args[]) {
        SwingUtilities.invokeLater(() -> {
            buildGui();
        });
    }
    
    private static void buildGui() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel label = new JLabel("Select your timeframe: ");
        frame.add(label, BorderLayout.WEST);
        JComboBox<String> comboBox = new JComboBox<String>();
        comboBox.addItem("6:00-8:00 AM");
        comboBox.addItem("8:00-10:00 AM");
        comboBox.addItem("10:00-11:00 AM");
        frame.add(comboBox);
        JButton submitButton = new JButton("Submit");
        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // add row to your model
                // then remove the selected timestamp from your box
                comboBox.removeItemAt(comboBox.getSelectedIndex());
            }
        });
        frame.add(submitButton, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }