To redirect System.out stream output on swing's JTextArea

Following is a program that needs to print output as follows:-
EXPECTED OUTPUT ON GUI:_ In action block (datapayload value) In Routing block (argus value)
PRESENT PROGRAM OUTPUT ON GUI_ In action block (datapayload value)
please examine the below code and correct mistakes to get the expected output as given above.....
I am not getting the second line as output on GUI i.e., In Routing block (argus value)
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    public class Demo extends JFrame implements ActionListener
      JTextField datapayload;
      JLabel Datapayload;
      JButton submit;
      JTextArea textFieldName;
      public Demo()
         DemoLayout customLayout = new DemoLayout();     
         getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
         getContentPane().setLayout(customLayout);
         Datapayload = new JLabel("Enter DataPayload:");
         getContentPane().add(Datapayload);
         datapayload = new JTextField("abcd...");
         getContentPane().add(datapayload);
         submit = new JButton("submit");
         getContentPane().add(submit);
         textFieldName = new JTextArea(80,10);
         textFieldName.setEditable( false );
         JScrollPane scroll = new JScrollPane(textFieldName) ;
         scroll.setBounds( 10, 60, 225, 150 );
         getContentPane().add( scroll );
         submit.addActionListener(this);
         setSize(getPreferredSize());
       public void actionPerformed(ActionEvent e)
          String demodata=datapayload.getText();
             textFieldName.append("In Action Block"+"\t"+demodata);  
          Demo pr = new Demo();                              
          pr.DemoRoute(demodata);
       public void DemoRoute(String argus)
             textFieldName.append("In routing block"+"\t"+argus);
        public static void main(String args[])
             Demo window = new Demo();
             window.setTitle("Demo");
             window.pack();
             window.show();
    class DemoLayout implements LayoutManager
       public DemoLayout() {  }
       public void addLayoutComponent(String name, Component comp) {   }
       public void removeLayoutComponent(Component comp) {  }
       public Dimension preferredLayoutSize(Container parent)
         Dimension dim = new Dimension(0, 0);
         Insets insets = parent.getInsets();
         dim.width = 320 + insets.left + insets.right;
         dim.height = 240 + insets.top + insets.bottom;
         return dim;
       public Dimension minimumLayoutSize(Container parent)
         Dimension dim = new Dimension(0, 0);
         return dim;
       public void layoutContainer(Container parent)
         Insets insets = parent.getInsets();
         Component c;
         c = parent.getComponent(0);
         if (c.isVisible()) {c.setBounds(insets.left+90,insets.top+8,172,26);}
         c = parent.getComponent(1);
         if (c.isVisible()) {c.setBounds(insets.left+230,insets.top+8,172,26);}
         c = parent.getComponent(2);
         if (c.isVisible()) {c.setBounds(insets.left+230,insets.top+52,142,26);}
         c = parent.getComponent(3);
         if (c.isVisible()) {c.setBounds(insets.left+90,insets.top+100,472,268);}
    }  Edited by: 997189 on Mar 31, 2013 8:52 AM

Hi,
change your actionPerformed() method as below to get the required output.
public void actionPerformed(ActionEvent e)
          String demodata=datapayload.getText();
             textFieldName.append("In Action Block"+"\t"+demodata);  
          //Demo pr = new Demo();      You are creating a new object to all DemoRoute method. This is the problem                         
          //pr.DemoRoute(demodata);
             this.DemoRoute(demodata);
}And also my suggestion is follow java coding conventions while coding

Similar Messages

  • Redirecting System.out stream to a TextArea

    I hope this isn't a stupid question--I'm blanking pretty hard.
    I want to use System.setOut() to direct standard output to a TextArea within a Frame. Is there a way to setup a TextArea to receive text from an output stream, or is an intermediary of some sort necessary?
    I feel like this is pretty easy, but I'm stumbling. That's what I get for doing J2EE for a year rather than GUI. :P
    Any input is appreciated!

    Here's the compiled and tested code...I learned some good stuff from this link as to why my simpler approach didn't work:
    http://www.devx.com/upload/registered/features/javapro/1999/11nov99/tl1199/tl1199.asp
    Here is my code:
      class OutRouter implements Runnable
        PipedInputStream pipeIn = null;
        JTextArea textArea = null;
        OutRouter( JTextArea ta, PipedOutputStream pos)
          try
            pipeIn = new PipedInputStream(pos);
          catch(IOException ioe)
            ioe.printStackTrace(System.err);
            System.exit(1);
          textArea = ta;
        public void run()
          String line = null;
          BufferedReader pipeReader = new BufferedReader(
            new InputStreamReader(pipeIn));
          try
            while(true)
              Thread.sleep(100);
              if(pipeIn.available() == 0)
                continue;
              line = pipeReader.readLine();
              if(line == null)
                continue;
              System.err.println("Line = " + line);
              final String fLine = line;
              SwingUtilities.invokeAndWait( new Runnable()
                {public void run()
                  { textArea.append(fLine + "\n"); }
          catch(InvocationTargetException ite)
          { ite.printStackTrace(System.err); System.exit(1); }
          catch(InterruptedException ie)
          { ie.printStackTrace(System.err); System.exit(1); }
          catch(IOException ioe)
          { ioe.printStackTrace(System.err); System.exit(1); }
      }

  • Redirecting System.out() output to a JTextArea control

    I want to be able to redirect System.out() and System.err() messages to a JTextArea control:
    I know how to redirect output to a file as follows:
    FileOutputStream fos =
    new FileOutputStream(filename, true);
    PrintStream ps = new PrintStream(fos, true);
    System.setOut(ps);
    System.setErr(ps);
    How can I set it up so that I can recognise when messages have been to System.out() with a view to displaying the message within the JTextArea?
    I guess I need to set it up so that the JTextArea control acts as an Observer. The bit I'm having difficulty with is figuring out how I can automatically determine when information has been written to System.out()?
    Hopefully I'm explaining my issue in enough detail and clarity.
    thanks
    - Garry

    I would suggest you set up a separate thread to monitor System.out. Use a PipedOutputStream and redirect System.out to that, then connect that to a PipedInputStream that your other thread is continually waiting to read. Each time that thread reads a line, it should append the line to the JTextArea, using SwingUtilities.invokeLater.
    This is just a rough outline of something that might work. Hope it helps.

  • Redirect, System.out  ?

    Hi.
    I want to redirect System.out to a Swing Component like JTextArea, etc.
    try with printstream, Reader, etc. but i dont know how.!.
    I want to see, messages (The standard out) in a Swing Component.
    plis some help..
    tnks.

    I was using the Redirect method you made edna for my software and it works wonderfully when using strings, unfortunately I ran in to a strange problem which is fitting since my current objective is very strange.
    I am writing a piece of software that has an embedded jython interpreter in it. When I execute my jython scripts all the output went to the console and I had no direct way of saying append to this particular text area since I wasn't able to pass my Java GUI class in to the script.
    Thus redirecting my output with your method came in quite handy. This is where the problem comes in. I tried the println function in my regular java classes and all the primitive types worked fine, but within in the script only String worked. Here is the code for the println function
    PrintStream stdout = new PrintStream(System.out) {
       public void println(String x) {
          outputTextArea.append(x + "\n");
       public void println(int x) {
          outputTextArea.append(x + "\n");
       public void println(boolean x) {
          outputTextArea.append(x + "\n");
       public void println(Object x) {
          outputTextArea.append(x.toString() + '\n');
    };Here is the sample Jython code:
    import JythonScripter
    System.out.println(4) #fails to print correctly
    System.out.println("HelloWorld") #works
    System.out.println(10) #fails
    System.out.println("Goodbye Cruel World") #works
    If you have any advice on why strings would work but not other types I would greatly appreciate it.

  • Redirect system.out.println() to a file

    hi all,
         how can i redirect all the console prints to a txt file in java application? i have used system.out oftenly in many class throught the
    application. is there any way to redirect all those console prints to a
    txt file by converting or assigning the System.out stream to a stream for filewriter or
    somthing like that, so that whenever system.out.println() is executed
    the content is written to a file insted of on the console.
    thanks in advance
    Sojan

    Actually,System.setOut(new PrintStream(new FileOutputStream("output.txt"), true));
    System.setErr(System.out);since setOut wants a PrintStream and not just some OuputStream...

  • Redirecting System.out to a JTextArea

    How can I redirect the System.out Stream into a JTextArea?
    I found the method System.setOut(PrintStream out) but I don't know
    how to get the PrintStream of my TextArea.

    I don't know if this is the most efficient way but it provides an example of using Pipes:
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TextAreaStream extends JTextArea implements Runnable{
         private static final PipedOutputStream _pipeOut = new PipedOutputStream();
         static{
                   System.setOut( new PrintStream(_pipeOut) );
         private InputStream _pipeIn;
    private byte[] buffer = new byte[256];
         public TextAreaStream(){
              this(1,10);
         public TextAreaStream(int numRows, int numCols){
              super(numRows, numCols);
              Thread t = new Thread(this);
              t.setDaemon(true);
              t.start();
              try{
              pipeIn =  new BufferedInputStream(new PipedInputStream(pipeOut));
              catch(IOException e){
                   System.err.println("Error creating pipe: "+e);
         public void run(){
              while(true){
                   try{
                        //blocks at read
                        int bytesRead = _pipeIn.read(buffer);
                        append(new String(buffer,0,bytesRead));
                   catch(IOException e){
                        System.err.println(e);
         public static void main(String[] args){
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JTextArea text = new TextAreaStream();
              text.setBorder(BorderFactory.createTitledBorder("System.out"));
              f.getContentPane().add(text);
              //Add an input component
              JPanel north = new JPanel(new FlowLayout(FlowLayout.LEFT));
              final JTextField field = new JTextField(25);
              north.add(field);
              north.add(new JLabel("Add text, press Enter"));
              f.getContentPane().add(north, BorderLayout.NORTH);
              field.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        System.out.println(field.getText());
                        field.setText("");
    f.setSize(600, 400);
              f.show();
    }

  • Reading System out stream ?

    Hi,
    I don't know whether I am asking a stupid question or not . But my problem is that in my thousand lines of code i wrote number of System.out.println(".....") statements to describe various situations / state of program which write those strings of messages to standard output i.e console . Here at this point of situation I was wondering that is there a possible way that i could read System.out stream by concurrently running a thread who could look on this stream and could redirect it to a file where i want. By achieving this I don't need to go at every piece of code where i have written System.out.println(".....") and change it to get desired result.
    If it is possible , please let me know ?
    Thanks in advance,
    Hemant.

    A suggestion - next time, set up a boolean - call it maybe "debugFlag" and check it befor a system.out write. That way all that's needed is to reset the flag and recompile when it goes to "production".
    And then the other possibility is to use your editor and do some global change all in your code.

  • Redirecting System.out to a textfield

    I want the output created by System.out (especially error messages) redirected to a textfield in stead of the console. How can I do this?

    this is how I've done it. Just create a new instance of this class and pass in your TextArea. It redirects System.out and checks for messages on System.out every 5 seconds.
    import java.io.*;
    import javax.swing.*;
    public class TextOut
    implements Runnable
         private JTextArea text;
         private Reader in;
         private Thread t;
         public TextOut( JTextArea text )
              throws Exception
              this.text = text;
              PipedOutputStream pout = new PipedOutputStream();
              System.setOut( new PrintStream( pout ) );
              in = new InputStreamReader( new PipedInputStream( pout ) );
              t = new Thread( this );
              t.start();
         public void run()
              while( true )
                   try
                        StringBuffer buffer = null;
                        while( in.ready() )
                             if ( buffer == null ) buffer = new StringBuffer();
                             buffer.append( (char)in.read() );
                        if ( buffer != null )
                             text.append( buffer.toString() );
                             java.awt.Rectangle r = new java.awt.Rectangle();
                             text.computeVisibleRect( r );
                             text.repaint( r );
                        t.sleep( 5000 );
                   } catch (IOException ioe) {
                        text.append( "" + ioe );
                   } catch (InterruptedException ie ) {
                        text.append( "" + ie );

  • Redirecting System.out?

    I am working with a team, and I am testing a standalone Java application using separate unit tests. The program takes text input and outputs some text results, but the way it is set up, it will output directly to System.out as soon as it needs it. I am not in control of the way it outputs the results.
    I need to capture all of the results from System.out, and compare them to what I know should be printed out. How do I do this without touching the original source files? Is there a way to do it purely in Java (my backup is to use shell scripts, but I really don't want to)?

    Well, you don't need to change all the source files, but you will need to
    change the source file with your main method.You don't even have to do that: build a Wrapper class with its own main
    that redirects System.out to a file and calls the Application.main afterwards.
    Instead of starting the Application, start the Wrapper.
    kind regards,
    Jos

  • Is System.out stream synchronized?

    Hi,
    I am using the System.out stream to print various logging messages
    by different threads.
    I am using System.out.println
    Is this thread-safe?
    The messages themselves are only for development, they are not essential,
    that's why I haven't bothered to set up any synchronization mechanism...

    Hi,
    are you sure?
    On what grounds do you claim this?
    The Javadocs do not specify it.
    Thanks.If you question the correctness, it's time for you to do your own research.

  • Redirecting System.out/err

    Hi all,
    Is there an easy way to redirect the System.out/err stream to my own stream? I want to implement that everything going to System.out/err will be printed in a JTextArea instead of the console (Like JBuilder does for example).
    Thanks for any hint, Mathias

    System.setErr(myErrorOutputStream);
    System.setOut(myStdOutStream);

  • Urgent: Redirecting System.out.println to more than one place

    Hi All,
    I want to divert all my System.out.println() statements to a Log file as well as on to the screen.
    But only one of the 2 options actually works.
    So if anyone can suggest me some ways I will appreciate very much.
    My code looks something like this:-
    if (m_filename != null) {
    try {
    FileOutputStream fos = new FileOutputStream(m_filename);
    PrintStream ps = new PrintStream(fos);
    System.setOut(ps);
    System.setErr(ps);
    //This code Added for Printing Onto Screen But it does not work
    Stream ps1 = new PrintStream(System.out);
    System.setOut(ps1);
    System.setErr(ps1);
    } catch (IOException ioe) {
    System.out.println("Could not create log file " + m_filename + " because " + ioe);
    As far as logging onto file is menat it works when i set it but printing onto screen does not.
    How can i achive it
    Thanks
    Raj

    Hi,
    You are right but in my current scenario i cannot incorporate this log4j because my application is using some other framework and I am just trying to override this frameworks loggig behaviour so that it logs to both a log file as well as on to the screen.
    Here is the code that this framework uses for logging and i am simply overriding it to do the reqd thing but its not working for me:-
    * Resets the System's out and err OutputStreams to the Launcher's
    * own ThreadedOutputStream, so that output from different threads
    * can be tracked efficiently.
    protected void setOutputStreams() {
         if (scInfo.size() <= 1) {
    // don't need Threaded handling with one thread
    if (m_filename != null) {
    try {
    FileOutputStream fos = new FileOutputStream(m_filename);
    PrintStream ps = new PrintStream(fos);
    System.setOut(ps);
    System.setErr(ps);
    //Added for Printing Onto Screen
                             PrintStream ps1 = new PrintStream(System.out);
    System.setOut(ps1);
    System.setErr(ps1);
    } catch (IOException ioe) {
    Debug.fatalError("Launcher.setOutputStreams","Could not create log file " + m_filename + " because " + ioe);
    else {
    Debug.information("Launcher.setOutputStreams","Initializing ThreadedPrintStream");
    if (m_filename == null) {
    System.setOut(new ThreadedPrintStream(System.out));
    System.setErr(new ThreadedPrintStream(System.err));
    else {
    PrintStream out = new ThreadedPrintStream(m_filename);
    System.setOut(out);
    System.setErr(out);
    //Added for Printing Onto Screen
    System.setOut(new ThreadedPrintStream(System.out));
    System.setErr(new ThreadedPrintStream(System.err));
    Debug.information("Launcher.setOutputStreams","ThreadedPrintStream initialized.");
    Thanks
    Raj

  • Redirecting system.out to a file

    I want to have the output of these threads go to a file, which it is doing now, but the program is finishing before all the data is written to the file.
    I had another idea that the threads could write to a shared stringbuffer and then when they have finished, i could write the contents of that stringbuffer to a file, but when do it tell it to write to the file. how can i tell when the threads are finished.
    /*      12 Nov 2002
         Class extends PThread which extends Thread.
    import Concurrency.*;
    import java.io.*; //added to write output to a file
    public class Exercise1 extends PThread{
         private static File theOutputFile;
         private static FileWriter fileWriterStream;
         private static int counter = 0;
         public Exercise1() {
              try {
                   if(theOutputFile == null) {
                        theOutputFile = new File("output.txt");
                        fileWriterStream = new FileWriter(theOutputFile);
              }catch(IOException ioe){}     
         public static void main(String[] args) throws IOException {
              System.out.println("Dave Casserly\n" +
                                       "Check the source folder for a file called output.txt\n" +
                                       "This contains the programs output.\n");
              Exercise1 thread1 = new Exercise1();
              Exercise1 thread2 = new Exercise1();
              thread1.start();
              thread2.start();
         //each thread will look at counter make sure its less than 1000,
         //get the current counter value and increment it
         //print it to screen
         //then increment the static counter
         public void run(){
              try {
                   while(counter <= 1000) {
                        int count = counter;
                        count++;
                        counter++;
                        System.out.println("COUNT = " + count);                    //write to screen
                        fileWriterStream.write("COUNT = " + count + "\n");      //write to file
                        counter = count;     
              }catch(IOException io){}     
    }//end of class

    You need to join the main thread with the child threads.
    Something like this:
      Exercise1 thread1 = new Exercise1();
      Exercise1 thread2 = new Exercise1();
      thread1.start();
      thread2.start();
      thread2.join();
      thread1.join();Or something.

  • System.out console output CP1252/CP850

    I've been trying to write something to receive XML as 'messages' through a socket connection and, in order to see better what's being parsed, I've been writing the elements and data to System.out so I can see the values in the console window (this is Windows XP).
    The problem I get is that when the client passes German characters such as '�' (o-umlaut), they don't get displayed correctly on the console window - the character that actually gets displayed is '�' (division sign?) - even though the correct value DOES (as far as I can tell) find its way into my Java String object.
    I've investigated this a bit and I find that if I 'force' the output to use encoding 'Cp850' (OEM - Multilingual Latin I) then it works correctly (I do this by creating an OutputStreamWriter object with that encoding and based on System.out and then I create a BufferedWriter based on that OutputStreamWriter).
    If, however, I explicitly use Cp1252 (ANSI - Latin I) then I get the original problem. I don't understand this because as far as I can tell, Cp1252 included the '�' character as code 246, which is the one I'm passing to it.
    It also may (or may not) be significant that my file.encoding property is set to 'Cp1252' but when I override this using the java -D command option, I get the correct result.
    So, in essense, my question is: why does Cp850 work but Cp1252 not work?
    Thanks in advance for any help
    Regards
    John

    I could do, but that's not really a problem - I've already got the 'work around' I need using Cp850. I just want to understand WHY it does what it does, because it seems to me that Cp1252 should work as well.

  • Need to hide System.out.println output in console

    class Hide{
    public void test(){
    System.out.println("hai");
    public static void main(String[] args){
    Hide obj=new Hide();
    obj.test();
    Output is : hai
    But I don't want to display hai. How i can hide this
    kindly help me on this........

    class Hide {
         public void test() {
              System.out.println("hai");
         public static void main(String[] args) {
              System.out.println("before");
              java.io.PrintStream old_out = System.out;
              try {
                   java.io.PrintStream pw = new java.io.PrintStream("test.txt");
                   System.setOut(pw);
              } catch (java.io.IOException e) {
                   e.printStackTrace();
              Hide obj=new Hide();
              obj.test();
              System.setOut(old_out);
              System.out.println("after");
    }

Maybe you are looking for

  • Itunes app does not stay open since updated to ios7

    Since updating to ios 7 when I open the iTunes Store app it closes straight away. I have reset and restored the phone worked fine once or twice but has started to do it again. Help. 

  • How to include 3 sql statements in a single procedure

    I have 3 SQL statements to create 3 tables: Table1:To get all the data from an ORIGIN table that have an expiration_dates between 02/01/2006 and 04/30/2006. This has all the customer data (customer_id, company, etc…) Table 2:Secondly I am getting all

  • I can't play YouTube videos on my IPhone! What's the problem?

    I can't watch YouTube Videos on my IPhone 4 (iOS 5.0.1 No jailbreak) The Debug Console from Safari tells me, that there's a mistake in the JavaScript. How to fix it? I already spoke with Google, but they didn't have a problem. I can open other websit

  • USB causes Mac Pro to crash.

    Hi Guys, I've got a MacPro1,1, I have an issue with the USB on it. Now and again, when ever I eject my USB it totally locks my Mac Pro up and I have to cold reboot it (I.E turn the power off). The USB was formatted with the Mac file system, and I alw

  • DNS problem on Snow Leopard Server.

    I have a mac mini server on my network running DNS, File Sharing, Open Directory, and Web services.  I believe that I have everything configured properly, but I'm having a perplexing issue with DNS.  I also have some client machines on the network, a