错误:检查查看选定项时,方法getSelectedItem()未定义

时间:2013-10-29 22:42:44

标签: java

我正在为我的班级制作投票计划。到目前为止,我已经将GUI与登录窗口一起完成投票。我在向用户投票的人添加投票时遇到了问题。我的程序基本上可以工作,以便用户选择他们投票的人(JComboBox),当他们点击提交按钮(JButton)时,它会在单独的文本文件中为他们添加投票。错误是当我搜索以查看谁被选中时该部分的第一行。错误是“错误:方法getSelectedItem()未定义类型java.lang.String”。执行此操作的代码部分是:

    if (evt.getSource() == submitButton){ //JButton 
           for (int i = 0; i < valiNames.length; i++) {
            if (valiNames[i].getSelectedItem().toString()) { /*Checks to see who in the JComboBox is selected. Alse where error occurs.*/

              createScanner("ValiVotes.txt"); //Calls to seprate routine seen below.

              for (int j = 0; in.hasNext(); j++) {
                addValiVotes(); //Seprate sub-routine seen below.
               valiVotes[j] = in.nextInt();
              }
              valiVotes[i]++;          
              try {
        PrintWriter out = new PrintWriter(new FileWriter ("VotesCounted.txt"));          
                for (int j = 0; j < valiVotes.length;j++) {
                  out.println(valiVotes[j]);               
                }
                out.close();
              } catch (IOException exc) {          
              }            
              break;
            }
          }
        }      


    public static void addValiVotes() {
      int newSize = 1 + valiVotes.length;
      int[] newData = new int[newSize];
      System.arraycopy(valiVotes, 0, newData, 0, valiVotes.length);
      valiVotes = newData;
      voteCount++;
    }


    public static void createScanner(String fileName) {
      while(true){
        try {
          in = new Scanner( new File(fileName));
          break;
        }
        catch (FileNotFoundException e) {
          System.out.println("Wrong File");
        }
      }
    }

这是创建ComboBox并添加人员的地方。

     public static void main(String[] args) { /*Theres more to the main-routine, this is just where the ComboBox stuff happens*/
      valiComboBox = new JComboBox();
      centerPanel.add(valiComboBox);
      valiComboBox.setBounds(20, 70, 230, 40);
      valiComboBox.addActionListener(listener);
      valiComboBox.addItem("Please select a candidate below...");

      createScanner("ValiNames.txt");
      int j = 0;
      while (in.hasNext()) {
        addValiNames();
        valiNames[j] = in.next();
        j++;
      }

      for (int k = 0; k < valiNames.length; k++) {
        valiComboBox.addItem(valiNames[k]);
      }

}

1 个答案:

答案 0 :(得分:2)

我认为你想测试JComboBox中选择的值,假设它包含String个值,否则你必须调用方法toString()

if(myJComboBox.getSelectedItem().equals(valiNames[i]))   

<小时/>  或者,如果您的JComboBox包含除String之外的其他对象:

if(myJComboBox.getSelectedItem().toString().equals(valiNames[i]))