帮助实现JComboBox []侦听器

问题描述

| 1)在以下方法(actionListener)中,用户从JComboBox中选择成绩(例如A-F)。 2)有多个JComboBoxes,每个选择都存储在单个String []数组中。 问题: 这是一个难题,如果用户返回并更改从随机JComboBox所做的选择,则以前的成绩选择不会在数组中被替换,但是所做的新选择将存储在下一个数组索引中。 我如何才能使程序代替以前的成绩选择而不仅仅是添加新的选择? 相关变量:
int counter;
private JComboBox[] gradeField;
//grade.userGrades[] is array of grades taken from selected combo boxes                  
动作侦听器匿名类:
gradeField[counter].addActionListener(new ActionListener () {
            @Override
            public void actionPerformed(ActionEvent e) {
                Object holder = e.getSource();
                JComboBox tempGradeBox = (JComboBox)holder;
                String theGrade = (String)tempGradeBox.getSelectedItem();
                grade.userGrades[grade.getNext()] = theGrade;
                grade.updateNext();
            }                       
        });
在此先感谢您的帮助。     

解决方法

        更新用户等级与组合框的索引相同:
    final int index = counter;
    gradeField[counter].addActionListener(new ActionListener () {
        @Override
        public void actionPerformed(ActionEvent e) {
            Object holder = e.getSource();
            JComboBox tempGradeBox = (JComboBox)holder;
            String theGrade = (String)tempGradeBox.getSelectedItem();
            grade.userGrades[index] = theGrade;
        }                       
    });
    ,           我将成绩保存在数组中并增加索引, 好吧,您不应该增加索引。假定用户从组合框中按顺序选择成绩。如您所见,用户经常可以随机工作。 相反,您需要知道哪个组合框已更改,然后更新阵列中的相应条目。 或其他解决方案可能是在最后更新阵列。因此,也许您有一个“处理结果”按钮。然后,您可以依次遍历所有组合框以获取选定的值。     ,        这是JB Nizet答案的另一种变化:
class OuterClass
{
 ...

 gradeField[counter].addActionListener( new GradeSettingActionListener( counter ) );

 ...
 class GradeSettingActionListener implements ActionListener
 {
  // -- Doesn\'t have to be final here (it does in JB\'s answer),but I like to be restrictive.
  private final int index;

  public GradeSettingActionListener( int index )
  {
   this.index = index;
  }

  @Override
  public void actionPerformed( ActionEvent e )
  {
   Object holder = e.getSource();
   JComboBox tempGradeBox = (JComboBox) holder;
   String theGrade = (String) tempGradeBox.getSelectedItem();
   grade.userGrades[index] = theGrade;
  }
 }
}
此方法通过添加内部类来删除匿名类。内层阶级仍然可以使用
grade
。除非有机会稍后再拆分内部类,否则您在这里不会获得太多收益。 当然,camickr建议一次处理所有成绩的建议也可能有效,这取决于其他要求(即,在将成绩存储在数组中之后是否进行了其他处理,这似乎是可能的)。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...