Friday, October 16, 2009

Java : Implement console in textarea using swing or awt

Program to implement output console using JTextArea of swing or TextArea of awt. Here all output log ie (System.out.println("")) is redirected to textarea rather than console.

Here is the complete code, directly you can run this code and see output.


/* ImplementConsole.java */


import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.io.*;

public class ImplementConsole extends JFrame
{
JTextArea console;
JScrollPane sp_console;

ImplementConsole()
{
setSize(700,350);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridBagLayout());

console = new javax.swing.JTextArea();
console.setColumns(50);
console.setRows(15);

console.setText("Console Output...");

sp_console = new javax.swing.JScrollPane(console);

add(sp_console);

System.setOut(new PrintStream(new JTextAreaOutputStream(console)));
System.setErr(new PrintStream(new JTextAreaOutputStream(console)));


//starting new Thread for log writing
new Thread(new Runnable()
{
public void run()
{ try
{
writeLog();
}
catch (Exception ie)
{ }
}
}).start();
}

//inner class
public class JTextAreaOutputStream extends OutputStream
{
JTextArea ta;

public JTextAreaOutputStream(JTextArea t)
{
super();
ta = t;
}

public void write(int i)
{
ta.append(Character.toString((char)i));
}

public void write(char[] buf, int off, int len)
{
String s = new String(buf, off, len);
ta.append(s);
}
}


//function to write console log
public void writeLog()
{
for(int i=0; i< 10000; i++)
{
System.out.println("Console output : "+i);

// Make sure the last line is always visible
console.setCaretPosition(console.getDocument().getLength());

//just taking pause of 50ms
try
{
Thread.currentThread().sleep(50);
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}

//to flush console log after specific number of lines.
if(console.getLineCount() > 1000)
console.setText("");
}
}

public static void main(String[] args)
{
JFrame obj = new ImplementConsole();
obj.setVisible(true);
}
}



Output

3 comments:

  1. Takes a extremely long time for everything to load?

    ReplyDelete
    Replies
    1. Its just showing how to loop through SOPs, I am doing it purposely.

      //just taking pause of 50ms
      try
      {
      Thread.currentThread().sleep(50);
      }
      catch (Exception e)
      {
      System.out.println("Exception in Thread Sleep : "+e);
      }

      Delete
  2. Affiliate Student Loans People means to sell products.

    ReplyDelete