//http://www.java2s.com/Code/Java/File-Input-Output/StandardErrandOutputWindows.htm
// Standard Err and Output Windows

package menu;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import DrawTop.*;


public class DialogOfSystemOut extends JDialog implements WindowListener {

    public DialogOfSystemOut() {
        super(ObjectTable.getDrawMain(), "System.out");
        this.setName("DialogOfSystemOut");  
        this.addWindowListener(this);
    }
    
    public void showDialog(){
        MenuUtil menuUtil=ObjectTable.getMenuUtil();
        DialogOfSystemOut dialog
                =(DialogOfSystemOut)menuUtil.getMenuComponent("DialogOfSystemOut");
        if(dialog!=null) {
            JOptionPane.showMessageDialog(ObjectTable.getDrawMain(), 
                    "system.out dialog is already opened", "", JOptionPane.ERROR_MESSAGE);
            return;
        }
        JTextArea textArea=new JTextArea(20, 50);
        JScrollPane scrollPane = new JScrollPane(textArea);
        this.getContentPane().add(scrollPane);
        this.setMinimumSize(new Dimension(600,200));
     //set this location
        DrawMain main=ObjectTable.getDrawMain();
        Point centerP=new Point(main.getX()+10, main.getY()+100);
        this.setLocation(centerP);
     //redirect OutputStream
        TextAreaOutputStream outputStream=new TextAreaOutputStream(textArea);
        System.setOut(new PrintStream(outputStream));
        //System.setErr(new PrintStream(outputStream));
    // show dialog    
        this.setVisible(true);
        menuUtil.setMenuComponent(this);
    }
  
    private void closeDialog(){
        this.setVisible(false);
        MenuUtil menuUtil=ObjectTable.getMenuUtil();
        Component component=menuUtil.getMenuComponent(this.getName());
        if(component!=null) menuUtil.removeMenuComponent(component);
        FileOutputStream fileOut=new FileOutputStream(FileDescriptor.out);
        PrintStream out=new PrintStream(new BufferedOutputStream(fileOut), true);
        System.setOut(out);
        System.setErr(out);
    }
    
    public void windowActivated(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {}
    public void windowClosing(WindowEvent e) {
        this.closeDialog();
    }
    public void windowDeactivated(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowOpened(WindowEvent e) {}
}

class TextAreaOutputStream extends OutputStream {
    JTextArea textArea;

    public TextAreaOutputStream(JTextArea textArea) {
        super();
        this.textArea=textArea;
    }
    
    public void write(int i) {
        this.textArea.append(Character.toString((char)i));
    }
    
    public void write(char[] buf, int off, int len) {
        String s = new String(buf, off, len);
        this.textArea.append(s);
    }
}
