Reputation: 93
I'm making a voting program for my class. So far I've gotten the GUI finished along with the login window to vote. I'm having a problem though with adding a vote to the person who is being voted by the user. My program basically works so that the user picks their person they're voting for (JComboBox) and when they click the submit button (JButton), it adds a vote to them in a separate text file. The error is that the first line of that part when I search to see who is being selected. The error is "Error: The method getSelectedItem() is undefined for the type java.lang.String". The part of the code that does this is:
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");
}
}
}
This is where The ComboBox is created and people are added to it.
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]);
}
}
Upvotes: 1
Views: 1650
Reputation: 93872
I think you want to test the value selected in the JComboBox
, assuming that it contains String
values, otherwise you'll have to call the method toString()
if(myJComboBox.getSelectedItem().equals(valiNames[i]))
JComboBox
holds other objects than String
:
if(myJComboBox.getSelectedItem().toString().equals(valiNames[i]))
Upvotes: 2