JTextArea Does Not Display File Contents On New Lines - java

I'm having an issue using a JTextArea within a scrollpane. I can read from a textfile, but the contents are all showing up on one line. I have tried various methods using append and trying to break the line, but with no success.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class SplashScreen extends JFrame implements ActionListener
{
JButton mobile;
JButton browser;
JLabel welc;
JPanel home;
File file = new File("C:\\Users\\Jimbob\\Desktop\\DisWorkspace\\TrustWizard\\welcometwo.txt");
BufferedReader reader = null;
int lines = 10;
public String read()
{
String savetext = "";
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while((text = reader.readLine()) != null)
{
savetext += text;
}
}
catch(IOException jim)
{
jim.printStackTrace();
}
return savetext;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource().equals(mobile))
{
MobileHome openB = new MobileHome();
this.dispose();
}
if(e.getSource().equals(browser))
{
BrowserHome openB = new BrowserHome();
this.dispose();
}
}
public SplashScreen()
{
super("Trust Wizard");
JTextArea homeText = new JTextArea(25, 30);
homeText.setText(read());
JScrollPane homeScroll = new JScrollPane(homeText);
welc = new JLabel("Welcome To The Trust Wizard");
home = new JPanel();
mobile = new JButton("Mobile Wizard");
browser = new JButton("Browser Wizard");
home.add(welc);
home.add(homeScroll);
home.add(mobile);
home.add(browser);
ImageIcon img = new ImageIcon("hand.jpg");
setIconImage(img.getImage());
mobile.addActionListener(this);
browser.addActionListener(this);
getContentPane().add(home);
home.repaint();
setSize(450, 530);
setVisible(true);
}
public static void main(String args[])
{
SplashScreen test = new SplashScreen();
}
}

Don't write your own method to load data into a JTextArea.
//homeText.setText(read());
Instead, just use the read() method provided by the JTextArea API:
FileReader reader = new FileReader( your file name here );
BufferedReader br = new BufferedReader(reader);
homeText.read( br, null );
br.close();

Instead of appending just text, try appending text + "\n"
public String read() {
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String text = null;
while((text = reader.readLine()) != null) {
builder.append(text + "\n");
}
} catch(IOException jim) {
jim.printStackTrace();
} finally {
try {
if (reader != null) reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return builder.toString();
}
Also added a finally block to close the BufferedReader (and with it the rest of the stream)

homeText.setLineWrap(true); should do the trick for you.
Put that line right after the where you create the homeText variable and then your text will wrap to the size of your JTextArea.
Also put a StringBuilder in your while loop instead of using String concatenation which has a lot of overhead.

Related

Java Login Function

Hey I need some help with my code..
I want it to say 'logged on' when the 'Pass' and 'getPass' is the same.
and if its not its says 'logged off'.. but it says that all the time even if its correct. :/. Can Someone Help Me :(
p.s
sorry For My Bad English xd
package ca.sidez.main;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private static JTextField txtName;
private static JTextField txtPass;
public static String Pass;
public static String Pass2;
public static String getPass;
public static String getName;
public static String File;
public Main() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e1) {
e1.printStackTrace();
}
setResizable(false);
setTitle("Login");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(380, 380);
setLocation(100, 100);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtName = new JTextField();
txtName.setBounds(67, 50, 165, 28);
contentPane.add(txtName);
txtName.setColumns(10);
txtPass = new JTextField();
txtPass.setBounds(67, 100, 165, 28);
contentPane.add(txtPass);
txtPass.setColumns(20);
JLabel lblName = new JLabel("Login");
lblName.setBounds(127, 20, 100, 30);
contentPane.add(lblName);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File = txtName.getText();
Share();
}
});
btnLogin.setBounds(60, 311, 117, 29);
contentPane.add(btnLogin);
}
public static void Share() {
try {
//Checks if The Username Exists.
File file = new File(File + ".txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
Pass = stringBuffer.toString();
getPass = txtPass.getText();
getName = txtName.getText();
System.out.println("Clients Password: " + getPass + " For Acc '" + getName + "' ");
System.out.println("The Correct Password For Acc: " + getName + " Is: " + Pass);
if(Pass == getPass) {
System.out.println("Logged In");
} else {
System.out.println("Logged Out");
}
} catch (IOException e) {
System.out.println("Wrong Username Or Password");
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
There are probably many issues with the code you have posted but one of them, and perhaps this is why it is not working as you think it should, is the adding of a newline to the stringbuffer:
stringBuffer.append(line);
stringBuffer.append("\n");
This would make the password in the file "mySecretPassword\n" which will not evaluate to true when compared to "mySecretPassword" using Equals (assuming that is the password in the file and what the user entered in the password field).
Your code would also not work if there is more than one line in the password file. If the assumption is that there will be only one line in the file and it is the password to verify against, then read only one line.
if(Pass == getPass)
Should really be:
if(Pass.compareTo(getPass) == 0)
or
if(Pass.equals(getPass))
Are how you actually compare the content of the string.
if(Pass == getPass)
Is how you compare to see if they are both references to the same object.
Another Problem
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
Pass = stringBuffer.toString();
Adds a new line to the end of Pass
You just want
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
fileReader.close();
Pass = stringBuffer.toString();

reading a log file and displaying it in jTextArea [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to read a file that changes dynamically and display its contents in jTextArea.
I am using buffered reader for reading.
I have tried to display the contents on console and it works fine, but doesn't work with jTextArea.
I am doing something like
while(true)
{
line = br.readLine();
if(line == null)
Thread.sleep();
else
System.out.println(line);
}
Any help would be appreciated. Thanks
Don't use Thread.sleep(), you will block the EDT. Instead use a javax.swing.Timer if you want to "animate" the results. Just read each line each iteration of the timer, until it reaches the end of the file, then stop the timer
timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
String line;
try {
if ((line = reader.readLine()) != null) {
textArea.append(line + "\n");
} else {
((Timer) e.getSource()).stop();
}
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
Test this program out. I think it works the way you want it to.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ReadFile {
File file = null;
BufferedReader reader = null;
private Timer timer = null;
private JTextArea textArea;
private JTextField jtfFile;
private String fileName;
private JButton browse;
private JFrame frame;
public ReadFile() {
textArea = new JTextArea(25, 60);
frame = new JFrame("Show Log");
browse = new JButton("Browse");
browse.addActionListener(new ShowLogListener());
jtfFile = new JTextField(25);
jtfFile.addActionListener(new ShowLogListener());
timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
String line;
try {
if ((line = reader.readLine()) != null) {
textArea.append(line + "\n");
} else {
((Timer) e.getSource()).stop();
}
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
JPanel panel = new JPanel();
panel.add(new JLabel("File: "));
panel.add(jtfFile);
panel.add(browse);
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(textArea), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private class ShowLogListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
fileName = file.getName();
jtfFile.setText(fileName);
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
timer.start();
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new ReadFile();
}
});
}
}
2 points:
Don't call Thread.sleep() in the EDT. This blocks the UI and prevents UI updates
JTextArea has a read method that allows files to be loaded
Example:
JTextArea textArea = new JTextArea();
textArea.read(new FileReader("input.txt"), "blah");
String line;
String textToDisplay = "";
while((line = br.readLine()) != null)
textToDisplay+=line;
textArea.setText(textToDisplay);
I used setText(String) instead of append(String) because it'll replace what is already is in the JTextArea... From your question I felt that's what you wanted to do.
You have to set the text of the text area..try doing so:
{
line = br.readLine();
if(line == null)
Thread.sleep();
else
textArea.append(line + "\n");
}
this will append (put text at end) of the file, meaning that you will not have to worry about text being deleted each time it runs
that should work, hope it helps

While loop not updating variable defined by user

So, I have two classes.
main class:
package guiprojj;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import guiprojj.gui;
import javax.swing.JFrame;
#SuppressWarnings("unused")
public class Test {
public static String movie;
public static String line;
public static void main(String args[]) throws IOException {
BufferedReader rd;
OutputStreamWriter wr;
//Scanner s = new Scanner(System.in);
//System.out.println("Enter input:");
//movie = s.nextLine();
//movie = movie.replaceAll(" ", "%20");
while (movie != null)
{
try {
URL url = new URL("http://www.imdbapi.com/?i=&t=" + movie);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
// Get the response
rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
line = rd.readLine();
if (line != null) {
System.out.println(line);
} else {
System.out.println("Sorry! That's not a valid URL.");
}
} catch (UnknownHostException codeyellow) {
System.err.println("Caught UnknownHostException: " + codeyellow.getMessage());
}
catch (IOException e)
{
System.out.println("Caught IOException:" + e.getMessage());
}
}
}
}
gui class:
package guiprojj;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class gui {
public static void main(String[] args)
{
JFrame maingui = new JFrame("Gui");
JPanel pangui = new JPanel();
JButton enter = new JButton("Enter");
JLabel movieinfo = new JLabel(Test.line);
final JTextField movietext = new JTextField(16);
maingui.add(pangui);
pangui.add(movietext);
pangui.add(enter);
pangui.add (movieinfo);
maingui.setVisible(true);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
enter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
Test.movie = movietext.getText();
System.out.println(Test.movie);
}
});
}
}
What I am writing is a program that outputs the movie data from imbd after you enter it in the box, and I am running into an issue.
When I type in the movie, and press enter, it still shows as null and doesn't seem to be outputting the data from the api I am using.
public class Test {
public static String getMovieInfo(String movie) {
BufferedReader rd;
OutputStreamWriter wr;
//Scanner s = new Scanner(System.in);
//System.out.println("Enter input:");
//movie = s.nextLine();
//movie = movie.replaceAll(" ", "%20");
if (movie != null)
{
try {
URL url = new URL("http://www.imdbapi.com/?i=&t=" + movie);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
// Get the response
rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = rd.readLine();
if (line != null) {
return line;
} else {
return "Sorry! That's not a valid URL.";
}
} catch (UnknownHostException codeyellow) {
System.err.println("Caught UnknownHostException: " + codeyellow.getMessage());
}
catch (IOException e)
{
System.out.println("Caught IOException:" + e.getMessage());
}
}
else
{
return "passed parameter is null!";
}
return "an error occured, see console!";
}
}
I've rewritten your Test-class. Renamed main-method, added return-statements (String) and removed the while-loop. Try to avoid multiple main(String[] args)-methods in one project, else your IDE could launch the "wrong" one, if your context switches.
I did not test it, but now you should be able to call Test.getMovieInfo("movie-name") from your gui-class to get the info.
(nethertheless this code should be refactored ;))

In Attempt to Create a JFileChooser--public variables?

In my previous question, I've stated I'm somewhat new to Java's JFrame features.
I'm trying to create a JFileChooser that will get a directory in which a file named setup.exe will be saved. That's irrelevant, though.
I'm receiving this error:
C:\Users\b\Downloads\files\thankyousanta>javac UpdateMechanism.java
UpdateMechanism.java:31: error: <identifier> expected
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
^
UpdateMechanism.java:31: error: <identifier> expected
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
^
UpdateMechanism.java:33: error: <identifier> expected
openButton.addActionListener(openButton);
^
UpdateMechanism.java:33: error: <identifier> expected
openButton.addActionListener(openButton);
^
4 errors
...for this code:
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
import javax.swing.filechooser.*;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFileChooser;
import javax.swing.BoxLayout;
import javax.Swing.SwingUtilities;
import javax.swing.BorderFactory;
import javax.swing.border.EmptyBorder;
import javax.imageio.ImageIO;
public class definitiveVoid extends JFileChooser implements ActionListener {
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
JButton openButton = new JButton("The update is waiting on you.");
openButton.addActionListener(openButton);
}
public class UpdateMechanism extends JPanel
implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openButton) {
int returnVal = fc.showOpenDialog(UpdateMechanism.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
} else {
// operation cancelled
}
} else {
// destroy life
}
}
private static String readURL(String targetURL) {
String returnish = "";
try {
URL tempURL = new URL(targetURL);
Scanner s = new Scanner(tempURL.openStream());
while (s.hasNextLine()) {
returnish = returnish+s.nextLine();
}
} catch (IOException e) {
System.out.println(e);
}
return returnish;
}
private static String readFile(String targetFile) {
String returnString = "";
try {
File tempFile = new File(targetFile);
Scanner s = new Scanner(tempFile);
while (s.hasNextLine()) {
returnString = returnString + s.nextLine();
}
} catch(IOException e) {
// !
System.out.println(e);
}
return returnString;
}
private static void showGUI() {
JFrame frame = new JFrame("The Neverhood Restoration Project");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(1024, 600));
frame.setExtendedState(frame.MAXIMIZED_BOTH);
frame.getContentPane().setBackground(new Color(0xA64343));
File fileCheck = new File("C:/Program Files (x86)");
String returnString = null;
String rootDirectory = null;
if (fileCheck.exists()) {
rootDirectory = "C:/Program Files (x86)/DreamWorks Interactive";
String checkFile = rootDirectory+"/Neverhood/version.txt";
File tempFile = new File(checkFile);
if (tempFile.exists()) {
returnString = readFile(checkFile);
} else {
returnString = "It appears you do not have the Neverhood Restoration Project installed, or you are using an earlier version.";
}
} else {
rootDirectory = "C:/Program Files/DreamWorks Interactive";
String checkFile = rootDirectory+"/Neverhood/version.txt";
File tempFile = new File(checkFile);
if (tempFile.exists()) {
returnString = readFile(checkFile);
} else {
returnString = "It appears you do not have the Neverhood Restoration Project installed, or you are using an earlier version.";
}
}
if (returnString.equals(readURL("http://theneverhood.sourceforge.net/version.txt"))) {
returnString = "You are updated to the recent version!";
} else {
returnString = "It appears you're not updated.";
}
JLabel headerLabel = new JLabel("The Neverhood Restoration Project");
headerLabel.setHorizontalAlignment(JLabel.CENTER);
JPanel heapPanel = new JPanel();
heapPanel.setLayout(new BoxLayout(heapPanel, BoxLayout.PAGE_AXIS));
heapPanel.setPreferredSize(new Dimension(500, heapPanel.getPreferredSize().height));
JTextArea heapLabel = new JTextArea(50, 50);
heapLabel.setLineWrap(true);
heapLabel.setWrapStyleWord(true);
heapLabel.setEditable(false);
heapLabel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
heapLabel.setFont(new Font("Serif", Font.PLAIN, 14));
heapLabel.append("Current version: "+readURL("http://theneverhood.sourceforge.net/prettyversion.txt")+".\nInstalled version: "+readFile(rootDirectory+"/Neverhood/prettyversion.txt")+".\n"+returnString+"\n" +
"You can read the full version of the document to the left at http://theneverhood.sourceforge.net."
+ "\nBelow is the download button. Just click, choose your directory to save setup.exe in and enjoy!");
heapPanel.add(heapLabel);
try {
Font sFont = Font.createFont(Font.TRUETYPE_FONT, new File("DUGFB___.TTF"));
sFont = sFont.deriveFont(Font.PLAIN, 48);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(sFont);
headerLabel.setFont(sFont);
} catch (FontFormatException | IOException e) {
System.out.println(e);
}
BufferedImage icoImage = null;
try {
icoImage = ImageIO.read(
frame.getClass().getResource("/nhood.bmp"));
} catch (IOException e) {
System.out.println(e);
}
frame.setIconImage(icoImage);
JEditorPane updateLog = new JEditorPane();
JScrollPane scrollPane = new JScrollPane(updateLog);
updateLog.setEditable(false);
try {
updateLog.setPage("http://theneverhood.sourceforge.net/");
} catch (IOException e) {
updateLog.setContentType("text/html");
updateLog.setText("<html>The application could not load the webpage.</html>");
}
frame.add(headerLabel, BorderLayout.NORTH);
frame.add(scrollPane);
frame.add(heapPanel, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
showGUI();
}
});
}
}
In Java, public classes must be defined in their own file, having the same name (with a .java suffix) as the class name.
You defined a public class named definitiveVoid in the file UpdateMechanism.java. And you tried to put code directly in this class, outside of any method. That isn't valid Java.
Swing is hard and complex. Don't try to use it before knowing the basics of Java.
Moreover, classes, by convention, start with an uppercase letter in Java.

How to display shell command output on a jtextarea in java?

How to display shell command output on a jtextarea in java?
Kindly help
Thanks
You can get shell command output below snippet code, set jtextarea on while loop.
try {
String cmd = "java"; // Set shell command
Process child = Runtime.getRuntime().exec(cmd);
InputStream lsOut = child.getInputStream();
InputStreamReader r = new InputStreamReader(lsOut);
BufferedReader in = new BufferedReader(r);
// read the child process' output
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
// You should set JtextArea
}
} catch (Exception e) { // exception thrown
System.err.println("Command failed!");
}
You need to read the standard output as the process input stream and update the JTextArea using the event queue from another thread. See the example code below:
public class OutputDisplayer implements Runnable {
protected final JTextArea textArea_;
protected Reader reader_ = null;
public OutputDisplayer(JTextArea textArea) {
textArea_ = textArea;
}
public void commence(Process proc) {
InputStream in = proc.getInputStream();
reader_ = new InputStreamReader(in);
Thread thread = new Thread(this);
thread.start();
}
public void run() {
StringBuilder buf = new StringBuilder();
try {
while( reader_ != null ) {
int c = reader_.read();
if( c==-1 ) return;
buf.append((char) c);
setText( buf.toString() );
}
} catch ( IOException ioe ) {
buf.append("\n\nERROR:\n"+ioe.toString());
setText( buf.toString() );
} finally {
try {
reader_.close();
} catch ( IOException ioe ) {
ioe.printStackTrace();
}
}
}
private void setText(final String text) {
EventQueue.invokeLater(new Runnable() {
public void run() {
textArea_.setText(text);
}
});
}
}
In addition to my two links in my comments above, I created and used a TextAreaOutputStream that helps to redirect output stream data to a textarea:
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class TextAreaOutputStream extends OutputStream {
private final JTextArea textArea;
private final StringBuilder sb = new StringBuilder();
private String title;
public TextAreaOutputStream(final JTextArea textArea, String title) {
this.textArea = textArea;
this.title = title;
sb.append(title + "> ");
}
#Override
public void flush() {
}
#Override
public void close() {
}
#Override
public void write(int b) throws IOException {
if (b == '\r')
return;
if (b == '\n') {
final String text = sb.toString() + "\n";
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
sb.setLength(0);
sb.append(title + "> ");
}
sb.append((char) b);
}
}
import java.io.OutputStream;
import javax.swing.JTextArea;
/**
* This class extends from OutputStream to redirect output to a JTextArrea
* #author www.codejava.net
*
*/
public class CustomOutputStream extends OutputStream {
private JTextArea textArea;
public CustomOutputStream(JTextArea textArea) {
this.textArea = textArea;
}
#Override
public void write(int b) throws IOException {
// redirects data to the text area
textArea.append(String.valueOf((char)b));
// scrolls the text area to the end of data
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package guiconsoleoutput;
/**
*
* #author root
*/
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
public class TextAreaLogProgram extends JFrame {
/**
* The text area which is used for displaying logging information.
*/
private JTextArea textArea;
private JButton buttonStart = new JButton("Start");
private JButton buttonClear = new JButton("Clear");
private PrintStream standardOut;
public TextAreaLogProgram() {
super(" CONSOLE ");
textArea = new JTextArea(50, 10);
textArea.setEditable(false);
PrintStream printStream = new PrintStream(new CustomOutputStream(textArea));
// keeps reference of standard output stream
standardOut = System.out;
// re-assigns standard output stream and error output stream
System.setOut(printStream);
System.setErr(printStream);
// creates the GUI
setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.insets = new Insets(10, 10, 10, 10);
constraints.anchor = GridBagConstraints.WEST;
add(buttonStart, constraints);
constraints.gridx = 1;
add(buttonClear, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
add(new JScrollPane(textArea), constraints);
// adds event handler for button Start
buttonStart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
printLog();
}
});
// adds event handler for button Clear
buttonClear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
// clears the text area
try {
textArea.getDocument().remove(0,
textArea.getDocument().getLength());
standardOut.println("Text area cleared");
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(480, 320);
setLocationRelativeTo(null); // centers on screen
}
/**
* Prints log statements for testing in a thread
*/
private void printLog() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
System.out.println("Time now is " + (new Date()));
System.out.println("lol ");
String s = null;
/*try {
// run the Unix "ps -ef" command
// using the Runtime exec method:
Process p = Runtime.getRuntime().exec("dir");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}*/
try {
String cmd = "cmd /c ping 8.8.8.8"; // Set shell command
Process child = Runtime.getRuntime().exec(cmd);
InputStream lsOut = child.getInputStream();
InputStreamReader r = new InputStreamReader(lsOut);
BufferedReader in = new BufferedReader(r);
// read the child process' output
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
// You should set JtextArea
}
} catch (Exception e) { // exception thrown
System.err.println("Command failed!");
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
});
thread.start();
}
/**
* Runs the program
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TextAreaLogProgram().setVisible(true);
}
});
}
}

Categories