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