JOptionPane cancel button and getting input - java

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

Related

String data still remains? (Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string)

I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('') to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer + "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText is completely clear?
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
The variable userAnswer doesn't get cleared when answerText is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer); is called at a point where userAnswer is empty (because it can't make a number out of nothing).

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

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;

Validation when Creating an Account JAVA

So there is this certain part of my program where I can create an account and the created account will be inserted into my database. And I'm trying to code something where *refer to the code:
public void actionPerformed(ActionEvent e) {
String user = userField.getText().trim();
String pass = passField.getText().trim();
String conPass = confirmPass.getText().trim();
try{
// TODO Auto-generated method stub
if(e.getSource()==submit){
if (user.equals(user)&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if the pass field is blank
else if(user.length()<5){
JOptionPane.showMessageDialog(null,"Username must be at least 5 characters!");
}
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
GUI gui = new GUI();
}//if(pass.equals(conPass))
else if(user.length()==0&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if both fields are blank
else if (user.length()==0 &&pass.equals(pass)){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if user field is blank
else if(user.equals(user)&&pass!=conPass){
JOptionPane.showMessageDialog(null, "Password do not match!");
}//check if password and confirm pass matches
}
I dont really know how to say the problem but look in the if and else if statements, if the user meet one the those conditions, the program should print the JOptionPane thing. Except for the second else if.
You might be wondering why I put these codes at my else if
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
The reason for this is that, my program is having some logic error when I try to put it in if statement. Please help me with my code thanks :) Feel free to write a new code for me :DD
i might try something like this:
public static boolean isSet(String s){
if(s==null || "".equals(s)) return false;
return true;
}
//.... your validation here
if(isSet(user) && isSet(pass) && isSet(conPass) && pass.equals(conPass)){
//create account
}else{
//smth wrong eg. if(!pass.equals(conPass) { //wrongpass }
}

Data validation within data validation

I first want to validate that the user entered a value and to make sure to exit if 'cancel' was pushed. Then, I want to validate that the String releaseDateString is in the correct format at the same time as converting the String to java.sql.Date.
The first validation is taking place but then the JOptionPane carries on repeating itself and does not even consider the try and catch following it.
Here is my method
boolean retry = false;
java.sql.Date releaseDate = null;
String releaseDateString = "";
String title = "";
while (!retry) {
while(!retry){//field is validated to make sure a value was entered and to exit if cancel was pushed
releaseDateString = JOptionPane.showInputDialog("Please input the release date of the movie (yyyy-mm-dd)");
qtd.stringValidation(releaseDateString);
}
try { //the date is validated to make sure it is in the correct format
releaseDate = java.sql.Date.valueOf(releaseDateString);
} catch (Exception e) {
retry = false;
JOptionPane.showMessageDialog(null, "Make sure you enter a date in the format of 'dd-mm-yyy'");
}
}
It links to this method
public static boolean stringValidation(String attribute){
boolean retry = false;
if (attribute == null){
System.exit(0);
}
else if (attribute.equals("")) //if the cancel button is selected or no value was entered into the
{
JOptionPane.showMessageDialog(null, "Make sure you enter a character into the textbox");
}
else {
retry = true;
}
return retry;
}
When you do this,
qtd.stringValidation(releaseDateString);
You aren't assigning the result to retry. I believe you wanted,
retry = qtd.stringValidation(releaseDateString);

Why won't this method call work?

I'm creating a method to take an input by a user and validate it to make sure it's correct. If it's correct it will call a method and input the user input in to it. But for some reason, the method call is not working. It doesn't produce any errors, it just simply doesn't do it. I placed a print statement at the end of the code to make sure it actually reaches there and it does, but for some reason it's just not calling the method like it's supposed to. The other method works fine if I call it by itself and input a string via the parameters.
The code is:
public void getGetScheduledShowByFilmInput()////new - omar////
{
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
String filmInput;
filmInput = "";
boolean foundFilm;
foundFilm = false;
System.out.println("Here is a list of films that are currently showing:");
for(Film film : films){
System.out.println(film.getFilmName());
}
System.out.println("");
System.out.println("Please type the film name that you wish to view the corresponding shows for and press enter.");
System.out.println("Type 'exit' and press enter to exit this process.");
while(foundFilm == false){
try{
filmInput = reader.readLine();
}
catch (IOException e){
System.out.println("Error");
}
//If user enters "exit" then return.
if(filmInput.equals("exit")){
return;
}
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName() == filmInput){
foundFilm = true;
break;
}
}
if(foundFilm = true){
System.out.println("Film found.");
}
else{
System.out.println("The film name you entered has not been recognised. Please try again.");
}
}
//Call the function and input the film name input by the user.
getScheduledShowsByFilm(filmInput); ////This is the code that seems to be the problem.
System.out.println("reached bottom");
}
and the second method is:
public void getScheduledShowsByFilm(String inputFilmName)
{
ArrayList<Show> scheduledShows;
scheduledShows = new ArrayList<Show>();
for(Film film : films){
if(inputFilmName == film.getFilmName()){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}
for(Show show : scheduledShows){
System.out.println("**********************************");
show.getShowDetails();
System.out.println("**********************************");
}
}
The second method works perfectly when I call it on its own and enter parameters manually though.
It's probably something extremely simple that I'm not understanding! haha, thank you for your help :)
foundFilm can never be false because you always assign true to it:
if(foundFilm = true){
System.out.println("Film found.");
}
try changing it to this:
if(foundFilm)
{
System.out.println("Film found.");
}
In getGetScheduledShowByFilmInput() and getScheduledShowsByFilm(String) avoid doing string comparison using the equality operator (==). The == operator tests for object equality, but you want to test whether two strings contain the same sequence of characters. Therefore, use equals instead:
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName().equals(filmInput)){
foundFilm = true;
break;
}
}
and
for(Film film : films){
if(inputFilmName.equals(film.getFilmName())){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}

Categories

Resources