1

我正在为我的班级制作一个投票程序。到目前为止,我已经完成了 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]);
      }

}
4

1 回答 1

2

我认为您想测试在 中选择的值JComboBox,假设它包含String值,否则您将不得不调用该方法toString()

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


或者,如果您JComboBox持有的物品不是String

if(myJComboBox.getSelectedItem().toString().equals(valiNames[i]))
于 2013-10-29T22:45:15.060 回答