Code for Console for Java JAR programs.

Amit amitchoudhary0523 at gmail.com
Sat Oct 1 09:58:52 UTC 2022


Code for Console for Java JAR programs in case someone needs it.

Description: When you run a jar file by double-clicking on it, you
don't get console so all your input/output have to be on GUI. This
program solves this problem and gives users/programmers a console
which can be used for input/output as done on console by command line
programs. So, in effect this program gives a console for JAR programs.

-------------------------------------------------------------------------------------------

// License: This file has been released under APACHE LICENSE, VERSION 2.0.
// The license details can be found here:
https://www.apache.org/licenses/LICENSE-2.0

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

public class Console_For_JAR_Programs implements KeyListener, ActionListener {

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int screenWidth = screenSize.width;
    int screenHeight = screenSize.height;

    String title = null;

    JFrame jf = null;
    JTextArea jta = null;
    JScrollPane jsp = null;
    JMenuBar jmb = null;
    JMenu jm = null;
    JMenuItem jmi = null;

    // key codes
    int BACKSPACE = 8;
    int ENTER = 10;
    int PG_UP = 33; // do nothing for this key pressed
    int PG_DN = 34; // do nothing for this key pressed
    int END = 35;
    int HOME = 36;
    int LEFT_ARROW = 37;
    int UP_ARROW = 38; // do nothing for this key pressed
    //int RIGHT_ARROW = 39; // handled by JTextArea
    int DOWN_ARROW = 40; // do nothing for this key pressed

    int CTRL = 128;
    int A = 65; // disable ctrl-a
    int H = 72; // handle ctrl-h
    //int DELETE = 127; // handled by JTextArea

    int initialCaretPosition = 0;
    int endOfInputCaretPosition = 0;
    final Object lock1 = new Object();
    final Object lock2 = new Object();
    boolean inputAvailable = false;
    byte[] b = null;
    int len = -1;
    int indexIntoByteArray = -1;
    boolean newLineSent = false;
    byte endOfInput = -1;
    byte newLine = 10;
    boolean enterAlreadyPressedEarlier = false;

    @Override
    public void actionPerformed(ActionEvent ae) {
        int cCurrPos = jta.getCaretPosition();
        jta.selectAll();
        jta.copy();
        jta.select(cCurrPos, cCurrPos);
    } // end of actionPerformed

    @Override
    public void keyTyped(KeyEvent ke) {
    } // end of keyTyped

    @Override
    public void keyReleased(KeyEvent ke) {
    } // end of keyReleased

    @Override
    public void keyPressed(KeyEvent ke) {
        Thread.currentThread().getId();
        int keyCode = ke.getKeyCode();
        if ((keyCode == PG_UP) || (keyCode == PG_DN) || (keyCode ==
UP_ARROW) || (keyCode == DOWN_ARROW) || ((keyCode == A) &&
(ke.getModifiersEx() == CTRL))) {
            ke.consume();
        } else if ((keyCode == LEFT_ARROW) || (keyCode == BACKSPACE)
|| ((keyCode == H) && (ke.getModifiersEx() == CTRL))) {
            synchronized(lock1) {
                if (jta.getCaretPosition() <= initialCaretPosition) {
                    ke.consume();
                }
            } // end of synchronized block
        } else if (keyCode == HOME) {
            synchronized(lock1) {
                jta.setCaretPosition(initialCaretPosition);
                ke.consume();
            } // end of synchronized block
        } else if (keyCode == END) {
            synchronized(lock1) {
                jta.setCaretPosition(jta.getDocument().getLength());
                ke.consume();
            } // end of synchronized block
        } else if (keyCode == ENTER) {
            // this if block should not exit until all the input has been
            // processed.
            synchronized(lock1) {
                inputAvailable = true;
                endOfInputCaretPosition = jta.getDocument().getLength();
                //if ((endOfInputCaretPosition - initialCaretPosition) == 1) {
                    // only newline was entered, so increment
initialCaretPosition
                if ((enterAlreadyPressedEarlier == true) &&
(endOfInputCaretPosition - initialCaretPosition) > 0) {
                    // need to increment initialCaretPosition by 1 to
account for last enter pressed
                    initialCaretPosition++;
                }
                jta.setCaretPosition(jta.getDocument().getLength());
                enterAlreadyPressedEarlier = true;
                lock1.notifyAll();
            }
            // wait until all input has been processed
            synchronized(lock2) {
                //if (Thread.holdsLock(lock2) == true) {
System.out.println("Thread id: " + Thread.currentThread().getId() + ",
lock2 is held"); } else { System.out.println("Thread id: " +
Thread.currentThread().getId() + ", lock2 is _not_ held"); }
                try {
                    lock2.wait();
                } catch (Exception e) {
                    //System.out.println("Exception (debug:1): " +
e.getMessage());
                }
            }
        } // end of if else if
    } // end of keyPressed

    byte getNextByteFromJTextArea() {
        String s = "";
        Thread.currentThread().getId();
        synchronized(lock1) {
            //if (Thread.holdsLock(lock1) == true) {
System.out.println("Thread id: " + Thread.currentThread().getId() + ",
lock1 is held"); } else { System.out.println("Thread id: " +
Thread.currentThread().getId() + ", lock1 is _not_ held"); }
            if (inputAvailable == false) {
                try {
                    lock1.wait();
                } catch (Exception e) {
                    //System.out.println("Excpetion (debug:2): " +
e.getMessage());
                    //System.exit(1);
                } // end of try catch
            } // end of if inputAvailable

            if (newLineSent == true) {
                // send endOfInput now, all input has been prcocessed, anyone
                // waiting on lock2 should be woken up and some variables
                // should be re-initialized
                newLineSent = false;
                b = null;
                len = -1;
                indexIntoByteArray = -1;
                inputAvailable = false;
                initialCaretPosition = jta.getDocument().getLength();
                endOfInputCaretPosition = jta.getDocument().getLength();
                synchronized(lock2) {
                    //if (Thread.holdsLock(lock2) == true) {
                    //    System.out.println("lock2 is held..2..Thread
id = " + Thread.currentThread().getId());
                    //} else {
                    //    System.out.println("lock2 is ___not___
held..2..Thread id = " + Thread.currentThread().getId());
                    //}
                    lock2.notifyAll();
                    return endOfInput;
                }
            } // end of if newLineSent

            if (len == -1) { // read input
                len = endOfInputCaretPosition - initialCaretPosition;
                try {
                    s = jta.getText(initialCaretPosition, len);
                    b = s.getBytes(); // enter is still getting
processed, the text area
                                      // hasn't been updated with the
enter, so send a
                                      // newline once all bytes have been sent.
                } catch (Exception e) {
                    //System.out.println("Exception (debug:3): " +
e.getMessage());
                    if (b != null) {
                        Arrays.fill(b, (byte)(-1));
                    }
                } // end of try catch
            } // end of if len == -1

            // if control reaches here then it means that we have to send a byte
            indexIntoByteArray++;
            if (indexIntoByteArray == len) { // send newLine as all
input have been sent already
                newLineSent = true;
                return newLine;
            }
            if (b[indexIntoByteArray] == newLine) {
                newLineSent = true;
            }
            return b[indexIntoByteArray];
        } // end of synchronized block
    } // end of getNextByteFromJTextArea

    void outputToJTextArea(byte b) {
        Thread.currentThread().getId();
        synchronized(lock1) {
            char ch = (char)(b);
            String text = Character.toString(ch);
            jta.append(text);
            jta.setCaretPosition(jta.getDocument().getLength());
            initialCaretPosition = jta.getCaretPosition();
            enterAlreadyPressedEarlier = false;
        }
    } // end of outputToJTextArea

    void configureJTextAreaForInputOutput() {
        jta.addKeyListener(this);

        // remove all mouse listeners
        for (MouseListener listener : jta.getMouseListeners()) {
            //outputToJTextArea(jta, "\nRemoving mouse listener\n");
            jta.removeMouseListener(listener);
        }

        // remove all mouse motion listeners
        for (MouseMotionListener listener : jta.getMouseMotionListeners()) {
            //outputToJTextArea(jta, "\nRemoving mouse motion listener\n");
            jta.removeMouseMotionListener(listener);
        }

        // remove all mouse wheel listeners
        for (MouseWheelListener listener : jta.getMouseWheelListeners()) {
            //outputToJTextArea(jta, "\nRemoving mouse wheel listener\n");
            jta.removeMouseWheelListener(listener);
        }

        System.setIn(new InputStream() {
            @Override
            public int read() {
                // we need to sleep here because of some threading issues
                //try {
                //    Thread.sleep(1);
                //} catch (Exception e) {
                    //System.out.println("Exception (debug:4): " +
e.getMessage());
                //}
                byte b = getNextByteFromJTextArea();
                return ((int)(b));
            }
        });

        System.setOut(new PrintStream(new OutputStream() {
            @Override
            public void write(int b) {
                outputToJTextArea((byte)(b));
            }
        }));

        System.setErr(new PrintStream(new OutputStream() {
            @Override
            public void write(int b) {
                outputToJTextArea((byte)(b));
            }
        }));

    } // end of configureJTextAreaForInputOutput

    void createAndShowConsole() {
        title = "Console";
        jf = InitComponents.setupJFrameAndGet(title,
(3*screenWidth)/4, (3*screenHeight)/4);

        jta = InitComponents.setupJTextAreaAndGet("", 5000, 100, true,
true, true, false, 0, 0, 0, 0);
        jta.setBackground(Color.WHITE);
        jta.setForeground(Color.BLACK);
        jta.setCaretColor(Color.BLACK);
        jta.setFont(jta.getFont().deriveFont(13.5f));

        configureJTextAreaForInputOutput();

        jsp = InitComponents.setupScrollableJTextAreaAndGet(jta, 10,
10, (3*screenWidth)/4 - 33, (3*screenHeight)/4 - 79);
        jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jf.add(jsp);

        jmb = InitComponents.setupJMenuBarAndGet();
        jm = InitComponents.setupJMenuAndGet("Copy All to Clipboard");
        jm.setBorder(BorderFactory.createLineBorder(Color.green, 2));
        jmi = InitComponents.setupJMenuItemAndGet("Copy All to Clipboard");
        jm.add(jmi);
        jmb.add(jm);
        jmi.addActionListener(this);
        jf.setJMenuBar(jmb);

        jf.setLocationRelativeTo(null);
        jf.setVisible(true);
    } // end of createAndShowConsole

    public static void main(String[] args) {
        Console_For_JAR_Programs cfjpv2 = new Console_For_JAR_Programs();
        cfjpv2.createAndShowConsole();

        while (true) {
            try {
                BufferedReader br = null;
                String input = "";
                System.out.println();
                System.out.print("Enter some input (BufferedReader
Example) (press enter after inputting): ");
                br = new BufferedReader(new InputStreamReader(System.in));
                input = br.readLine();
                System.out.print("User input was: " + input + "\n\n");
                //System.err.println("Is this getting printed?\n\n");

                System.out.print("Enter an int, then float, then a
string (Scanner Example): ");
                Scanner sc = new Scanner(System.in);
                int num = sc.nextInt();
                float f = sc.nextFloat();
                String s = sc.nextLine();
                System.out.println("Number: " + num);
                System.out.println("Float: " + f);
                System.out.println("String: " + s);

            } catch (Exception e) {
                //System.out.println("Exception (debug:5): " + e.getMessage());
            }
        } // end of while true
    } // end of main

} // end of Console_For_JAR_Programs

class InitComponents {

    public static JFrame setupJFrameAndGet(String title, int width,
int height) {
        JFrame tmpJF = new JFrame(title);
        tmpJF.setSize(width, height);
        tmpJF.setLocationRelativeTo(null);
        tmpJF.setLayout(null);
        tmpJF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        return tmpJF;
    } // end of setupJFrameAndGet

    public static JTextArea setupJTextAreaAndGet(String text, int
rows, int columns, boolean setEditableFlag, boolean setLineWrapFlag,
boolean setWrapStyleWordFlag, boolean setBoundsFlag, int xpos, int
ypos, int width, int height) {
        JTextArea tmpJTA = new JTextArea(text, rows, columns);
        tmpJTA.setEditable(setEditableFlag);
        tmpJTA.setLineWrap(setLineWrapFlag);
        tmpJTA.setWrapStyleWord(setWrapStyleWordFlag);
        if (setBoundsFlag == true) {
            tmpJTA.setBounds(xpos, ypos, width, height);
        }
        return tmpJTA;
    } // end of setupJTextAreaAndGet

    public static JScrollPane setupScrollableJTextAreaAndGet(JTextArea
jta, int xpos, int ypos, int width, int height) {
        JScrollPane tmpJSP = new JScrollPane(jta);
        tmpJSP.setBounds(xpos, ypos, width, height);
        return tmpJSP;
    } // end of setupScrollableJTextAreaAndGet

    public static JMenuBar setupJMenuBarAndGet() {
        JMenuBar tmpJMB = new JMenuBar();
        return tmpJMB;
    } // end of setupJMenuBarAndGet

    public static JMenu setupJMenuAndGet(String text) {
        JMenu tmpJM = new JMenu(text);
        return tmpJM;
    } // end of setupJMenuAndGet

    public static JMenuItem setupJMenuItemAndGet(String text) {
        JMenuItem tmpJMI = new JMenuItem(text);
        return tmpJMI;
    } // end of setupJMenuItemAndGet

}// end of InitComponents

-------------------------------------------------------------------------------------------


More information about the core-libs-dev mailing list