I have assigment to make notepad using NetBeans Java. I already made the whole thing, I just don't know how to implement find/replace dialog, can you help me with this. I'm using jTextArea.
I will assume that you already know about Swing and how to make the appropriate dialog box (since you apparently have already made the JTextArea for the Notepad equivalent), and that you just want to know how to make it work on the back end.
What I would do is have a Scanner object go through your file to perform the find and replace.
String myAlteredText = "";
Scanner scanner = new Scanner(myText);
while(scanner.hasNext()) {
String next = scanner.next();
if(next.equals(userFindInput)) {
myAlteredText += userReplaceInput;
}
else {
myAlteredText += next;
}
myAlteredText += " ";
}
You can use .equalsIgnoreCase() if case doesn't matter. Likewise, you can tweak to adjust to your user parameters (i.e., if it doesn't have to match the whole word, use .contains() instead). There may be some nit-picky other things you need to do to maintain abnormal spacing and line breaks, but this is the general approach I would use.
You could use a JTable although this is rather unconventional. You could load each word into a new cell. This way when you need to replace 1 word you don't need to update the entire jtextarea for just 1 character unless I am mistaken. This would require a lot of work however in order to get this to work
Related
What I need have happen: Take a list of names from a multiline TextArea, put them into an array, modify them a bit, and then print them out in a list.
What I'm having problems with: Actually getting the input from the TextArea and sticking it in an array -- I have the rest down. I read someone's similar question, but the solution for that question isn't working for me; I keep getting a NullPointerException when I reference it, meaning that there's nothing there, and that the input wasn't put into the array.
The coding: The TextArea is called "taClient" and is all activated by a mouse click on a button called "btnProcess"
private void btnProcessMouseClicked(java.awt.event.MouseEvent evt)
{
String[] names = taClient.getText().split("\\n");
Account[] account = new Account[names.length];
for(int x = 0; x<names.length; x++)
{
account[x].Name = names[x];
}
//All the modifications and other code and printout.
}
As far as I'm aware, this should work, but I don't have much experience with textareas or the String.split() method, so I could just be way off. (Plus, as I said before, this design was based off of someone else's question on here, and they said this answer solved their problem...but not mine.)
Thanks in advance!
Did you try to split the string with just one backslash, likes this: .split("\n").
You are probably on Windows and want to read Split Java String by New Line
Also using Guava's new LineReader(new StringReader(taClient.getText())) can do the trick (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/LineReader.html)
My intentions are to show a letter and have the user type the letter, while after they have hit the corresponding key (whether it's right or wrong) it is to then display the next key. I can only make this happen, at the moment, after pressing the key and then pressing the enter key following so that it finishes the scanner.next() method. Any way that I could automate the enter key so that I could make it scan in the character letter and then automatically continue to the next randomly generated character? Let me know if there needs to be clarification on this.
//some initialized code here
for(int i = 0; i < 5; i++)
{
int letterToDisplay = rand.nextInt(26)
System.out.printf("%s\r\n", letters[letterToDispaly]);
**String inputLetter = scanner.next();**
if(intputLetter.exquals(letters[letterToDisplay]))
{
letterCounter(letterToDisplay);
}
}
//some methods etc. here
Thanks,
Kyle P.
There is no portable way to read user input from a console character-by-character using the standard API; for example the Unix terminal is by default line-buffered which means that the OS does not transfer characters into the application's buffer until the user hits enter. You can't do it even from standard C.
You need to run code specific to the OS and terminal to achieve this, ideally wrapped in a library, like the ones discussed here: What's a good Java, curses-like, library for terminal applications?
A better option is using a graphical user interface. It's not the 1970s anymore ;)
Is there a way to dynamically change output in Java? For instance, in a terminal window if I have:
System.out.print("H")
and then I have:
System.out.print("I")
The output will be:
HI
Is there a way to assign a position to outputs that allows you to replace characters dynamically? For instance (and I know this would not output what I want, I merely want to demonstrate my thinking) this:
System.out.print("H")
Thread.sleep("1")
System.out.print("I")
And it would first print out
H
and then after a second, replace the H with an I?
I'm sure this sounds stupid, I am just interested in dynamically changing content without GUIs. Can someone point me in the direction for this technique? Thank you very much in advance.
You might want to take a look at
System.out.printf
Look at the example shown here: http://masterex.github.com/archive/2011/10/23/java-cli-progress-bar.html
edit:
printf displays formatted strings, which means you can adapt that format and change it for your needs.
for example you could do something like:
String[] planets = {"Mars", "Earth", "Jupiter"};
String format = "\r%s says Hello";
for(String planet : planets) {
System.out.printf(format, planet);
try {
Thread.sleep(1000);
}catch(Exception e) {
//... oh dear
}
}
Using the formatted string syntax found here: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
As the comment says this solution is only limited to a singular line however dependent on your needs this might be enough.
If you require a solution for the whole screen then a possible solution would be (although quite dirty) would be to hook the operating system using JNA and get a handle on the console window, find its height and then loop println() to "clear" the window then redraw your output.
If you would like to read more then I can answer more questions or here is a link: https://github.com/twall/jna
You can use \b to backspace and erase the previous character.
$ cat T.java
import java.lang.Thread;
public class T {
public static void main(String... args) throws Exception {
System.out.print("H");
System.out.flush();
Thread.sleep(1000);
System.out.print("\bI\n");
System.out.flush();
}
}
$ javac T.java && java T
I
It will output H, then replace it with I after one second.
Sadly, it doesn't work in Eclipse console, but in normal console it does.
This is what you need (uses carriage return '\r' to overwrite the previous output):
System.out.print("H");
Thread.sleep(1000);
System.out.print("\rI");
The C library that is usually used to do this sort of thing is called curses. (Also used from scripting languages that rely on bindings to C libraries, like Python.) You can use a Java binding to it, like JCurses. Google also tells me a pure-Java equivalent is available, called lanterna.
Total Java noob, I need to figure out how to capture string entered as an argument for one method in order to reuse it later.
Basically, here I pass String content as a label when creating buttons:
public void start() {
// set up the label for one button
viewer.setButtonLabel(1, "");
viewer.setButtonLabel(2, "");
viewer.setButtonLabel(3, "");
// start the viewer
viewer.open();
}
Then I want to reuse the string I've given as the button label as the keywords for a search in the next method, taking into account which button was pressed:
public void buttonPressed(int n) {
// fetch an image of the Forum from Flickr
Photo photo = finder.find("", 5);
}
I feel I'm making this much harder than it has to be but I'm totally new to Java and can't seem to find what I'm looking for.
Would really appreciate any tips you may have.
String buttonLabel1 = "Blah blah blah";
viewer.setButtonLabel(1, buttonLabel1);
Next Method
blahMethod(buttonLabel1);
This is one way of doing this, but probably the easiest to see. You can get a bit more complicated by storing all your button labels into a list instead (which will make your code look cleaner), but since you are new, I suggest you try it this way. Eventually, to make your code dynamic (ex. If I select the 4th button, get the 4th label), you will have to use some sort of data structure to avoid from getting extremely sloppy/messy.
You also can probably "get" the label of the button in order to retrieve the same string value.
Using either JLine (or JLine2), is it possible to issue a call to readline on a ConsoleReader and have, in addition to the standard prompt, the buffer be pre-filled with a string of my choosing?
I have tried to do, e.g.:
reader.getCursorBuffer().write("Default");
reader.readLine("Prompt> ");
This seems to indeed write into the buffer, but the line only displays the prompt. If I press enter, readLine returns "Default" as I would expect. If I clear the screen, the buffer is redrawn and shown correctly.
My understanding is that I should somehow call reader.redrawLine() right after the call to readLine. This last one however is blocking, which makes it hard (not impossible, but it certainly feels wrong to use a second thread for that).
I ran into exactly this use case today.
It's a bit of a hack, but I was able to preload text into the JLine buffer and then let the user edit it by doing this:
String preloadReadLine(ConsoleReader reader, String prompt, String preload)
throws IOException
{
reader.resetPromptLine(prompt, preload, 0);
reader.print("\r");
return reader.readLine(prompt);
}
Yeah, the printing of \r is a hack, but it seems to make the thing work.
I'm using JLine-2.13.
I managed to do that using a thread (yes, it does feel wrong, but I found no other way).
I took inspiration from code found in JLine itself that also uses a thread for similar purposes.
In Scala:
val thr = new Thread() {
override def run() = {
reader.putString("Default")
reader.flush()
// Another way is:
// reader.getCursorBuffer.write("Default") // writes into the buffer without displaying
// out.print("D*f*ult") // here you can choose to display something different
// reader.flush()
}
}
thr.setPriority(Thread.MAX_PRIORITY)
thr.setDaemon(true)
thr.start()
I think you want either resetPromptLine or putStream if you already have the prompt set.
Not to hijack your question but I can't figure out how to simply print a line replacing the prompt (ostensibly or visually pushing the prompt down with a message above it).
Update for JLine3:
This can be accomplished with one of the existing overloads of readLine:
readLine(String prompt, Character mask, String buffer)
For example, reader.readLine("> ", null, "abc") will yield > abc where abc is part of the buffer being edited.