1

I want to implement a JtextArea use as a console for any java program run through ProcessBuilder Here is my code

import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JTerminal extends JFrame implements KeyListener{

    private static String proPath = "D:" + File.separator + "Smart Coder Projects" + File.separator;
    private static String projectName = "Triangle";

    private JTextPane area = new JTextPane();
    private JTextField input = new JTextField("Input");

    private SimpleAttributeSet inputSAS = new SimpleAttributeSet(), output = new SimpleAttributeSet(), error = new SimpleAttributeSet();

    private ArrayList<String> paramsExecute = new ArrayList<String>();
    private Process process;

    public JTerminal() throws IOException {
        super("JTerminal");

        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        StyleConstants.setForeground(inputSAS, Color.GREEN);
        StyleConstants.setBackground(inputSAS, Color.BLACK);

        StyleConstants.setForeground(output, Color.WHITE);
        StyleConstants.setBackground(output, Color.BLACK);

        StyleConstants.setForeground(error, Color.RED);
        StyleConstants.setBackground(error, Color.BLACK);

        String target = proPath + projectName + File.separator + "bin";

        paramsExecute.add("java");
        paramsExecute.add("-cp");
        paramsExecute.add(target);
        paramsExecute.add("Triangle");




        input.addKeyListener(this);
        ProcessBuilder builder = new ProcessBuilder(paramsExecute);
        process = builder.start();





        area.setBackground(Color.black);
        area.setCaretColor(Color.green);
        area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
        area.setEditable(false);

        JScrollPane pane = new JScrollPane(area);
        pane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
        pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        pane.setPreferredSize(new Dimension(640, 460));

        input.setBackground(Color.black);
        input.setForeground(Color.green);
        input.setCaretColor(Color.green);
        input.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
        input.setBorder(BorderFactory.createLineBorder(Color.GREEN));

        add(pane);
        add(input);

        Dimension DIM = new Dimension(640, 480);
        setPreferredSize(DIM);
        setSize(DIM);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(true);
        pack();
        setVisible(true);



    }

    public void exec(){

        while(process.isAlive()){
            input.setEditable(false);
            writeStream(process.getErrorStream(), error);
            writeStream(process.getInputStream(), output);
            input.setEditable(true);
            input.requestFocus();
        }
    }

    public static void main(String[] args) throws IOException {
        JTerminal terminal = new JTerminal();
        terminal.setVisible(true);
        //terminal.exec();
    }

    private void write(SimpleAttributeSet attributeSet, String... lines) {
        try {
            if (lines.length == 0) {
                return;
            }
            for (String line : lines) {
                area.getStyledDocument().insertString(area.getStyledDocument().getLength(), line + "\n", attributeSet);
            }
            area.getStyledDocument().insertString(area.getStyledDocument().getLength(), "\n", attributeSet);
        } catch (Exception e) {
            error(e);
        }
    }

    private void error(Exception e) {
        write(error, "An error has occured: " + e.getLocalizedMessage());
        e.printStackTrace(); //TODO: temp.
    }

    private void writeStream(InputStream s, SimpleAttributeSet color) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(s));

            ArrayList<String> strs = new ArrayList<String>();

            while (reader.ready()) {
                strs.add(reader.readLine());
            }

            if (strs.size() > 0) {
                write(color, strs.toArray(new String[strs.size()]));
            }
        } catch (Exception e) {
            error(e);
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    try {
                        String command = input.getText();
                        if (command.equals("")) {
                            return;
                        }
                        input.setText("");
                        input.setEditable(false);

                        write(inputSAS, command);

                        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(process.getOutputStream());
                        outputStreamWriter.write(command);
                        outputStreamWriter.close();

                    } catch (Exception ex) {
                        error(ex);
                    }
                } //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void keyPressed(KeyEvent e) {

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}

Here i am stuck at how to continuously get input from process and send output to process during its execution

i used a function exec() but it throws exception because it calls again and again i want to implement console like netbeans console to run java programs enter image description here

Waqas Ahmed
  • 1,321
  • 1
  • 14
  • 23

0 Answers0