【问题标题】:How to automatically remove an item in jcombobox when I already select it?当我已经选择它时如何自动删除jcombobox中的项目?
【发布时间】:2020-09-29 10:40:17
【问题描述】:

这是提交按钮代码:

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

这是表格代码:

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

这是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");

我担心的是,如果我选择 jcheckbox 中的第一个选项,我想完全删除它,这样它就不会再选择了。

【问题讨论】:

  • 我不认为JCheckBox 是这样工作的,我也无法在JCheckBox Javadoc 中找到JCheckBox#addItem()...这是有效的代码吗?
  • JComboBox 对您来说可能很容易,您可以在其中简单地从选择中添加和删除您的时间跨度。见JComboBox Tutorial
  • @maloomeister 抱歉,拼写错误是 jcombobox。

标签: java swing windowbuilder jcheckbox


【解决方案1】:

在您澄清您实际上是指JComboBox 而不是JCheckBox 之后,这显然更有意义。我很快整理了一个最小的可重现示例,其中包含一个JComboBox,包括您的时间范围和一个提交按钮。单击提交按钮时,当前选定的时间范围将从组合框中删除。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多