【问题标题】:cancel JComboBox actionEvent取消 JComboBox 动作事件
【发布时间】:2012-01-19 05:00:58
【问题描述】:

我正在编写一个 gui 程序,并且有一个用于打开文件的 Jbutton 的 AbstractAction。在 JComboBox 中,我有一个已打开文件的列表。 JComboBox 的 AbstractAction 将变回任何已打开的文件。当我更新 JComboBox 的列表时,虽然动作触发了。

因此,当我实际打开文件时,JComboBox 动作会触发,而当我使用 JComboBox 时,动作会触发一次,然后在更新时触发第二次。

有没有办法在更新 JComboBox 列表时停止事件?

提前致谢

【问题讨论】:

  • 您可以删除监听器,然后重新添加。或者你可以让它的动作由一个布尔字段控制。
  • 删除、重新添加是否比仅仅让事件被调用以及在 AbstractAction actionPerformed 方法中进行检查更有效?目前我只是检查新文件的名称是否等于更新,如果是,我会跳过事件中发生的大部分内容。

标签: java swing events jcombobox


【解决方案1】:

答案在设计中,尤其是在关注点分离方面:不要考虑视图与两个动作,而是考虑多视图更改单个数据的状态。

在伪代码中类似于:

// data class
public class MyOpenFilesBean {

    private File currentFile; 

    public void setCurrentFile(File current) {
         File old = getCurrentFile();
         this.currentFile = current;
         firePropertyChange("currentFile", old, getCurrentFile());
    }

    public File getCurrentFile() {
        return currentFile;
    }

}  

// view wiring (view --> data)

Action open = new AbstractAction(...) {

      public void actionPerformed(...) {
          File choosenFile = // grab it from whereever in the view
          myOpenFileBean.setCurrentFile(choosenFile);
      }  

};
myButton.setAction(open);
myComboBox.setAction(open);

// view wiring (data --> view)

PropertyChangeListener l = new PropertyChangeListener() {
     public void propertyChanged(...) {
         if ("currentFile".equals(evt.getPropertyName()) {
               // a method implemented to update f.i. the combo selection  
               updateView((File) evt.getNewValue());
         }
     } 
};
myOpenFileBean.addPropertyChangeListener(l);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多