console output on gui - java

I have problem with console output. I did search for one day now and i still can't fix the problem. I have tried adding text on JTextArea manually and it works, so gui should be fine. IF i change code to System.out.println(s), it will writte in console successfully. Here is my code:
public static void runSystemCommand(String command) {
String message=null;
int i=0;
while (i<1){
try {
gui area=new gui();
// ArrayList<String> sList = new ArrayList<String>();
areaField=new JTextArea();
sarray = new String [500];
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
area.jTextArea.append(s+ "\n"); //this doesnt work..
}
Thread.sleep(9000);
} catch (Exception e) {
e.printStackTrace();
}
i++;
}

In your code you have an empty string String s = ""; try to assign some string to s like this:
String s = "some value";
area.jTextArea.append(s+ "\n");

You are appending to the wrong JTextArea.
In your pingmain class you create a new instance of gui which is never shown to the user. In this invisible instance you correctly add the text to the textarea.
If you instead add a gui area parameter to your runSystemCommand method and give this as second arguemnt to the method call in gui, you will see your output in your textarea.

Related

Trying to read multiple lines of cmd input

I'm trying to write a method that:
Prints out a message (Something like: "Paste your input: ")
Waits that the user presses enter.
Reads all the lines, that got pasted and adds them up in one String.
(An empty line can be used to determine the end of the input.)
The first syso does the printing part and also the first line gets read correctly, but then it never exits the while loop. Why? There has to be an end?
public static String readInput(String msg) {
System.out.print(msg);
String res = "";
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
String line;
while ((line = buffer.readLine()) != null && !line.isBlank())
res += "\n" + line;
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
Ive already seen the following sites, but they all didn't help:
How to read input with multiple lines in Java
https://www.techiedelight.com/read-multi-line-input-console-java/
Make the console wait for a user input to close
Edit:
The same bug applies for:
public static String readInput(String msg) {
System.out.print(msg);
String res = "";
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
res = buffer.lines().reduce("", (r, l) -> r + "\n" + l);
System.out.println(res);
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
Edit 2:
I've tried this code in my actual project and in a new test-project, but with different results. Here is a video of that test.
Why wouldn't use this statement?
while (!(line = buffer.readLine()).isEmpty())
In this case sending empty line will exit the loop.
Although, if you insert large text with empty lines (for example, the beginning of a new paragraph, or a space between them) will terminate the program.

Java - List<String> printing \n instead of showing a line break

I have a .txt file reader, which reads individuals lines of a file and stores them in a List<String> which I then display on a JTextArea. Some of the lines contain \n, because I wanted specific breaking when displaying. However, when I do display the code, the \nare shown instead of breaking the line as they usually do.
I tried replacing the \n's with linebreaks by placing the code str.replaceAll( "\\\\n", System.lineSeperator()); in the while loop, before list.add(str); but it doesn't seem to have any effect.
To reiterate, I simply need a way to change the \n's to linebreaks. Any help would be much appreciated.
The code for the .txt reader is below.
static void parseStringArray(final String filePath, List<String> list){
try {
InputStream input = Text.class.getResourceAsStream(filePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String str;
while((str = reader.readLine()) != null){
list.add(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
**Edit - I have updated the post to include a bit more code.
The List I send in as an argument is initialized before the method. It is
protected static List<String> textfiles = new ArrayList<String>();
An example of a line from the .txt file is
Welcome!\n\n If you wish to proceed, please type the password below.\nEnjoy your stay!
The code to display this text is below. (Pardon formatting)
Timer teletypeTimer = null;
public static void animateTeletype(final JTextArea displayArea)
{
final String[] s = new String[1];
s[0] = "";
final int[] i = new int[2];
i[0] = 0;
i[1] = 0;
teletypeTimer = new Timer(20, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(i[0]==0)
displayArea.setText("");
s[0] = TTqueue[i[1]].substring(i[0], i[0]+1);
i[0]++;
displayArea.append(s[0]);
if(displayArea.getText().equals(TTqueue[i[1]]))
{
i[1]++;
if(TTqueue[i[1]] !=null)
{
teletypeTimer.stop();
i[0] = 0;
timerRestart(5000, teletypeTimer);
}
else
{
Arrays.fill(TTqueue, null);
complete=true;
teletypeTimer.stop();
}
}
}
});
teletypeTimer.start();
}
(Posted on behalf of the OP).
I switched replaceAll() with replace() and worked with Pshemo and Nick Vanderhoven's points. I added the line of code str = str.replace("\\n", System.lineSeparator()); as suggested by Pshemo, and that's done the trick. Cheers!

Easiest way to show text in gui?

I've seen many posts about it, but it looks complicated. Here is my code, what would be the easiest way to display information on gui textArea?
public static void runSystemCommand(String command) {
String message=null;
int i=0;
while (i<1) {
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
//here i dont know what to type..please help
}
Thread.sleep(9000);
} catch (Exception e) {
e.printStackTrace();
}
i++;
}
}
Easiest way would be
textAreaName.setText(/*What ever you want to display here*/);
In your case it would be the following if you wanted to just set the text to s:
textArea.setText(s + "\n");
If you wanted to update the text along with the existing text you would use:
textArea.append(s + "\n");

How to use JFrame to output file content in system console output?

I am using JFrame Java Swing for a piece of code shown below:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String filename = (jTextField1.getText());
if (filename.endsWith(".log")) {
Scanner inFile1 = new Scanner(filename).useDelimiter(";");
List<String> temps = new ArrayList<String>();
// while loop
while (inFile1.hasNext()) {
// find next line
String token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
for (String s : tempsArray) {
System.out.println(s);
}
This code works but it only displays the file name as the file name itself (e.g. If my file name = lalala.txt, the output in console would be lalala.txt) I have tried this code but it does not display the contents inside the file. How do I go about displaying the contents in the file while using JFrame as my GUI in my console output? My GUI consist of a text field which will display the file name and when I click the jButton2, I want the button to show the the content of the file instead of the file name by itself. It runs perfectly fine but it is not what I want for my output.
You are using:
new Scanner(filename).useDelimiter(";");
Which in turn is reading the data from the string filename. Instead use:
new Scanner(new File(filename)).useDelimiter(";");
Simply use:
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(new File("absolute path to your text file...")),"UTF8"));
String buf;
while ((buf = in.readLine()) != null)
{
System.out.println(buf);
}
in.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

Redirecting System.out.println to an AWT Component on button press

I have the following code and want to print the System.out.println(result); to my frame but I don't know how. I tried txtField.setText(result) however this did not work.
I just want to display System.out.println(result); to that Form
Public static void main(String...args) throws IOException {
String line = null;
Pattern category = Pattern.compile("^\\[(.*?)\\]$"); // matches [Cars]
Pattern itemAndQuantity = Pattern.compile("^(\\w+)=(\\d+)$"); // matches Lamborghini=6
StringBuilder result = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader("D:/test.txt"))) {
while ((line = br.readLine()) != null) {
Matcher categoryMatcher = category.matcher(line);
Matcher itemMatcher = itemAndQuantity.matcher(line);
if (categoryMatcher.matches()) {
if (result.length() > 0) { // found new category, put on new line
result.append(System.getProperty("line.separator"));
}
String categoryName = categoryMatcher.group(1); // Cars
result.append(categoryName).append(": "); // Cars:
} else if (itemMatcher.matches()) {
String item = itemMatcher.group(1); // Lamborghini
String quantity = itemMatcher.group(2); // 6
result.append(item).append(" ") // Lamborghini
.append(quantity) // Lamborghini 6
.append(", "); // Lamborghini 6,
}
}
// we are done processing the file, output the result
System.out.println(result);
}
Based on the information you've given to us so far, there are several things wrong:
Public static void main(String...args) throws IOException {
The P here should be lowercase. Also you should wrap code that may throw an IOException in a try-catch statement instead of using throws IOException; it's good coding practice to do so, since an IOException that may occur will be left unhandled...
try (BufferedReader br = new BufferedReader(new FileReader("D:/test.txt"))) {
You're missing your catch statement at the end of the try...
txtField.settext(result)
It shoud be txtField.setText(result.toString()). Note that the T is capitalized and toString() returns the String stored in the StringBuilder.
EDIT EDIT:
The below answer was written when I was inexperienced and is only left for context. Disregard it and consider only the information provided in this edit edit.
What you have is a StringBuilder object with the text you want container within it. When you do System.out.println(result) it most likely calls the StringBuilder#toString method on result which extracts this text from the StringBuilder. Calling txtField.setText() most likely does not do this implicit conversion which is why it doesn't appear to work.
What you want to do is call txtField.setText(result.toString()) to get the text contained in the StringBuilder and set the text field's text to that.
See:
StringBuilder
Using Swing Components
EDIT:
Replace the System.out.println with the following:
JFrame frame = new JFrame();
JTextField text;
text = new JTextField(result.toString());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(text, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
Firstly, I cannot tell if you've imported all necessary packages, if you haven't that is most likely your first error.
public static void main(String...args)
not
public static void main(String...args)
Also, I'd recommend adding the following code after your try whenever you create a try statement:
catch(Exception e){
System.out.println("An exception occurred");
}
You can add anything instead of System.out.println("An exception occurred") but that's the simplest I can think of to notify you that an error occurred.

Categories

Resources