I want to make an options window where a JOptionPane is opened, the user goes through it, and it sets options. I have a problem on lines 10-14 of the following code, though.
if (key == KeyEvent.VK_ENTER) {
Object[] possibleValues = { "Trails (Broken)", "Invicibility" };
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
if (possibleValues[0] != null) {
Object[] options = {"True", "False"};
JOptionPane.showOptionDialog(null,
"Press True To Make It True And False For False",
(String) possibleValues[0], JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (options[0] != null) {
Options.OP_TRAILS = true;
} else if(options[1] != null) {
Options.OP_TRAILS = false;
}
}
}
I think you need to have a read of the JOptionPane JavaDocs and How to Make Dialogs in order to understand what is been returned to you
JOptionPane is providing you withing information about what the user selected. For example...
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
selectedValue is going to either be null (for nothing was selected) or one of the values from the possibleValues array.
JOptionPane.showOptionDialog will return:
an integer indicating the option chosen by the user, or CLOSED_OPTION if the user closed the dialog
Something like this...
Object[] possibleValues = {"Trails (Broken)", "Invicibility"};
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
System.out.println(selectedValue);
if (possibleValues[0].equals(selectedValue)) {
// Trails (Broken) was selected
Object[] options = {"True", "False"};
int result = JOptionPane.showOptionDialog(null, "Press True To Make It True And False For False", (String) possibleValues[0], JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
switch (result) {
case 0:
Options.OP_TRAILS = false;
break;
case 1:
Options.OP_TRAILS = false;
break;
}
} else if (possibleValues[1].equals(selectedValue)) {
// Invicibility was selected
}
might be more appropriate
Related
Im creating a project where the area or volume of certain shapes are calculated using dropdown menus in java. I don't have any errors when compiling however I'm getting the message that "Unlikely argument type for equals(): String seems to be unrelated to String[]". As stated, it complies fine, but when running it allows area/volume to be selected, but it does not reach the next option pane to select the shapes.
The message appears on: if (choices.equals("Area"))
and : if (choices.equals("Volume"))
`
import javax.swing.JOptionPane;
public class Shapes
{
public static void main(String[] args)
{
//Dropdown menu for area and volume
String[] choices = {"Area", "Volume"};
String question = (String) JOptionPane.showInputDialog(null, "What would you like to calculate?",
"Shapes", JOptionPane.QUESTION_MESSAGE, null,
choices,
choices[0]);
System.out.println(question);
if (choices.equals("Area"))
{
//user chooses area
String[] choices2D = {"triangle", "parallelogram", "rectangle", "trapezoid", "circle"};
String question2D = (String) JOptionPane.showInputDialog(null, "What shape will you choose?",
"Shapes", JOptionPane.QUESTION_MESSAGE, null,
choices2D,
choices2D[0]);
System.out.println(question2D);
}
//user chooses volume
if (choices.equals("Volume"))
{
String[] choices3D = {"cone", "cylinder", "rectanglular prism", "trapezoid prism", "sphere"};
String question3D = (String) JOptionPane.showInputDialog(null, "What figure will you choose?",
"Shapes", JOptionPane.QUESTION_MESSAGE, null,
choices3D,
choices3D[0]);
System.out.println(question3D);
}
}
}
`
I originally had the options linked to a switch but would keep running into errors, after changing it to an if statement it will compile but not run properly.
Your comparisons are choices.equals(…), but you meant to compare the selection from the dropbox, and this is stored in question. So the comparisons should be question.equals(…).
Alternatively, try this:
import javax.swing.JOptionPane;
public class Shapes
{
public static void main(String... args)
{
//Dropdown menu for area and volume
String[] choices = {"Area", "Volume"};
String question = (String) JOptionPane.showInputDialog( null,
"What would you like to calculate?",
"Shapes",
JOptionPane.QUESTION_MESSAGE,
null,
choices,
choices[0]) ;
System.out.println(question);
switch( question )
{
case "Area":
{
//user chooses area
String[] choices2D = {"triangle", "parallelogram", "rectangle", "trapezoid", "circle"};
String question2D = (String) JOptionPane.showInputDialog( null,
"What shape will you choose?",
"Shapes",
JOptionPane.QUESTION_MESSAGE,
null,
choices2D,
choices2D[0] );
System.out.println( question2D );
break;
}
case "Volume":
{
//user chooses volume
String[] choices3D = {"cone", "cylinder", "rectanglular prism", "trapezoid prism", "sphere"};
String question3D = (String) JOptionPane.showInputDialog( null,
"What figure will you choose?",
"Shapes",
JOptionPane.QUESTION_MESSAGE,
null,
choices3D,
choices3D[0] );
System.out.println( question3D );
break;
}
}
}
}
You can also use the new switch-case syntax and optimise further, by using enums for the various choices.
You are comparing the whole array with a single string. Use choices[0].equals("Area"). Now this will compare choices array with string at index 0 with Area.
I'm trying to get the user to input there name if it is left blank it will ask again, if they fill it out it sets a JLabel or hit cancel to get out.
My last if statement is wrong it does not like nameEnt.
public Player() {
//setBackground(Color.green);
setSize(600, 400);
name = new JLabel();//Input hint
JOptionPane nameOption = new JOptionPane();
String nameEnt = nameOption.showInputDialog("First Name: ");
if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
}
if (nameEnt.length() == 0) {
//if this condition is true JOption stays until name is entered or canceled
}
if (nameEnt == nameOption.CANCEL_OPTION) {
System.exit(0);
}
}
The JOptionPane.CANCEL_OPTION is a static int field, and you can't compare String with int with ==.
Good practice
In your case you want to use ok and cancel button JOptionPane.showConfirmDialog and JOptionPane.showInputDialog() in one shot and this is not possible, i suggest to use this instead :
JTextField nameF = new JTextField(20);//create TextField
JPanel myPanel = new JPanel();//cerate JPanel
myPanel.add(new JLabel("Name"));
myPanel.add(nameF);//add your JTextField to your panel
int result;
do {
result = JOptionPane.showConfirmDialog(null, myPanel,
"Title of Panel", JOptionPane.OK_CANCEL_OPTION);//add your panel to JOptionPane
if (result == JOptionPane.OK_OPTION) {//if the user press OK then
if (nameF.getText().isEmpty()) {//check if the input is empty
//if this condition is true JOption stays until name is entered or canceled
} else if (!nameF.getText().matches("[a-zA-Z]+")) {//check if the input match with your regex
//name match exactly
//name.setText(nameF.getText());
}
}
} while (result != JOptionPane.CANCEL_OPTION);//If the user hit cancel then exit
As per the JOptionPane API, if the user cancels the dialog, null is returned.
And so the correct solution is to to not to use equals, but rather to check the return value for null and to do this first, before checking its length.
public Player() {
//setBackground(Color.green);
setSize(600, 400);
name = new JLabel();//Input hint
JOptionPane nameOption = new JOptionPane();
String nameEnt = nameOption.showInputDialog("First Name: ");
if (nameEnt == null) {
// user canceled. get out of here.
System.exit(0);
// or return;
// or throw some exception
}
if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
}
if (nameEnt.length() == 0) {
//if this condition is true JOption stays until name is entered or canceled
}
// if (nameEnt == nameOption.CANCEL_OPTION) {
// System.exit(0);
// }
}
But why are you creating a JOptionPane this way? Better to use the static method of creation.
// don't use null as the first parameter if the GUI is already showing
String nameEnt = JOptionPane.showInputDialog(null, "First Name: ");
if (nameEnt == null) {
// user canceled. get out of here.
System.exit(0);
}
Or maybe something like this, if you're trying to loop to get input:
public Player() {
setSize(600, 400); // This is not good to do. Ask for details and I'll tell.
name = new JLabel();// Don't forget to add this to the GUI!
String nameEnt = "";
while (nameEnt.trim().isEmpty()) {
// if the GUI is already showing, pass a component from it as the first param here, not null
nameEnt = JOptionPane.showInputDialog(null, "First Name: ");
if (nameEnt == null) {
// user canceled. get out of here.
System.exit(0);
// or return;
// or throw some exception
} else if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
} else {
// set it to "" so that we keep looping
nameEnt = "";
}
}
}
String nmEmp = fName.getText();
if(nmEmp.trim().isEmpty() || nmEmp.trim().equals("")){
JOptionPane.showMessageDialog(null, "Empty Name", "Name Confirmation", JOptionPane.YES_OPTION);
}
Why JOptionPane cannot stop flow of execution, in my application ? And java keep running to executing code below JOptionPane, if JOptionPane execution in true condition. And what reason, this happen?. Please help, Thank you
From Java documentation JOptionPane : https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
Direct Use:
To create and use an JOptionPane directly, the standard pattern is
roughly as follows:
JOptionPane pane = new JOptionPane(arguments);
pane.set.Xxxx(...); // Configure
JDialog dialog = pane.createDialog(parentComponent, title);
dialog.show();
Object selectedValue = pane.getValue();
if(selectedValue == null)
return CLOSED_OPTION;
//If there is not an array of option buttons:
if(options == null) {
if(selectedValue instanceof Integer)
return ((Integer)selectedValue).intValue();
return CLOSED_OPTION;
}
//If there is an array of option buttons:
for(int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++) {
if(options[counter].equals(selectedValue))
return counter;
}
return CLOSED_OPTION;
I'm using the Message Dialog of org.eclipse.jface.dialogs and i need to rename the 'Ok' and 'Cancel' text in the buttons displayed. How to go about ?
MessageDialog requestRestartDialog = new MessageDialog(window.getShell(), "Title", null,
"Message to be displayed", MessageDialog.CONFIRM, new String[] { "String 1", "String 2" }, 0);
int index = requestRestartDialog.open();
index will return the array index of the label specified.
can't get the buttons in the OptionDialog to appear on a new line.
They all appear in one row, but I'd like to have them on separate lines.
I also tried setting up a frame to add to the OptionDialog (to set the max width), but it didn't work out for me either.
Any ideas/help/suggestions appreciated.
Object[] options = { "Button1", "Button2", "Button3", "Button4",
"Button5 On a newLine\n\n", "Button 6", "Button 7" };
int x = JOptionPane.showOptionDialog(null, "Choose a button..", "Title",
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
Consider this alternative.
import javax.swing.*;
class Options {
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
Object[] options = {
"Option 1",
"Option 2",
"Option 3",
"Option 4",
"Option 5",
"Option 6",
"Option 7",
"None of the above"
};
JComboBox optionList = new JComboBox(options);
optionList.setSelectedIndex(7);
JOptionPane.showMessageDialog(null, optionList, "Title",
JOptionPane.QUESTION_MESSAGE);
}
});
}
}
You can't do that using the Option Dialog from JOptionPane, but you still can create your own dialog window by extending JDialog, and this way you will be able to use the layout you want for your components.
Create your own OptionPane class if you want to break buttons in multiple lines.
You'll be breaking a bunch of UI standards in doing so, though.
The same kind of answer as above, but more concrete:
Object[] options = outputcdirs;
JComboBox optionList = new JComboBox(outputcdirs);
optionList.setSelectedIndex(0);
JPanel jpan = new JPanel ();
jpan.add(new JLabel("Select dirs:"));
jpan.add(optionList);
int n = JOptionPane.showOptionDialog(this, jpan, "text...",
JOptionPane.DEFAULT_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
null,
null);
if (n != -1)
n = optionList.getSelectedIndex();
if (n == -1)
throw new Exception("No selection: ...");
String value = outputcdirs[n];