Beruflich Dokumente
Kultur Dokumente
1 of 8
http://www.codeproject.com/Articles/328417/Java-Console-apps-made...
CPOL
Contents
Introduction
How to use this Java Console
How to wire up a console
Making a custom block caret
Extra! Extra! The menu system.
25/02/2016 14:24
2 of 8
http://www.codeproject.com/Articles/328417/Java-Console-apps-made...
Final comments
History
Introduction
The humble console app: I write them all the time creating one off tests to explore new coding ideas. I'll even string up quick,
menu based, test applications for testing remote device communications and command sets, where the number of commands
can grow during the product development cycle. The advantage of course, is that to grow the application I only have to add a
menu item and an event handler in the code. That is far preferable to squeezing more fields onto an already crowded Windows
Forms application. Sometimes you don't know what you have till it's gone.
I decided to tackle Java this year and get a feel for the language and tools. I usually take on a new (for me) language by
translating an application I have written into the new language and stumbling through the thorny issues as I encounter them. I
was surprised at how many of the things I took for granted in C# turned out to be rather hard to do in Java; case in point, the
console app.
The application I chose to port to Java happened to be a console based menu driven application. Porting the menu code was
fairly straightforward once I figured out how to substitute an interface and nested Java class for a C# delegate in order to obtain
callback behavior. The real headache lay in the performance of the application's menu code in an actual Windows console
instance.
Java applications utilize STDIN, STDOUT, and STDERR streams but do not own the console instance displaying the streams.
Since Java aims at a broad range of Operating Systems, it doesn't include support for clearing the screen. I tried a number of
work-a-rounds to get my application to function as intended without acceptable results.
I was about to give up when I took a different track and considered duplicating console functionality in a Java GUI widget. This
turned out to be more promising. There were quite a few examples of redirecting STDOUT and STDERR to a JtextArea but
I was unable to find one that also successfully copied keyboard input to STDIN. What I did find was quite a bit of chatter from
other developers indicating a desire for such a component.
I began to test the various code solutions and snippets that I had found and settled on one particularly robust example[^]. I
then added some code to pipe keyboard characters to STDIN, added a public clear() method, and some properties to
customize the look and feel of the console. Finally I figured out how to create a custom blinking block cursor for
JavaConsole to round things off.
25/02/2016 14:24
3 of 8
http://www.codeproject.com/Articles/328417/Java-Console-apps-made...
4 of 8
http://www.codeproject.com/Articles/328417/Java-Console-apps-made...
The first thing we need to do is to redirect STDOUT and STDERR to our JtextArea. The code class I started with achieved
this in the following manner.
1. Establish some Piped Input Streams.
private final PipedInputStream pin=new PipedInputStream();
private final PipedInputStream pin2=new PipedInputStream();
2. Hook the input streams up to the associated output streams.
PipedOutputStream pout=new PipedOutputStream(this.pin);
PipedOutputStream pout2=new PipedOutputStream(this.pin2);
3. Redirect System STDOUT and STDERR to these output streams.
System.setOut(new PrintStream(pout,true));
System.setErr(new PrintStream(pout2,true));
4. Spin up some threads to read from the Piped Input Streams.
//Declarations
private Thread reader;
private Thread reader2;
//In the class constructor
reader=new Thread(this);
reader.setDaemon(true);
reader.start();
reader2=new Thread(this);
reader2.setDaemon(true);
reader2.start();
5. Monitor STDOUT and STDERR appending the text to the JtextArea.
public synchronized void run()
{
try
{
while (Thread.currentThread()==reader)
{
try { this.wait(100);}catch(InterruptedException ie) {}
if (pin.available()!=0)
{
String input=this.readLine(pin);
textArea.append(input);
textArea.setCaretPosition(textArea.getDocument().getLength()); //DWM
02-07-2012
}
if (quit) return;
}
while (Thread.currentThread()==reader2)
{
try { this.wait(100);}catch(InterruptedException ie) {}
if (pin2.available()!=0)
{
String input=this.readLine(pin2);
textArea.append(input);
textArea.setCaretPosition(textArea.getDocument().getLength()); //DWM
02-07-2012
}
if (quit) return;
}
} catch (Exception e)
{
25/02/2016 14:24
5 of 8
http://www.codeproject.com/Articles/328417/Java-Console-apps-made...
25/02/2016 14:24
6 of 8
http://www.codeproject.com/Articles/328417/Java-Console-apps-made...
if (width <= 0)
width = getComponent().getWidth();
repaint();
repaint();
}
/* (non-Javadoc)
* @see javax.swing.text.DefaultCaret#paint(java.awt.Graphics)
*/
public void paint(Graphics g) {
JTextComponent comp = getComponent();
if (comp == null)
return;
int dot = getDot();
Rectangle r = null;
char dotChar;
try {
r = comp.modelToView(dot);
if (r == null)
return;
dotChar = comp.getText(dot, 1).charAt(0);
} catch (BadLocationException e) {
return;
}
if(Character.isWhitespace(dotChar)) dotChar = '_';
if ((x != r.x) || (y != r.y)) {
// paint() has been called directly, without a previous call to
// damage(), so do some cleanup. (This happens, for example, when
// the text component is resized.)
damage(r);
return;
}
g.setColor(comp.getCaretColor());
g.setXORMode(comp.getBackground()); // do this to draw in XOR mode
width = g.getFontMetrics().charWidth(dotChar);
if (isVisible())
g.fillRect(r.x, r.y, width, r.height);
}
}
25/02/2016 14:24
7 of 8
http://www.codeproject.com/Articles/328417/Java-Console-apps-made...
Final comments
The menu system does not work well in the standard console when used in a Java application. The version of Menu class
included here should only be used in this Java Console. This Java Console may be used anytime you want to have a console
window that is owned by your application. While it features a clear() method for clearing the screen it does not, however
handle DOS commands or provide a command prompt.
History
Feb 09, 2012: Version 1.0.0.0.
License
25/02/2016 14:24
8 of 8
http://www.codeproject.com/Articles/328417/Java-Console-apps-made...
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Share
About the Author
David MacDermot
United States
No Biography provided
SharePoint Governance: A
definitive Guide
SAPrefs - Netscape-like
Preferences Dialog
Selecione o idioma
25/02/2016 14:24