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.
Related
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
I am trying to replace a word one occurrence at a time. I have been looking through other answers here, but I think what I have coded so far would be much simpler. I want to replace a word that a user selects with another word that the user also selects. I will have two text fields and a button and every time the user clicks the button, we will get the text out of both text fields and replace the word that needs to be replaced in the text area. My issue is that when the replace button is clicked, any other text that is in the text area is deleted and we are left only with the word that is doing the replacing. I know my issue is because I am setting the text of the text area to just that one word, but I do not know how to fix it. Here is my code: Any help is appreciated.
replaceButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String findText = textField.getText();
String replaceText = textField2.getText();
String text = textArea.getText();
text += text.replaceFirst(findText, replaceText);
textArea.setText(replaceText);
}
});
Like you said. You are setting the text in textArea to the text you want to replace. So set the text in textArea to the updated text returned from text.replaceFirst(findText, replaceText). Also you don't need to concatenate the result.
Try this.
replaceButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//the text you want to replace
String findText = textField.getText();
//what you want to replace it with
String replaceText = textField2.getText();
//all the text in the text area
String text = textArea.getText();
//replace first occurrence of "findText" with "replaceText"
//returns the altered string
text = text.replaceFirst(findText, replaceText);
//set text in textArea to newly updated text
textArea.setText(text);
}
});
To make sure I understand you correctly you want something like this.
Original text: I like cats, cats are cool.
find: cats; replace: dogs.
First click output: I like dogs, cats are cool.
Second click output: I like dogs, dogs are cool.
I am running a console application in Netbeans that prompts a user input, validates the input, and prints an error message if the input failed validation and re-prompts. The error message I have set up to print in red text per this answer. It works perfectly, save one issue.
After the program asks for a second input given that the first input was invalid, user inputs following that error message are the same color as the error message.
For example, the user has entered an invalid input. They enter their input again after the error message. It should print in the default text color (black in my version), but it prints as red text instead.
Is there a way in which I am supposed to close out the application of the ANSI color code on my text? An end tag of sorts?
Code:
public static void main(String[] args)
{
//Initialize keyboard input
Scanner keyboard = new Scanner(System.in);
//Print prompt to screen
System.out.println("User input prompt goes here: ");
//Store user input
String inputGot = keyboard.nextLine();
//Print a dummy error message
System.out.println("\u001B[31m" + "This is an error of some sort. "
+ "Please re-enter input: ");
//Rerun input prompt (this would be looped in the real program)
System.out.println("User input prompt goes here: ");
//Store user input
inputGot = keyboard.nextLine();
}
Wherever you want the red text to stop, you need to insert the ANSI escape sequence to set all ANSI attributes off: "\u001b[0m".
See this for other things you might want/need. https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes
I am trying to create a java text area, with it being created with the text
"Chat Here!" being placed inside the textarea. I then want them to type in a word, and press enter. When they press enter, i want to be able to select the text from just that line - (i.e. chatArea.getText() gets all the text, including the "Chat Here!", which is not what I want. As well, I can't say that the text they enter will always be on a specific line (i.e. always the 2nd line); I haven't found a way to access the line the user has put in exclusively yet. Any help would really be appreciated. I'm still new to java, so if examples of code could be given as well, that'd be really helpful. Thanks a lot.
I then want them to type in a word, and press enter. When they press enter, i want to be able to select the text from just that line
You can use the Utilities class to help you out:
int end = textArea.getDocument().getLength();
int start = Utilities.getRowStart(textArea, end);
while (start == end)
{
end--;
start = Utilities.getRowStart(textArea, end);
}
String text = textArea.getText(start, end - start);
System.out.println("(" + text + ")");
The above will return the last line that contains text. The while loop handles empty lines at the end of the text area.
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.