gpt4 book ai didi

java - 错误: The method getSelectedItem() is undefined when checking to see item selected

转载 作者:行者123 更新时间:2023-11-30 04:10:43 24 4
gpt4 key购买 nike

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

    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");
}
}
}

这是创建组合框并将人员添加到其中的位置。

     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]);
}

}

最佳答案

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

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

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

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

关于java - 错误: The method getSelectedItem() is undefined when checking to see item selected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19670553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com