This is likely the code you will want to use (or some variation of it):
Object[] possibleChoices = {"Car", "Truck"};
Object choice = JOptionPane.showInputDialog(null, "Choose a vehicle type", "Choose Vehicle", JOptionPane.PLAIN_MESSAGE, null, possibleChoices, possibleChoices[0]);
switch (choice.toString)
{
case "Car":
//insert code for if this choice is made
break;
case "Truck":
//insert code for if this choice is made
break;
}
To explain:
The following creates an array for the drop down list in the JOptionPane box.
Object[] possibleChoices = {"Car", "Truck"};
The following opens the JOptionPane and puts the value that is chosen into the reference variable "choice". It uses the constructor JOptionPane(Object message, int messageType, int optionType, Icon icon, Object[] options, Object initialValue).
Object choice = JOptionPane.showInputDialog(null, "Choose a vehicle type", "Choose Vehicle", JOptionPane.PLAIN_MESSAGE, null, possibleChoices, possibleChoices[0]);
The switch statement then executes code based on what the choice is. Note that it uses the choice.toString() method which is necessary since the array must be an Object and can't be cast as a string from that array in the second line of the code.
If you want to be able to create a second choice based on the choice made in this JOptionPane you can simply have it open a second JOptionPane which uses a different array based on the choice made in the first JOptionPane and then add another switch statement to execute code made from the second choice like so:
.
For example the full code would look something like this:
Object[] possibleChoices = {"Car", "Truck"};
Object choice = JOptionPane.showInputDialog(null, "Choose a vehicle type", "Choose Vehicle", JOptionPane.PLAIN_MESSAGE, null, possibleChoices, possibleChoices[0]);
switch (choice.toString)
{
case "Car":
//insert code for if this choice is made
break;
case "Truck":
//insert code for if this choice is made
break;
}
Object[] carChoices = {"Honda", "Nissan", "Acura"};
Object[] truckChoices = {"Ford", "GM"};
Object choice2;
switch (choice.toString)
{
case "Car":
choice2 = JOptionPane.showInputDialog(null, "Choose a car type", "Choose Car", JOptionPane.PLAIN_MESSAGE, null, carChoices, carChoices[0]);
break;
case "Truck":
choice2 = JOptionPane.showInputDialog(null, "Choose a vehicle type", "Choose Vehicle", JOptionPane.PLAIN_MESSAGE, null, truckChoices, truckChoices[0]);
break;
}
switch (choice2.toString())
{
case "Honda":
//code for this choice;
break;
case "Nissan":
//code for this choice;
break;
case "Acura":
//code for this choice;
break;
case "Ford":
//code for this choice;
break;
case "GM":
//code for this choice;
break;
}
For more information on JOptionPane you can refer to:JavaDocs for JOptionPane