Frame not disposing [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 days ago.
Improve this question
I don't know why my JFrame is not closing with this code:
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit){
//Input
String name = textField1.getText();
String lastName = textField2.getText();
//Input check
if(textField1.getText().isEmpty() && textField2.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "Both name and last name not entered!", "Warning", JOptionPane.WARNING_MESSAGE);
}else if(textField2.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "Last name not entered!", "Warning", JOptionPane.WARNING_MESSAGE);
}else if(textField1.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "Name not entered!", "Warning", JOptionPane.WARNING_MESSAGE);
}else{
frame.dispose();
JOptionPane.showMessageDialog(null, "Hello " + name + " " + lastName, "Welcome", JOptionPane.PLAIN_MESSAGE);
}
I want to close the main window after the user clicks the "OK" on the dialog, but it just ignores the dispose() method.

You have to use this because your class extends JFrame, most likely something like:
public class MyClass extends javax.swing.JFrame implements ActionListener {
On A Side:
Because you have already established that String name = textField1.getText(); and lastName = textField2.getText();, you just need to use those variables within you if conditions, for example:
//Input check
if(name.isEmpty() && lastName.isEmpty()){
JOptionPane.showMessageDialog(this, "Both first and last name not entered!", "Warning", JOptionPane.WARNING_MESSAGE);
}else if(lastName.isEmpty()){
JOptionPane.showMessageDialog(this, "Last name not entered!", "Warning", JOptionPane.WARNING_MESSAGE);
}else if(name.isEmpty()){
JOptionPane.showMessageDialog(this, "First Name not entered!", "Warning", JOptionPane.WARNING_MESSAGE);
}else{
this.dispose();
JOptionPane.showMessageDialog(null, "Hello " + name + " " + lastName, "Welcome", JOptionPane.PLAIN_MESSAGE);
}
You will also notice that this is used as parent for your JOptionPane's except the last one. This is because of where this.dispose(); is located within the else block.
As is currently used,
else{
this.dispose();
JOptionPane.showMessageDialog(null, "Hello " + name + " " + lastName, "Welcome", JOptionPane.PLAIN_MESSAGE);
}
when the else block is run, the form will go invisible but will not fully dispose until the JOptionPane's OK button is selected. This may be the more desirable effect you are looking for.
In the else block, if this.dispose(); is was run before the JOptionPane and this is used as the JOptionPane's parent then the form will go invisible but, the JFrame will never be fully released and your application could remain open unless forcefully closed.
else{
this.dispose();
JOptionPane.showMessageDialog(this, "Hello " + name + " " + lastName, "Welcome", JOptionPane.PLAIN_MESSAGE);
}
In the else block, if this.dispose(); is run after the JOptionPane's OK button is selected,
else{
JOptionPane.showMessageDialog(this, "Hello " + name + " " + lastName, "Welcome", JOptionPane.PLAIN_MESSAGE);
this.dispose();
}
then the JOptionPane will become visible over the Form and when the OK button is selected both the JOptionPane and the Form will dispose.

Related

How do I make it so JOptionPane.showMessageDialog can sense multiple strings?

/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String grade = JOptionPane.showInputDialog(null, "Please Specify Your Grade");
String First_name = JOptionPane.showInputDialog(null, "What is your First Name?");
String Last_name = JOptionPane.showInputDialog(null, "What is your Last Name?");
]JOptionPane.showMessageDialog (null,"You are a " + grade, "Your Name is " + First_name, "Your Last Name is " + Last_name);
}
How do I get the part where it says "Your Last Name is " + Last_Name to print the correct string? in my code it says that the string cannot be converted to an integer but the rest of that line works fine (using Netbeans IDE)
You are trying to pass multiple messages as separate parameters to the method JOptionPane.showMessageDialog, however the method only accepts a single message parameter. However, this parameter is not limited to just Strings; you can actually pass any Object as the message. See the JOptionPane javadocs for details on how JOptionPane handles various types of message parameters.
I think there are a couple approaches that could be used. One approach is to create a String that concatenates all of the results together. My suggestion would be to use a newline character (\n) to concatenate the results, so they appear one per line. Here is an example:
String message = "You are a " + grade + "\n"
+ "Your Name is " + First_name + "\n"
+ "Your Last Name is " + Last_name;
JOptionPane.showMessageDialog (null, message);
Another approach is to create an array out of the results, and pass the array as the message parameter:
String[] message = {
"You are a " + grade,
"Your Name is " + First_name,
"Your Last Name is " + Last_name
};
JOptionPane.showMessageDialog (null, message);
works also in the constructor :
JOptionPane.showMessageDialog(null, "You are a " + grade+ "\nYour Name is " + First_name+
"\nYour Last Name is " + Last_name);
and probably delete ] in your last line of code
JOptionPane has 3 showMessageDialog() methods, each with different arguments, let's look at each of them, but first we're going to use the following String:
String message = "You are a " + grade + " Your Name is " + First_name " Your Last Name is " + Last_name;
showMessageDialog(Component parentComponent, Object message) this method recieves the parentComponent (it shouldn't be null, instead pass the reference to your JFrame because otherwise you won't be blocking the parent component, so it won't be a modal Dialog) and the message, in your case it would be the String containing the name, last name, etc, you could use it this way:
JOptionPane.showMessageDialog(frame, message);
showMessageDialog(Component parentComponent, Object message, String title, int messageType) this method allows you to modify the icon (or the message type (A list of the full message types can be found on the docs) and the title of the dialog and you can use it as:
JOptionPane.showMessageDialog(frame, message, "My title", JOptionPane.QUESTION_MESSAGE);
showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon) this allows you to use a custom icon and you can use it this way:
JOptionPane.showMessageDialog(frame, message, "My title2", JOptionPane.ERROR_MESSAGE, icon);
For more information you can check How to use Dialogs
Now, if you want to improve the format you can either use html tags as:
String message = "<html>" + name + "<br/>" + lastname + "<br/>" + grade + "</html>";
Or create your own custom JPanel where you add your components to it and then add that JPanel to the showMessageDialog on the Object message argument, but I'm leaving that part to you
This code will create the above output images, however you need to change the image path to your own path, the custom icon has been taken from here
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class DialogExamples {
private JFrame frame;
private ImageIcon icon = new ImageIcon("/home/jesus/Pictures/L5DGx.png");
public static void main (String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new DialogExamples().createAndShowGui();
}
});
}
public DialogExamples() {
System.out.println(icon);
}
public void createAndShowGui() {
frame = new JFrame("Example");
String name = "Your name is Frakcool";
String grade = "Your grade is 5";
String lastname = "Your lastname is YajiSuzu";
String message = "<html>" + name + "<br/>" + lastname + "<br/>" + grade + "</html>";
// String message = name + " " + lastname + " " + grade;
JOptionPane.showMessageDialog(frame, message);
JOptionPane.showMessageDialog(frame, message, "My title", JOptionPane.QUESTION_MESSAGE);
JOptionPane.showMessageDialog(frame, message, "My title2", JOptionPane.ERROR_MESSAGE, icon);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
In your case you're getting the exception:
String cannot be converted to an int
because you're sending 4 parameters here:
JOptionPane.showMessageDialog (null,"You are a " + grade, "Your Name is " + First_name, "Your Last Name is " + Last_name);
In this case, you're using the 2nd method I showed you above, so it's expecting to receive an int messageType on the 4th parameter, not a String.
This isn't something as a console.log() in JS, here you concatenate Strings with + operator, not with a , (comma).
NOTE:
As an aside note, your variable and method names should start with lowerCamelCase while your classes should start with UpperDromedaryCase as stated on the Java naming conventions
NOTE2:
You're not placing your program on the EDT which could cause you problems in the future, so be careful, my above code already solved that problem

Java Error, Incompatible types: Object cannot be converted to string

I almost finished creating this simple code, but I keep getting an error when making my input dialog box from JOptionPane and giving it a variable.
For instance:
name = JOptionPane.showInputDialog(null, "What is your name?",
"Question",
JOptionPane.QUESTION_MESSAGE,
iconhello,
null,
"");
When the name is in front, I get the error, when it is not there are no errors and my code runs smoothly, but I need to return the input into a message dialog which I create later in my code.
This is the full code:
public static void main(String[] args) {
String name, choice, choice2, choice3, order;
ImageIcon iconhello;//identifying the new icon created
iconhello = new ImageIcon("hello.gif");
ImageIcon iconcat1;
iconcat1 = new ImageIcon("cat1.gif");
ImageIcon iconcat7;
iconcat7 = new ImageIcon("cat7.gif");
ImageIcon icondrink;
icondrink = new ImageIcon("drink.gif");
ImageIcon iconpizza;
iconpizza = new ImageIcon("pizza.gif");
name = JOptionPane.showInputDialog(null, "What is your name?",
"Question",
JOptionPane.QUESTION_MESSAGE,
iconhello,
null,
"");
Object[] possibilities= {"Chicken Sub", "Chicken Teriyaki Sub", "Tuna "
+ "Sub", "Vegetable Sub"};//creating options for user to choose from
choice= (String)JOptionPane.showInputDialog(null, "What type of"
+ " subsandwich do you like? \n \"I like...\"",
"Subsandwich",
JOptionPane.QUESTION_MESSAGE,
iconpizza,
possibilities,
"Chicken Sub");
Object[] possibilities1= {"Sprite", "Coke", "7Up", "Pepsi"};
choice2= (String)JOptionPane.showInputDialog(null, "What type of"
+ " drink do you prefer to have? \n \"I prefer..\"",
"Drink",
JOptionPane.QUESTION_MESSAGE,
icondrink,
possibilities1,
"Sprite");
JOptionPane.showInputDialog(null, "Please state what you would like"
+ " to have additionally",
"Additional Request",
JOptionPane.INFORMATION_MESSAGE,
iconcat1,
null,
"");
order= String.format("Your order: \n " + choice + " \n" + choice2 +
" \n Please enjoy!",
"Order for: " + name + " " ,
JOptionPane.PLAIN_MESSAGE,
iconcat7,
null);
JOptionPane.showMessageDialog(null, order);
}
Please, help me if you can.
The showInputDialog method that you're calling returns an Object, but you're assigning the returned value to a String variable. The error message is telling you that Java won't implicitly make this conversion for you, you have to do it explicitly. You've got it right a few lines later in your code.
choice = (String)JOptionPane.showInputDialog(null, "What type of"
+ " subsandwich do you like? \n \"I like...\"",
"Subsandwich",
JOptionPane.QUESTION_MESSAGE,
iconpizza,
possibilities,
"Chicken Sub");

Confused by multiple indented if statements in Java

So I made this really hard to follow method a while ago and I came back to add in another indented if statement to check against an array list of Users using a for loop.
Before I added this in, the method worked fine but now I am getting an error on the last 'else' keyword. It says "syntax error. please delete this token".
I have no errors when I delete the last else keyword but I'm not sure why when they are four if keywords - should there not be a fourth else keyword?
Thanks for any help given.
//method to validate input by user to log in
public void validateInput() {
//presence check on username
if (qi.getEnteredName().length() > 0) {
//compare entered username to stored user accounts
for(int i = 0; i < users.size(); i++) {
if (qi.getEnteredName().equalsIgnoreCase(getUserList().get(i).getUsername())) {
//presence check on password
if (qi.getEnteredPass().length > 0) {
//ensures password is at least 6 char long
if(qi.getEnteredPass().length > 5) {
qi.getMainCards().next(qi.getPanels()); //getPanels() == cardPanel
} else {
JOptionPane.showMessageDialog(null,
"Your password must be at least six characters long.",
"Password Violation", JOptionPane.WARNING_MESSAGE);
}
}else {
JOptionPane.showMessageDialog(null,
"Your did not enter a password.",
"Password Violation", JOptionPane.WARNING_MESSAGE);
}
}
else { JOptionPane.showMessageDialog(null,
"You are not registered.",
"User Violation", JOptionPane.WARNING_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null,
"You did not enter a username. Please try again.",
"Username Violation", JOptionPane.WARNING_MESSAGE);
}
}
}
}
Well, basically your last two else statements are matching up with the same if statement which is probably not what you want. You'd have to move the second else statement outside of another }. You have this:
else { JOptionPane.showMessageDialog(null,
"You are not registered.",
"User Violation", JOptionPane.WARNING_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null,
"You did not enter a username. Please try again.",
"Username Violation", JOptionPane.WARNING_MESSAGE);
}
}
But you really want this:
else { JOptionPane.showMessageDialog(null,
"You are not registered.",
"User Violation", JOptionPane.WARNING_MESSAGE);
}
}else {
JOptionPane.showMessageDialog(null,
"You did not enter a username. Please try again.",
"Username Violation", JOptionPane.WARNING_MESSAGE);
}
This is why it's very important to format your code correctly and neatly with proper indentation. In Eclipse (if you're using that) you can select everything and hit ctrl + i (I think) or cmnd + i depending on whether you're using a PC or a mac, and it will properly format your indentation.
That being said, it's probably a lot easier to do if, else if, and else statements than what you're doing here.
You have two else statements.
On the top level you have if, else and another else.
It should be if, else if, and the ultimate condition would be else. If you are dealing with many if statements, every next if should be else if, because else means "if everything else is not true".
You missed the right place in your if statement, as already mentioned by other answers. To prevent such annoying errors I would recommend to organize the code in more readable manner. For your case it could be something similar to (if I got the logic correctly):
public void validateInput() {
final String name = qi.getEnteredName();
final String password = qi.getEnteredPass();
if (empty(name)) {
showWarn("Username Violation", "You did not enter a username. Please try again.");
} else if (!registered(name)) {
showWarn("Username Violation", "You are not registered.");
} else if (empty(password)) {
showWarn("Password Violation", "Your did not enter a password.");
} else if (password.length < 6) {
showWarn("Password Violation", "Your password must be at least six characters long.");
} else {
// we are good
qi.getMainCards().next(qi.getPanels());
}
}
private boolean registered(String name) {
for(int i = 0; i < users.size(); i++) {
if (name.equalsIgnoreCase(getUserList().get(i).getUsername())) {
return true;
}
}
return false;
}
private void showWarn(String title, String message) {
JOptionPane.showMessageDialog(null,
message,
title, JOptionPane.WARNING_MESSAGE);
}
private boolean empty(String string) {
return string != null && !string.isEmpty();
}

Counter Occurrences of User Specified String in a Text File

Count keeps coming up zero. I'm just trying to read the text file and look for the word, and display the count back to the user.
I'm not sure where it's falling apart. The If statement I think, but not sure where the syntax is going wrong. Thanks for any help!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import javax.swing.*;
public class TextSearchFromFile
{
public static void main(String[] args) throws FileNotFoundException
{
boolean run = true;
int count = 0;
//greet user
JOptionPane.showMessageDialog(null,
"Hello, today you will be searching through a text file on the harddrive. \n"
+ "The Text File is a 300 page fantasy manuscript written by: Adam\n"
+ "This exercise was intended to have the user enter the file, but since \n"
+ "you, the user, don't know which file the text to search is that is a \n"
+ "bit difficult.\n\n"
+ "On the next window you will be prompted to enter a string of characters.\n"
+ "Feel free to enter that string and see if it is somewhere in 300 pages\n"
+ "and 102,133 words. Have fun.",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
while (run)
{
try
{
//open the file
Scanner scanner = new Scanner(new File("An Everthrone Tale 1.txt"));
//prompt user for word
CharSequence findWord = JOptionPane.showInputDialog(null,
"Enter the word to search for:",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
count = 0;
while (scanner.hasNext())
{
if ((scanner.next()).contains(findWord))
{
count++;
}
} //end search loop
//output results to user
JOptionPane.showMessageDialog(null,
"The results of your search are as follows: \n"
+ "Your String: " + findWord + "\n"
+ "Was found: " + count + " times.\n"
+ "Within the file: An Ever Throne Tale 1.txt",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
} //end try
catch (NullPointerException e)
{
JOptionPane.showMessageDialog(null,
"Thank you for using the Text Search.",
"Text Search",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
} //end run loop
} // end main
} // end class
EDIT:
Need help again. The instructor changed the parameters of the project and now I need to find word fragments like "th" or "en" and count those as well.
This I feel is beyond what he has taught and I have no idea how to make that work. I've googled until I can't google anymore.
You have to provide a File Object to Scanner in order to read the file, currently everything is getting searched in a String "An Everthrone Tale 1.txt"
Scanner scanner = new Scanner(new File("An Everthrone Tale 1.txt"));
And for searching a word, you need to do like this:
while (scanner.hasNext())
{
if (findWord.equals(scanner.next()))
{
count++;
}
}
and if you want to perform case-insensitive search then use String#equalsIgnoreCase instead of String#equals
Hope this helps

Cancel button in showinputdialogbox

I have a few buttons on my panel and everytime I click on it an input dialog box appears. It has an inbuilt cancel button. Now, when i click on the cancel button in the beginning of the code without entering the quantity in the dialog box, it says, "This is an invalid" number. This line has to only appear if the user enters alphabets or symbols, and not on pressing cancel. Can we solve this?
First you need a way to decide if a String represents a number; the method below uses Double.valueOf() to decide.
private Double valueOf(String s) {
try {
return Double.valueOf(s);
} catch (NumberFormatException e) {
return null;
}
}
Here's an example of how you might use the method:
private void display() {
String input = JOptionPane.showInputDialog(
null, "Enter a number?", "Number", JOptionPane.QUESTION_MESSAGE);
Double value = valueOf(input);
JOptionPane.showMessageDialog(null, "The value " + input
+ " is " + (value != null ? "valid" : "invalid") + ".");
}
See also How to Make Dialogs.
Try doing,
String Input = JOptionPane.showInputDialog(null,"Enter the number?",
"Number", JOptionPane.QUESTION_MESSAGE);
if (Input.equals(""))
{
JOptionPane.showMessageDialog(null,"This is an invalid number");
}
The following link explains it even better: Simple Data Validation.
String Input = JOptionPane.showInputDialog(null,"Enter the number?",
"Number", JOptionPane.QUESTION_MESSAGE);
if
(Input.matches(("((-|\+)?[0-9]+(\.[0-9]+)?)+"))) {
JOptionPane.showMessageDialog(null,"valid number");
}
else{
JOptionPane.showMessageDialog(null,"This is an invalid number");
}

Categories