How would I initialize a string in Jframe? - java

I'm fairly new to programming, and I can't seem to figure out how to initialize a String on JFrame Form. I do not know what code to put in to initialize the String if the contents of the string is entered later, by the user. This basically means that the String (stringone) is currently a blank text field on my form. The user enters a sentence or string and the label (one) tells how many characters are in the string they just entered. Here is my code so far:
{String stringone = new String ();
int one;
one = Integer.parseInt(txtstringone.getText());
one = (stringone.length());
lblone.setText(String.valueOf(one));}
Currently there is a yellow line under the third line of code, saying it may not have been initialized. It also does not work when I run it. Hope this clears it up!
Thanks so much in advance!

Try this:
String stringone;
Remove new String()
If you want to initialize it, tou must pass it a String value. For example:
String stringone = "value";
The string's length (stringone.length()), will be 5.
So, in order to take the length of a String you must first initialize it. Otherwise, it will be null, and null does not have length.

The user enters a sentence or string and the label (one) tells how many characters are in the string they just entered.
What you need to do is add an event handler for when the user has entered the string. There is no "user entered string" before the user has given the string.
An event handler is code that runs when some "event" occurs. A user writing in a field is a possible event.
Here's how you can add an event listener on your txtstringone text field component. It will be triggered when the user presses the Enter key.
txtstringone = new JTextField();
txtstringone.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
String text = txtstringone.getText();
int one = text.length();
lblone.setText(String.valueOf(one));
}
});
You can find a longer tutorial at https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html and a short working program at https://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextDemoProject/src/components/TextDemo.java

Related

How do you check if a text field in a GUI contains something?

I'm trying to check if a user's input into a text field contains certain letters and have it increment a counter if it does.
//this is the code for the button
//tfYourName is the name of the text field
//below is what I've tried already
private void btnResultsMouseClicked(java.awt.event.MouseEvent evt) {
if (tfYourName.getSelectedItems.toString.toUpperCase().contains("T"))
}
if (tfYourName.getText().toUpperCase().contains("T"))
counter++;

Making input.getText take my next input rather than my last one

I've got a window (like a command prompt) and when I type "calculate", it's supposed to begin the calculator process. When I type "calculator", it says "calculator activated" and "please input your first value".
The problem is, when I type this value, I don't know how to make it use it. Instead, it's taking the text from when I said "calculate" before.
Any ideas of how I can get it to take the number, rather than the word "calculate"?
public void calculate(){
try{
print("calculator activated" + "\n" + "please input your first value" + "\n", false, new Color(210, 190, 13));
String words = input.getText();
//trying to get it to take the number I input
print (words +"\n", false, new Color(210, 190, 13));
//this print is to test what text it's saving as the 'words' variable
//all it prints is the word 'calculate'
}
catch (Exception ex){}
}
You're printing the invitation to type a number and reading the content of the input immediately after. So yes, the input at that time still contains "calculate". Printing an invitation, or calling getText() on a text field, don't block until the user erases the text and replaces by something else. It just returns the current text in the field.
GUI applications don't work like console applications. They are event based. Your calculate method should not do anything other that printing the invitation. You should have an ActionListener on the text field or on a button, so that, when the user types enter in the text field or presses the button, the listener is called, and gets the text from the text field.
Read the tutorial about events.

Converting from String to Int

I'm trying to validate my program by entering a value through a JTextField on a JDialog and if it's less than a value..., else do ... I keep running into a problem on the line:
int intDiagInput = Integer.parseInt(dialogInput)
JOptionPane.showInputDialog(dialogPaneInput, "Age verification required, please enter year of birth: yyyy");
dialogInput = dialogPaneInput.getText(); //get info from JTextField and put in string
int intDiagInput = Integer.parseInt(dialogInput); //convert string to int
Any help would be greatly appreciated.
Your code is wrong in two ways:
The first paramenter you pass to showInputDialog is used as the parent, just for layout purposes, it has nothing to do with the actual content of the input dialog. Therefore your second error is getting the text from the displayed dialog.
To get the text the users enters you need to write something like:
String dialogInput = JOptionPane.showInputDialog(dialogPaneInput, "Age verification required, please enter year of birth: yyyy");
int intDiagInput = Integer.parseInt(dialogInput ); //convert string to int
What you are doing is getting the text of some magical object dialogPaneInput, which probably is just an empty string.
Additionally you should check that the user inputs a valid number, not in terms of a number that you would accept but in terms of it actually beeing a number, otherwise you will run into the already existent NumberFormatException - or wrap the parsing in a try...catch-block.
try {
int intDiagInput = Integer.parseInt(dialogInput );
} catch (NumberFormatException nfex) {
System.err.println("error while trying to convert input to int.");
}
The exception you posted on the comment section (java.lang.NumberFormatException: For input string: "") means that you're trying to convert an empty String to int.
Change your code to verify if dialogInput is not empty before converting it to int.

Why is this JTextField not showing the contents?

I am trying to make a cheat code button for my game, and the displaying of it is all fine but I cannot correctly get the contents of this text field. This is the code for it:
cheats.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
Class.console("DISPLAYED OPTIONPANE");
JOptionPane.showInputDialog(cheatCode, "Enter Code Here");
Class.console("GOT STRING" + cheatCode.getText());
if(cheatCode.getText().equals("testin")) {
Class.console("testout");
}
}
I'm pretty much a beginner at this, so help? I can post everything else if needed.
P.S. Class.console() is a thing in my driver class. It's basically a shortened version of System.out.println()
The showInputDialog() method returns the value that was entered by the user. You should capture it into a variable. For example, do this:
String userInputString = JOptionPane.showInputDialog("Enter Code Here");
The variable userInputString will be a string containing the value that you're looking for.

Is there a way to use the methods of a string created JOptionPane? (Java)

I've googled the holy bejaysus out of it and just can't find the right combination of words. How do I use methods on something with no identifier? For instance;
String inputBio = JOptionPane.showInputDialog(null, heroPane, "Please enter details...", JOptionPane.OK_CANCEL_OPTION);
How do I refer to that dialog?
So you want to assign the value typed into the input box to the String? You need to create an Integer and assign it to the JOptionPane.showInputDialog, then use the constructor to instantiate a new instance of the Input Dialog with the options you want.
Now, to extract the data, add an IF statement and go through the possible options presented to the user. If you added JoptionPane.OK_CANCEL_OPTION then you have two options: OK and CANCEL.
The IF statement should be: If the user selected OK, extract the string, ELSE do whatever you want to do.
The string should be extracted from the textfield that was created (which I assume is somewhere in the 'heroPane')
Here's how that would look in code
//the string we use for input
String inputBio;
int optionBox = JOptionPane.showInputDialog(null, heroPane, "Please enter details...", JOptionPane.OK_CANCEL_OPTION);
//now the integer value represents the option selected (OK or CANCEL)
//All we need to do is extract the data and assign it to the string
if (optionBox == JOptionPane.OK_OPTION) {
//the OK option
inputBio = nameOfYourTextField.getText();
} else {
// we have a CANCEL option
}
You could, of course, do it without an IF statement, but make sure you handle all of the options accordingly
If you need a reference to the JOptionPane, you cannot use the showInputDialog convenience methods. You will need to construct a JOptionPane object.

Categories