【问题标题】:JButton and JComboBoxJButton 和 JComboBox
【发布时间】:2015-12-09 13:49:35
【问题描述】:

我的JButtonJComboBox 有问题。

当我点击我的JButton 时,它什么也不做。

我希望点击后弹出JOptionPane 消息。

selectionBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
    "Insert", "Delete", "Find", "Update"
}));
selectionBox.setSelectedIndex(0);
selectionBox.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        selection = selectionBox.getSelectedIndex();
        switch (selection) {
            case 0:
                selection = 0;
        }
    }
});
processButton.setText("Process Request");
processButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (selection == 0) {
            insertStudent();
        }
    }
});
public void insertStudent() {
    int id;
    String name;
    String major;
    id = Integer.parseInt(idTextField.getText());
    name = nameTextField.getText();
    major = majorTextField.getText();
    student.getID(id);
    student.getName(name);
    student.getMajor(major);
    JOptionPane.showMessageDialog(rootPane, "test");
}

【问题讨论】:

  • 您确定选择变量为 0 吗?使用 insertStudent();没有 if 语句的方法并检查是否会显示 JOptionPane。
  • switch(selection){ case 0: selection = 0; } 是不必要的......只是说。
  • 在每个动作侦听器的末尾放置一个 System.out.println 以打印选择的值。

标签: java swing


【解决方案1】:

我的建议是删除组合框中的 ActionListener。取而代之的是,访问 JButton 的动作侦听器中的当前选择的值,并确保您始终得到一些反馈:

processButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        switch(selectionBox.getSelectedIndex()) {
            case 0:
              insertStudent();
              break;
            default:
              JOptionPane.showMessageDialog(null, "Not yet implemented");
              break;
        }
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多