Why JOptionPane cannot stop flow of execution, in my application? - java

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;

Related

JOptionPane cancel button and getting input

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

How can I target a string in an array in Java?

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

How to get value of selected radioButton of buttonGroup

How to get value of selected radioButton?
I tried using buttonGroup1.getSelection().getActionCommand() (as posted in some of answers here) but it is not working.
Also, i am temporarily using this code but i want to know is this a good practice or not?
//Consider that maleRButton and femaleRButton are two radioButtons of
//same buttonGroup
String getGender()
{
if(maleRButton.isSelected())
{
return "Male";
}
else if(femaleRButton.isSelected())
{
return "Female";
}
else
{
return null;
}
}
I tried using buttonGroup1.getSelection().getActionCommand()
That approach will work, but for some reason it looks like you manually need to set the action command when you create the button. For example:
JRadioButton maleButton = new JRadioButton( "Male" );
maleButton.setActionCommand( maleButton.getText() );
This acutally seems like a bit of a bug to me since usually the action command defaults to the text if the action command is not set.
If you have several buttons you probably should do it this way :
String getSelectedButton()
{
for (Enumeration<AbstractButton> buttons = buttonGroup1.getElements(); buttons.hasMoreElements();) {
AbstractButton button = buttons.nextElement();
if (button.isSelected()) {
return button.getText();
}
}
return null;
}
String gender=group.getSelection().getActionCommand();
It will work but it show null value.
int selectedRadioButtonID = radio_group.getCheckedRadioButtonId();
// If nothing is selected from Radio Group, then it return -1
if (selectedRadioButtonID != -1) {
RadioButton selectedRadioButton = findViewById(selectedRadioButtonID);
String selectedRadioButtonText = selectedRadioButton.getText().toString();
answerList.add(selectedRadioButtonText);
} else {
Toast.makeText(this, "select radio button", Toast.LENGTH_SHORT).show();
return false;
}
For Deatils, check this

calling a function from textfield java gui

my question relates to java gui with netBeans
i'm trying to call a function from a TextField "Block"
but some how my gui freezing's when I do the following:
by the way if it's matters the other function called "startconnection();"
are private to... (p.s->Forgive me for my english...)
private void userTextActionPerformed(java.awt.event.ActionEvent evt) {
String str = evt.getActionCommand();
if(connected)
sendMessage(str);
else{
if((str.length() > 10) &&
(str.subSequence(0, 9).equals("<connect>")) &&
(str.charAt(9)== '<' )&&
(str.charAt(str.length()-1) == '>')&&
(!connected))
{
clientName = str.substring(10, str.length()-1);
userText.setText("");
startConnection();//sweet spot!! this is where i'm stack...
}else{
chatArea.append("Invalid input if you want to connect\nplease type '<connect><Your Name>'\n");
}
}
}

Force JOptionPane to Stay Open

My application is constructed as follows:
Main window allows user to select CSV file to be parsed
JOptionPane appears after a CSV file is selected and the JOptionPane contains a drop-down menu with various choices; each of which generates a separate window
Currently, the JOptionPane closes after a selection is made from the menu and the "OK" button is clicked
I am looking for a way to force the JOptionPane to remain open so that the user can select something different if they want. I would like the JOptionPane to be closed only by clicking the "X" in the upper right corner. I am also open to other possibilities to achieve a similar result if using a JOptionPane isn't the best way to go on this.
Here is the relevant block of code I'm working on:
try
{
CSVReader reader = new CSVReader(new FileReader(filePath), ',');
// Reads the complete file into list of tokens.
List<String[]> rowsAsTokens = null;
try
{
rowsAsTokens = reader.readAll();
}
catch (IOException e1)
{
e1.printStackTrace();
}
String[] menuChoices = { "option 1", "option 2", "option 3" };
String graphSelection = (String) JOptionPane.showInputDialog(null,
"Choose from the following options...", "Choose From DropDown",
JOptionPane.QUESTION_MESSAGE, null,
menuChoices, // Array of menuChoices
menuChoices[0]); // Initial choice
String menuSelection = graphSelection;
// Condition if first item in drop-down is selected
if (menuSelection == menuChoices[0] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option1();
}
if (menuSelection == menuChoices[1] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option2();
}
if (menuSelection == menuChoices[2] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option3();
}
else if (graphSelection == null)
{
log.append("Cancelled." + newline);
}
}
I would like for the window with the choices to remain open even after
the user has selected an option so that they can select another option
if they wish. How do I get the JOptionPane to remain open instead of
its default behavior where it closes once a drop-down value is
selected?
this is basic property, by default JOptionPane is disposed, this isn't possible without dirty hacks, don't do that
use JDialog (could, may be undecorated) with proper value for ModalityType
you can to use some of variations for Java & Ribbon
you can to put desired choices to the JComboBox or JMenu with JMenuItems (very nice of ways) to the JLayer or GlassPane
I think that this is standard job for JMenu or JToolBar
In either of these option panes, I can change my choice as many times as I like before closing it. The 3rd option pane will show (default to) the value selected earlier in the 1st - the current value.
import java.awt.*;
import javax.swing.*;
class Options {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
Object[] options = {
"Option 1",
"Option 2",
"Option 3",
"None of the above"
};
JComboBox optionControl = new JComboBox(options);
optionControl.setSelectedIndex(3);
JOptionPane.showMessageDialog(null, optionControl, "Option",
JOptionPane.QUESTION_MESSAGE);
System.out.println(optionControl.getSelectedItem());
String graphSelection = (String) JOptionPane.showInputDialog(
null,
"Choose from the following options...",
"Choose From DropDown",
JOptionPane.QUESTION_MESSAGE, null,
options, // Array of menuChoices
options[3]); // Initial choice
System.out.println(graphSelection);
// show the combo with current value!
JOptionPane.showMessageDialog(null, optionControl, "Option",
JOptionPane.QUESTION_MESSAGE);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
I think Michael guessed right with a JList. Here is a comparison between list & combo.
Note that both JList & JComboBox can use a renderer as seen in the combo. The important difference is that a list is an embedded component that supports multiple selection.
The following solution won't give you a drop-down menu but it will allow you to select multiple values.
You can use a JList to store your choices and to use JOptionPane.showInputMessage like this:
JList listOfChoices = new JList(new String[] {"First", "Second", "Third"});
JOptionPane.showInputDialog(null, listOfChoices, "Select Multiple Values...", JOptionPane.QUESTION_MESSAGE);
Using the method getSelectedIndices() on listOfChoices after the JOptionPane.showInputDialog() will return an array of integers that contains the indexes that were selected from the JList and you can use a ListModel to get their values:
int[] ans = listOfChoices.getSelectedIndices();
ListModel listOfChoicesModel = listOfChoices.getModel();
for (int i : ans) {
System.out.println(listOfChoicesModel.getElementAt(i));
}

Categories

Resources