【问题标题】:ComboBox with ActionListener and if-statement带有 ActionListener 和 if 语句的组合框
【发布时间】:2015-04-05 07:30:23
【问题描述】:

我正在尝试向我的 ComboBox 添加一个 ActionListener。当从框中选择一个项目时,我想打开一个表单。我在 JButton 上成功实现了它,但我不知道如何在组合框中执行它。有人可以帮帮我吗?

    JComboBox<String> valBox = new JComboBox<>();   

    valBox.addItem("Apparat");
    valBox.addItem("Smycke");
    valBox.addItem("Aktie");
    södra.add(valBox);

    valBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (valBox.getSelectedIndex() == 0)
                nyLyss.ApparatForm.form1();
        }
    });

选择第一项时我不想执行的代码是这个:

    class nyLyss implements ActionListener{
    public void actionPerformed(ActionEvent ae) {
        try{
            ApparatForm form1 = new ApparatForm();

            int svar = JOptionPane.showConfirmDialog(Layout.this, form1);
            if(svar != JOptionPane.OK_OPTION)
                return;
            String namn = form1.getNamn();
            int inköpspris = form1.getPris();
            int slitage = form1.getPris();
    //      saker ap = new saker(namn, inköpspris, slitage);
    //      alla.add(ap);

        }catch(NumberFormatException e){
            JOptionPane.showMessageDialog(Layout.this, "Felaktig indata!");
        }
    }
}

谢谢! :)

【问题讨论】:

  • 我在 JButton 上成功实现了它:然后将与您添加到按钮的 ActionListener 完全相同的 ActionListener 添加到组合框中,它应该可以工作。
  • 我投票决定将此问题作为题外话结束,因为官方教程中涵盖了这个问题 - How to Use Combo Boxes: Handling Events on a Combo Box

标签: java swing jcombobox


【解决方案1】:

我会在我的组合框中使用 ItemStateChanged 侦听器来解决问题。这里有一个名为“mycombobox”的组合框的简短示例。

private void mycomboboxItemStateChanged(java.awt.event.ItemEvent evt) {                                            

    System.out.println(mycombobox.getSelectedItem());

} 

结果是,应用程序在每次更改组合框“mycombobox”中的选定项目后打印出选定的项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 2021-06-19
    • 1970-01-01
    相关资源
    最近更新 更多