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.
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'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++;
I am making a Java program, but I've run into a problem.
First, let me show you the code:
if (file.exists()){
for (String s : DFileLoader.getMethod(pathToSaveAs)){
if (s.startsWith("playerSendMessage%$%##")){
pSmsgc.setSelected(true);
}else{
pSmsg.setEnabled(false);
}
}
if (DFileLoader.getMethod(pathToSaveAs).size() <= 0){
pSmsg.setEnabled(false);
}
}else{
pSmsg.setEnabled(false);
}
pSmsgc.setFont(fDisp);
pSmsgc.setBounds(new Rectangle(50, 135, 140, 30));
pSmsg.setBounds(new Rectangle(175, 135, 150, 30));
pSmsgc.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (pSmsgc.isSelected()) pSmsg.setEnabled(true);
else pSmsg.setEnabled(false);
}
});
pane.add(pSmsgc);
if (file.exists()){
for (String s : DFileLoader.getMethod(pathToSaveAs)){
if (s.startsWith("playerSendMessage%$%##")){
String[] d = s.split("%$%##");
String text;
if (d.length <= 1) text = "";
else text = d[1];
pSmsg.setText(text);
}
}
}
pane.add(pSmsg);
Here are some things to know about this:
When I use "getMethod(path)", its just returning a String List (List) which includes each line of the TXT file.
pSmsgc is a JCheckBox and pSmsg is a JTextField.
I have it so when the box is not checked, the text field is grayed out, which works fine.
If the file has a line that starts with "playerSendMessage%$%##", the box will be checked, which works.
The thing that isn't working is where it sets the text field's text to the second substring of that line.
For example, the file's line could be "playerSendMessage%$%##Hello!". This would cause the box to be checked, and the field to says "Hello!"
Everything works except for the part where the field says the text.
It might be just a simple thing that I am overlooking, or maybe not. Can anyone please help?
Your file's line name contains the character '$' which means end of a line on RegExp patterns.
So the solution would be to escaping with \\ the character in conflict with RegExp syntax like this:
String[] d = s.split("%\\$%##");
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.
I am working with netbeans on an applet. My problem is that I want to take multiple lines input (possibly from text area) and then output to another (text area).
My code in an application would look something like this. How to use the same concept with an applet?
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i=0;i<size;i++)
{
picks[i]=br.readLine();
picks[i] = picks[i].toUpperCase(); //picks is an array
}
/*
.
Some computations is happening here for picks[]
.
*/
for (int p=0;p<size;p++)
{
System.out.print(picks[p]);
System.out.print("\n"); }
}
I need to take each inputed line on its own and store it in the array and do the same with the output.
Thanks
"I am working with netbeans on an applet. My problem is that I want to take multiple lines input (possibly from text area) and then output to another (text area)."
Ok so you have two JTextAreas. You probably want a button to click to transfer the text. So lets add the actionPerformed code as you would been in Netbeans
Right-click on the button (from design view) and select Events -> Action -> actionPerformed. The following code will be auto-generated:
public void jButton1aActionPerformed(java.awt.event.ActionEvent evt) {
}
Now all you need is a one-liner
public void jButton1aActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea2.setText(jTextArea1.getText());
}
If you really, really want to store the text into an array, then just .split with the nex-line carriage character "\n"
String[] lines = jtextField1.getText().split("\\n");