0
At the level of Random in a package of Imageicon of flags of countries how to compare if it was typed right the name of the flag of the country in a Jtextfield by the user?
To randomize the images of the flags I’m getting so:
File file = new File("src/flagsII");
String[] imageNames = file.list();
Random rand = new Random();
I use one button to randomize the image and another to compare, since I can’t do this with a single button.
btnFlag.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Random
int index = rand.nextInt(8);
Image im = new ImageIcon(this.getClass().getResource("/flagsII/" + imageNames[index])).getImage();
ImageIcon iconLogo = new ImageIcon(im);
jlbFlag.setIcon(iconLogo);
}
});
jContentPane.add(btnFlag);
}
return jContentPane;
}
Now to compare I’m not getting:
int score = 0;
public void actionPerformed(ActionEvent e) {
// Random
// int flags = (int) (8 * Math.random() + 1);
// int flags = (int) (Math.random() * 8);
String country = textField.getText().toLowerCase();
switch (country) {
case "Australia":
// jlbFlag.setIcon(new
// ImageIcon(getClass().getResource(("flags/Australia.png"))));
if (imageNames.equals(country)) {
JOptionPane.showMessageDialog(null, "Correct", "Geography Quiz", JOptionPane.INFORMATION_MESSAGE);
score = score + 1;
lblScore.setText("Score: " + score);
} else {
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "incorrect!", "Geography Quiz", JOptionPane.ERROR_MESSAGE);
score = score - 1;
lblScore.setText("Score: " + score);
}
break;
case "Brazil":
// jlbFlag.setIcon(new ImageIcon(getClass().getResource(("flags/Brazil.png"))));
if (imageNames.equals(country)) {
JOptionPane.showMessageDialog(null, "Correct", "Geography Quiz", JOptionPane.INFORMATION_MESSAGE);
score = score + 1;
lblScore.setText("Score: " + score);
} else {
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "incorrect!", "Geography Quiz", JOptionPane.ERROR_MESSAGE);
score = score - 1;
lblScore.setText("Score: " + score);
}
break;
case "China":
// jlbFlag.setIcon(new ImageIcon(getClass().getResource(("flags/China
// (2).png"))));
if (imageNames.equals(country)) {
JOptionPane.showMessageDialog(null, "Correct", "Geography Quiz", JOptionPane.INFORMATION_MESSAGE);
score = score + 1;
lblScore.setText("Score: " + score);
} else {
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "incorrect!", "Geography Quiz", JOptionPane.ERROR_MESSAGE);
score = score - 1;
lblScore.setText("Score: " + score);
}
break;
default:
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "incorrect!", "Geography Quiz", JOptionPane.ERROR_MESSAGE);
break;
}
System.out.println(imageNames);
}
And to declare on the Submit button I declare this:
jbtSubmit.addActionListener(this);