【问题标题】:Action listener not working动作监听器不工作
【发布时间】:2012-07-31 08:31:57
【问题描述】:

我试图为JComboboxe实现一个动作列表,以便选择列表中的项目,并且确定jbutton点击后,我希望它出现在一个新的GUI中,我在其中定义了一个文本字段时项目是从组合框中选择的,它将出现在 gui 的文本字段中,以及选择的项目的详细信息。

这个例子显示了一个组合框,但我总共有 6 个。

jComboBox4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox4.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        jComboBox4MouseClicked(evt);
    }
});

【问题讨论】:

  • 如果您希望在单击 JButton 时发生某些事情,则将您的 ActionListener 附加到 JButton,而不是 JComboBox。
  • JButton(OK Button)actionPerformed(...) 方法内,只需使用jComboBox4.getSelectedItem() and so on for others 并简单地传递它,以显示在其他组件中,根据需要:-)
  • 非常感谢您的帮助,但这似乎不起作用我在两个地方都按照指示尝试了它们 Jbutton 1 是主按钮,或者换句话说(确定按钮
  • private void jComboBox4ActionPerformed(java.awt.event.ActionEvent evt) { jComboBox4.getSelectedItem() 然后在这里
  • 私人无效 jComboBox4MouseClicked(java.awt.event.MouseEvent evt) { jComboBox4.getSelectedItem()

标签: java swing action actionlistener


【解决方案1】:

首先在所需按钮上添加ActionListener

// When the button is clicked this is called...
public class ButtonActionListener extends ActionListener {
    public void actionPerformed(ActionEvent evt) {
        Object value = comboBox.getSelectedItem();
        // check for null value
        // do what ever it is you want to do after that...            
    }
}

如果你想监听 Co​​mboBox 的变化,你有很多选择,最简单的就是 ActionListener

// When the button is clicked this is called...
public class ComboBixActionListener extends ActionListener {
    public void actionPerformed(ActionEvent evt) {
        Object value = comboBox.getSelectedItem();
        // The combo box value has changed, maybe update the text field???
    }
}

【讨论】:

  • 再次非常感谢,但仍然无法得到它,无论我把它放在细节中的文本字段中单击组合框时它都不会改变 gui 与 netbeans 的私有或公共新手有关试图用它找到我的脚
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 2013-07-12
  • 1970-01-01
  • 2017-02-10
相关资源
最近更新 更多