Connecting Tech Pros Worldwide Forums | Help | Site Map

Clear the Screen

Dave
Guest
 
Posts: n/a
#1: Jul 17 '05
Hi,

I have done some research, trying to Clear The Screen in java code.

The first option was the obv:
system.out.print("\n\n\n\n\n\n\n\n\n\n\n\n");

then i heard about this method:
System.out.print((char)27 + "[2J");

However, it doen't work unless "ansi.sys" is loaded and very few WinXP
user's have this.

Any help appreciated in trying to solve this problem.

Cheers,
Dave



Nathan Zumwalt
Guest
 
Posts: n/a
#2: Jul 17 '05

re: Clear the Screen


It's kind of a hack, but what about this:

Runtime.exec("cls");

This makes your application platform-dependent, but it looks like your
stated alternative does this as well.

-Nathan

"Dave" <bigdavepotnoodle*SPAM*hotmail.com> wrote in message news:<3ffd55bd$0$13355$cc9e4d1f@news-text.dial.pipex.com>...[color=blue]
> Hi,
>
> I have done some research, trying to Clear The Screen in java code.
>
> The first option was the obv:
> system.out.print("\n\n\n\n\n\n\n\n\n\n\n\n");
>
> then i heard about this method:
> System.out.print((char)27 + "[2J");
>
> However, it doen't work unless "ansi.sys" is loaded and very few WinXP
> user's have this.
>
> Any help appreciated in trying to solve this problem.
>
> Cheers,
> Dave[/color]
Denz
Guest
 
Posts: n/a
#3: Jul 17 '05

re: Clear the Screen


Ive seen this question before- with no real solution.
Surely it wouldnt have been difficult to provide a clear screen, and even
basic screen cursor positioning?
It would make text-mode java alot more useful.

"Dave" <bigdavepotnoodle*SPAM*hotmail.com> wrote in message
news:3ffd55bd$0$13355$cc9e4d1f@news-text.dial.pipex.com...[color=blue]
> Hi,
>
> I have done some research, trying to Clear The Screen in java code.
>
> The first option was the obv:
> system.out.print("\n\n\n\n\n\n\n\n\n\n\n\n");
>
> then i heard about this method:
> System.out.print((char)27 + "[2J");
>
> However, it doen't work unless "ansi.sys" is loaded and very few WinXP
> user's have this.
>
> Any help appreciated in trying to solve this problem.
>
> Cheers,
> Dave
>
>[/color]


Silvio Bierman
Guest
 
Posts: n/a
#4: Jul 17 '05

re: Clear the Screen



"Dave" <bigdavepotnoodle*SPAM*hotmail.com> wrote in message
news:3ffd55bd$0$13355$cc9e4d1f@news-text.dial.pipex.com...[color=blue]
> Hi,
>
> I have done some research, trying to Clear The Screen in java code.
>
> The first option was the obv:
> system.out.print("\n\n\n\n\n\n\n\n\n\n\n\n");
>
> then i heard about this method:
> System.out.print((char)27 + "[2J");
>
> However, it doen't work unless "ansi.sys" is loaded and very few WinXP
> user's have this.
>
> Any help appreciated in trying to solve this problem.
>
> Cheers,
> Dave
>
>[/color]

Look at jcurses on sourceforge.

Silvio Bierman


Christian
Guest
 
Posts: n/a
#5: Jul 17 '05

re: Clear the Screen


Printing out the form-feed character will clear the screen

System.out.print("\f");

Hope this helps!

Christian
Anthony Borla
Guest
 
Posts: n/a
#6: Jul 17 '05

re: Clear the Screen



"Denz" <RUBBISH@RUBBISHhotmail.com> wrote in message
news:KvlLb.1671$Wa.792@news-server.bigpond.net.au...[color=blue]
>
> Ive seen this question before- with no real solution.
> Surely it wouldnt have been difficult to provide a clear
> screen, and even basic screen cursor positioning?
>
> It would make text-mode java alot more useful.
>[/color]

Unfortunately these tasks are inherently operating system-specific, and
cannot be implemented in any standard way across platforms. Some platforms,
in fact, don't even understand the concepts of 'screen', or 'cursor', so
wouldn't even have any use for classes that implemented these abstractions.
Even the 'standard' C and C++ languages which, like Java, aim for platform
independance, do not implement such functionality.

System-specific tasks such as these may be performed via:

* 'Runtime.getRuntime().exec(...)'

* Writing Java Native Interface [JNI] routines which tap into
the relevant operating system functionality

The first option should really be seen as a 'quick and dirty' approach - it
allows you to perform certain system-specific tasks but with very little
control. A program, to be considered robust, would make no more than sparing
use of this facility. If you find you are relying on it heavily you may need
to seriously question whether Java is the ideal development tool for this
task [a scripting language (Perl, Python) might be more suitable ?], or more
of a development commitment needs be made by using JNI.

There is nothing inherently wrong with JNI except that its use helps defeat
one of Java's most important qualities - platform independance - and it
introduces 'weaknesses' into the application because program execution
occurs outside the control of the JVM, and any failure here could be
catastrophic. On the flipside, Java would be a very limited development
environment without it since it allows for the tapping into system-specific
functionality in a controlled, and efficient way.

So, to provide the facilities you seek, you need to implement suitable JNI
routines. Again, options are available:

* Tap into someone else's work. As another respondant has
already meantioned, the JCurses package provides a
reasonable suit of screen handling routines for the *NIX
and Windows-familiy platforms

* Write your own. This isn't as difficult as you might imagine,
and might be the best approach if all you require is a
few simple routines like:

- Clearing the screen
- Moving the cursor to specified positions
- Accepting input [say a single keystroke] without pressing
ENTER

A good start would be the JNI tutorial at the Sun site, and,
of course, perusal of the documentation for the system
functions implementing this functionality

Anyway, apologies for the longwindedness of the response. Hopefully, though,
some useful insights have been provided.

Cheers,

Anthony Borla


Anthony Borla
Guest
 
Posts: n/a
#7: Jul 17 '05

re: Clear the Screen



"Christian" <javauser@emailuser.net> wrote in message
news:32330a83.0401081855.47512efc@posting.google.c om...[color=blue]
>
> Printing out the form-feed character will clear the screen
>
> System.out.print("\f");
>
> Hope this helps!
>[/color]

Sadly, it doesn't do as you expect - it's behaviour various with the
platform. Nice try, though :)

Cheers,

Anthony Borla


Anthony Borla
Guest
 
Posts: n/a
#8: Jul 17 '05

re: Clear the Screen



"Nathan Zumwalt" <nathanz@hotmail.com> wrote in message
news:521673fd.0401081330.49023c22@posting.google.c om...[color=blue]
> It's kind of a hack, but what about this:
>
> Runtime.exec("cls");
>
> This makes your application platform-dependent, but it looks
> like your stated alternative does this as well.
>[/color]

Actually, this won't work. Yes, the 'cls' command is invoked, *but* it is
invoked in a new process ['command.com' or 'cmd.exe' is exected creating a
new process], and *does not* clear the Java application's console.

Cheers,

Anthony Borla


nos
Guest
 
Posts: n/a
#9: Jul 17 '05

re: Clear the Screen


But if they can implement "beep", and they do,
they should be able to implement "cls" too.

"Anthony Borla" <ajborla@bigpond.com> wrote in message
news:g0yLb.2893$Wa.1516@news-server.bigpond.net.au...[color=blue]
>
> "Denz" <RUBBISH@RUBBISHhotmail.com> wrote in message
> news:KvlLb.1671$Wa.792@news-server.bigpond.net.au...[color=green]
> >
> > Ive seen this question before- with no real solution.
> > Surely it wouldnt have been difficult to provide a clear
> > screen, and even basic screen cursor positioning?
> >
> > It would make text-mode java alot more useful.
> >[/color]
>
> Unfortunately these tasks are inherently operating system-specific, and
> cannot be implemented in any standard way across platforms. Some[/color]
platforms,[color=blue]
> in fact, don't even understand the concepts of 'screen', or 'cursor', so
> wouldn't even have any use for classes that implemented these[/color]
abstractions.[color=blue]
> Even the 'standard' C and C++ languages which, like Java, aim for platform
> independance, do not implement such functionality.
>
> System-specific tasks such as these may be performed via:
>
> * 'Runtime.getRuntime().exec(...)'
>
> * Writing Java Native Interface [JNI] routines which tap into
> the relevant operating system functionality
>
> The first option should really be seen as a 'quick and dirty' approach -[/color]
it[color=blue]
> allows you to perform certain system-specific tasks but with very little
> control. A program, to be considered robust, would make no more than[/color]
sparing[color=blue]
> use of this facility. If you find you are relying on it heavily you may[/color]
need[color=blue]
> to seriously question whether Java is the ideal development tool for this
> task [a scripting language (Perl, Python) might be more suitable ?], or[/color]
more[color=blue]
> of a development commitment needs be made by using JNI.
>
> There is nothing inherently wrong with JNI except that its use helps[/color]
defeat[color=blue]
> one of Java's most important qualities - platform independance - and it
> introduces 'weaknesses' into the application because program execution
> occurs outside the control of the JVM, and any failure here could be
> catastrophic. On the flipside, Java would be a very limited development
> environment without it since it allows for the tapping into[/color]
system-specific[color=blue]
> functionality in a controlled, and efficient way.
>
> So, to provide the facilities you seek, you need to implement suitable JNI
> routines. Again, options are available:
>
> * Tap into someone else's work. As another respondant has
> already meantioned, the JCurses package provides a
> reasonable suit of screen handling routines for the *NIX
> and Windows-familiy platforms
>
> * Write your own. This isn't as difficult as you might imagine,
> and might be the best approach if all you require is a
> few simple routines like:
>
> - Clearing the screen
> - Moving the cursor to specified positions
> - Accepting input [say a single keystroke] without pressing
> ENTER
>
> A good start would be the JNI tutorial at the Sun site, and,
> of course, perusal of the documentation for the system
> functions implementing this functionality
>
> Anyway, apologies for the longwindedness of the response. Hopefully,[/color]
though,[color=blue]
> some useful insights have been provided.
>
> Cheers,
>
> Anthony Borla
>
>[/color]


Stewart Gordon
Guest
 
Posts: n/a
#10: Jul 17 '05

re: Clear the Screen


While it was 9/1/04 3:04 pm throughout the UK, nos sprinkled little
black dots on a white screen, and they fell thus:
[color=blue]
> But if they can implement "beep", and they do,
> they should be able to implement "cls" too.[/color]
<snip top of upside-down reply>

That's because BEL is a standard ASCII character (code 7) and it's
pretty much standard that any terminal/console would render it by
beeping. OTOH, for some reason I can't imagine FF (12) doesn't
standardly mean clear screen, and nor does any other ASCII string.

But I agree that having a portable means of screen clearing would be
handy. BTW, have the rest of you people stopped telling people to try
what you can't be bothered to try for yourself?

Stewart.

--
My e-mail is valid but not my primary mailbox, aside from its being the
unfortunate victim of intensive mail-bombing at the moment. Please keep
replies on the 'group where everyone may benefit.
Jared Dykstra
Guest
 
Posts: n/a
#11: Jul 17 '05

re: Clear the Screen


"Denz" <RUBBISH@RUBBISHhotmail.com> wrote in message news:<KvlLb.1671$Wa.792@news-server.bigpond.net.au>...[color=blue]
> Ive seen this question before- with no real solution.
> Surely it wouldnt have been difficult to provide a clear screen, and even
> basic screen cursor positioning?
> It would make text-mode java alot more useful.
>[/color]

Changing the cursor positions, clearing the screen, setting console
colurs...these are all functions of the console in use, not of Java.
One of the clear screen solutions touched on this by feeding the
correct escape sequence to the console to manipulate it with the
desired effect.

As you can imagine, this is tedious and time consuming. JCurses has
already been mentioned. It is an implementation of nCurses which
determines the console type being used, and wraps escape sequences
with a nice API, independant of the type of console being used.

It should be here:
http://sourceforge.net/projects/javacurses/

However, I can't help but wonder that if you need this type of
functionality from the console, perhaps you should consider the more
standard Java/Swing and make a nice GUI interface to your application.

---
Jared Dykstra
http://www.bork.org/~jared
Denz
Guest
 
Posts: n/a
#12: Jul 17 '05

re: Clear the Screen


mmm... interesting
Just tried- it works on the Linux box, but unfortunately it doesnt on
Windows- just prints a gender symbol. darn.
Going to look at jcurses

"Christian" <javauser@emailuser.net> wrote in message
news:32330a83.0401081855.47512efc@posting.google.c om...[color=blue]
> Printing out the form-feed character will clear the screen
>
> System.out.print("\f");
>
> Hope this helps!
>
> Christian[/color]


Tony Morris
Guest
 
Posts: n/a
#13: Jul 17 '05

re: Clear the Screen


http://www.xdweb.net/~dibblego/javafaq/javafaq.html#q30

--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software


"Dave" <bigdavepotnoodle*SPAM*hotmail.com> wrote in message
news:3ffd55bd$0$13355$cc9e4d1f@news-text.dial.pipex.com...[color=blue]
> Hi,
>
> I have done some research, trying to Clear The Screen in java code.
>
> The first option was the obv:
> system.out.print("\n\n\n\n\n\n\n\n\n\n\n\n");
>
> then i heard about this method:
> System.out.print((char)27 + "[2J");
>
> However, it doen't work unless "ansi.sys" is loaded and very few WinXP
> user's have this.
>
> Any help appreciated in trying to solve this problem.
>
> Cheers,
> Dave
>
>[/color]


Anthony Borla
Guest
 
Posts: n/a
#14: Jul 17 '05

re: Clear the Screen



"Stewart Gordon" <smjg_1998@yahoo.com> wrote in message
news:btmocn$cis$1@sun-cc204.lut.ac.uk...[color=blue]
> While it was 9/1/04 3:04 pm throughout the UK, nos sprinkled little
> black dots on a white screen, and they fell thus:
>[color=green]
> > But if they can implement "beep", and they do,
> > they should be able to implement "cls" too.[/color]
> <snip top of upside-down reply>
>
> That's because BEL is a standard ASCII character
> (code 7) and it's pretty much standard that any terminal/console
> would render it by beeping.
>[/color]

Try it on an IBM mainframe - they use EBCDIC, not ASCII ;) !
[color=blue]
>
> OTOH, for some reason I can't imagine FF (12) doesn't
> standardly mean clear screen, and nor does any other
> ASCII string.
>[/color]

You'll find that 'plain vanilla' *NIX / Linux systems *do* exhibit fairly
consistent console behaviour; it's the Windows-family environments that
exhibit such inconsistencies.
[color=blue]
>
> But I agree that having a portable means of screen clearing
> would be handy.
>[/color]

Maybe a nested class could be added to 'System', containing all the
system-specific console-management routines, something like:

class System
{
...
public class Console
{
...
public static native void cls();
public static native void setCurPos(int row, int col);
public static native String inputString();
public static native double inputNumeric();
...
}
...
}

You could then do something like:

System.Console.cls();

to clear the screen, and something like:

String name;

System.Console.setCurPos(10, 35);
System.out.print("Enter your name: ");
name = System.Console.inputString();

Platforms that did not support consoles or the like could then simply have
dummy [i.e. empty] methods ?

Maybe if the Sun Java developers were lobbied by enough developers they
might consider building this functionality into the API ?

I suspect, though, they will simply leave it to developers requiring console
management support to use JNI, either directly, or by downloading a package
like JCurses.
[color=blue]
>
> BTW, have the rest of you people stopped telling people
> to try what you can't be bothered to try for yourself?
>[/color]

I think their intentions were sincere, and probably did do some testing on
their own systems. The error was in assuming that the same behaviour could
be expected on other systems. My general view is that any constructive
response is to be welcomed and appreciated.

Cheers,

Anthony Borla


nos
Guest
 
Posts: n/a
#15: Jul 17 '05

re: Clear the Screen



"Stewart Gordon" <smjg_1998@yahoo.com> wrote in message
news:btmocn$cis$1@sun-cc204.lut.ac.uk...[color=blue]
> While it was 9/1/04 3:04 pm throughout the UK, nos sprinkled little
> black dots on a white screen, and they fell thus:
>[color=green]
> > But if they can implement "beep", and they do,
> > they should be able to implement "cls" too.[/color]
> <snip top of upside-down reply>
>
> That's because BEL is a standard ASCII character (code 7) and it's
> pretty much standard that any terminal/console would render it by
> beeping. OTOH, for some reason I can't imagine FF (12) doesn't
> standardly mean clear screen, and nor does any other ASCII string.
>[/color]
I thought I would try to find out how beep works by looking in the java
sdk files but i could not figure it out. All i found was

public abstract void beep();
in java/awt/Toolkit.java
[color=blue]
> But I agree that having a portable means of screen clearing would be
> handy. BTW, have the rest of you people stopped telling people to try
> what you can't be bothered to try for yourself?
>
> Stewart.
>
> --
> My e-mail is valid but not my primary mailbox, aside from its being the
> unfortunate victim of intensive mail-bombing at the moment. Please keep
> replies on the 'group where everyone may benefit.[/color]


Denz
Guest
 
Posts: n/a
#16: Jul 17 '05

re: Clear the Screen


Something like this Console class would be great.
Ive just downloaded JCurses but so far looks like overkill- when just a few
methods like clear screen and cursor position would go such a long way...

"Anthony Borla" <ajborla@bigpond.com> wrote in message
news:yAJLb.3537$Wa.407@news-server.bigpond.net.au...[color=blue]
>
> "Stewart Gordon" <smjg_1998@yahoo.com> wrote in message
> news:btmocn$cis$1@sun-cc204.lut.ac.uk...[color=green]
> > While it was 9/1/04 3:04 pm throughout the UK, nos sprinkled little
> > black dots on a white screen, and they fell thus:
> >[color=darkred]
> > > But if they can implement "beep", and they do,
> > > they should be able to implement "cls" too.[/color]
> > <snip top of upside-down reply>
> >
> > That's because BEL is a standard ASCII character
> > (code 7) and it's pretty much standard that any terminal/console
> > would render it by beeping.
> >[/color]
>
> Try it on an IBM mainframe - they use EBCDIC, not ASCII ;) !
>[color=green]
> >
> > OTOH, for some reason I can't imagine FF (12) doesn't
> > standardly mean clear screen, and nor does any other
> > ASCII string.
> >[/color]
>
> You'll find that 'plain vanilla' *NIX / Linux systems *do* exhibit fairly
> consistent console behaviour; it's the Windows-family environments that
> exhibit such inconsistencies.
>[color=green]
> >
> > But I agree that having a portable means of screen clearing
> > would be handy.
> >[/color]
>
> Maybe a nested class could be added to 'System', containing all the
> system-specific console-management routines, something like:
>
> class System
> {
> ...
> public class Console
> {
> ...
> public static native void cls();
> public static native void setCurPos(int row, int col);
> public static native String inputString();
> public static native double inputNumeric();
> ...
> }
> ...
> }
>
> You could then do something like:
>
> System.Console.cls();
>
> to clear the screen, and something like:
>
> String name;
>
> System.Console.setCurPos(10, 35);
> System.out.print("Enter your name: ");
> name = System.Console.inputString();
>
> Platforms that did not support consoles or the like could then simply have
> dummy [i.e. empty] methods ?
>
> Maybe if the Sun Java developers were lobbied by enough developers they
> might consider building this functionality into the API ?
>
> I suspect, though, they will simply leave it to developers requiring[/color]
console[color=blue]
> management support to use JNI, either directly, or by downloading a[/color]
package[color=blue]
> like JCurses.
>[color=green]
> >
> > BTW, have the rest of you people stopped telling people
> > to try what you can't be bothered to try for yourself?
> >[/color]
>
> I think their intentions were sincere, and probably did do some testing on
> their own systems. The error was in assuming that the same behaviour could
> be expected on other systems. My general view is that any constructive
> response is to be welcomed and appreciated.
>
> Cheers,
>
> Anthony Borla
>
>[/color]


Tony Morris
Guest
 
Posts: n/a
#17: Jul 17 '05

re: Clear the Screen


It would defeat the purpose of platform-independance, since not all
platforms have the concept of a "console".

--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software

"Denz" <RUBBISH@RUBBISHhotmail.com> wrote in message
news:Hz%Lb.4898$Wa.2751@news-server.bigpond.net.au...[color=blue]
> Something like this Console class would be great.
> Ive just downloaded JCurses but so far looks like overkill- when just a[/color]
few[color=blue]
> methods like clear screen and cursor position would go such a long way...
>
> "Anthony Borla" <ajborla@bigpond.com> wrote in message
> news:yAJLb.3537$Wa.407@news-server.bigpond.net.au...[color=green]
> >
> > "Stewart Gordon" <smjg_1998@yahoo.com> wrote in message
> > news:btmocn$cis$1@sun-cc204.lut.ac.uk...[color=darkred]
> > > While it was 9/1/04 3:04 pm throughout the UK, nos sprinkled little
> > > black dots on a white screen, and they fell thus:
> > >
> > > > But if they can implement "beep", and they do,
> > > > they should be able to implement "cls" too.
> > > <snip top of upside-down reply>
> > >
> > > That's because BEL is a standard ASCII character
> > > (code 7) and it's pretty much standard that any terminal/console
> > > would render it by beeping.
> > >[/color]
> >
> > Try it on an IBM mainframe - they use EBCDIC, not ASCII ;) !
> >[color=darkred]
> > >
> > > OTOH, for some reason I can't imagine FF (12) doesn't
> > > standardly mean clear screen, and nor does any other
> > > ASCII string.
> > >[/color]
> >
> > You'll find that 'plain vanilla' *NIX / Linux systems *do* exhibit[/color][/color]
fairly[color=blue][color=green]
> > consistent console behaviour; it's the Windows-family environments that
> > exhibit such inconsistencies.
> >[color=darkred]
> > >
> > > But I agree that having a portable means of screen clearing
> > > would be handy.
> > >[/color]
> >
> > Maybe a nested class could be added to 'System', containing all the
> > system-specific console-management routines, something like:
> >
> > class System
> > {
> > ...
> > public class Console
> > {
> > ...
> > public static native void cls();
> > public static native void setCurPos(int row, int col);
> > public static native String inputString();
> > public static native double inputNumeric();
> > ...
> > }
> > ...
> > }
> >
> > You could then do something like:
> >
> > System.Console.cls();
> >
> > to clear the screen, and something like:
> >
> > String name;
> >
> > System.Console.setCurPos(10, 35);
> > System.out.print("Enter your name: ");
> > name = System.Console.inputString();
> >
> > Platforms that did not support consoles or the like could then simply[/color][/color]
have[color=blue][color=green]
> > dummy [i.e. empty] methods ?
> >
> > Maybe if the Sun Java developers were lobbied by enough developers they
> > might consider building this functionality into the API ?
> >
> > I suspect, though, they will simply leave it to developers requiring[/color]
> console[color=green]
> > management support to use JNI, either directly, or by downloading a[/color]
> package[color=green]
> > like JCurses.
> >[color=darkred]
> > >
> > > BTW, have the rest of you people stopped telling people
> > > to try what you can't be bothered to try for yourself?
> > >[/color]
> >
> > I think their intentions were sincere, and probably did do some testing[/color][/color]
on[color=blue][color=green]
> > their own systems. The error was in assuming that the same behaviour[/color][/color]
could[color=blue][color=green]
> > be expected on other systems. My general view is that any constructive
> > response is to be welcomed and appreciated.
> >
> > Cheers,
> >
> > Anthony Borla
> >
> >[/color]
>
>[/color]


Anthony Borla
Guest
 
Posts: n/a
#18: Jul 17 '05

re: Clear the Screen



"Denz" <RUBBISH@RUBBISHhotmail.com> wrote in message
news:Hz%Lb.4898$Wa.2751@news-server.bigpond.net.au...[color=blue]
>
> Something like this Console class would be
> great. Ive just downloaded JCurses but so far looks
> like overkill- when just a few methods like clear screen
> and cursor position would go such a long way...
>[/color]

I quite like JCurses, *but* I fully agree with you - too much functionality.
Having thought about it a little more, all that is minimally required:

* Console information accessor [e.g. get max lines, columns, etc]
* A clear screen method
* Cursor position set / get methods
* A character read method i.e. accept a sing;le character
without needing to press ENTER [could be designed to
also accept 'special' keys like F1, though best, I think, to
keep it simple and ignore non-standard keys]

with other functionality such as:

* A string read method [e.g. up to X characters in
length without pressing ENTER; ESC could abort
input process; extend to not echo typed keys so
as to allow password-type input]
* Support character atributes like colour etc
* Cursor hide / unhide

would be purely optional.

It is easy enough to make a start with this by creating a Console class:

public class Console
{
public static native int getMaxRows();
public static native int getMaxCols();

public static native void cls();

public static native int getCurRow();
public static native int getCurCol();

public static native void setCurPos(int row, int col);

public static native char inputKey(int[] keyData);
}

Below you will find a JNI implementation for such a class. Since we're
dealing with JNI such code is strictly system-specific, so will work only on
the targeted platform, in this case, Win32 i.e. it should run ok on all
Win9x and up platforms.

The included files:

* A batch file called 'mkConsole.bat' used to document / generate
the steps in creating the native code

* The Java source files:

- Console.java, the Java interface to the JNI routines
- TestConsole.java, a minimal test harness for these routines

* C++ source files:

- Console.h
- ConsoleImp.cpp

Assuming you use a Win32 system [I hope so :)] you will need to provide:

* C++ Compiler capable of generating Win32 DLL's
* Suitable 'make' file for this compiler

The code was tested with Borland 5.5.1 and J2SDK 1.4.1, and appears to work
ok. The code is provided 'as is' for educational purposes. It goes without
saying that I accept no reponsibility for this code's use by others.

It may be worthwhile for anyone contemplating the use of this code to first:

* Read the JNI tutorial on the Sun site
* Consult Win32 documentation regarding 'console applications'
for some insight into the code

Sadly, the codes its provision alienates a substantial segment of the Java
community. It is hoped, though, that other may be motivated to implement
this, or similar functionality, for their own platform, and - hopefully -
post it. It would be interesting to see how these simple tasks are performed
on other platforms.

I hope this helps.

Anthony Borla

// FILE: mkConsole.bat ========================
@echo off

:: Compile JAVA Source containing Native Method calls
javac -deprecation TestConsole.java

:: Create .h header from Java Source
javah -jni TestConsole

:: Implement Native Method (C++) and create a .DLL
:: 1) Compile ConsoleImp.cpp
:: 2) Create ConsoleImp.dll
:: *** You need to implement this for your compiler ***
make -fConsoleImp.mak

:: Execute Java Program which calls Native Method
:: 1) Loads ConsoleImp.dll
:: 2) Calls 'Console' native method
java TestConsole


// FILE: Console.java ========================
public class Console
{
// Load DLL
static
{
try
{
System.loadLibrary("ConsoleImp");
}

catch (UnsatisfiedLinkError e)
{
System.out.println("Could not locate DLL");
System.exit(1);
}
}

public static native int getMaxRows();
public static native int getMaxCols();

public static native void cls();

public static native int getCurRow();
public static native int getCurCol();

public static native void setCurPos(int row, int col);

public static native char inputKey(int[] keyData);
}

// FILE: TestConsole.java =====================
public class TestConsole
{
public static void main(String[] args)
{
System.out.println("Start...");

Console.cls();

System.out.println(Console.getMaxRows());
System.out.println(Console.getMaxCols());

Console.setCurPos(10, 5);

System.out.println(Console.getCurRow());
System.out.println(Console.getCurCol());

char key;
int[] keyData = new int[]{0, 0};

System.out.print("Press a key: ");
key = Console.inputKey(keyData);

System.out.print(key + ", " + (int)key);

if (key == 0)
System.out.println("A special key was pressed");

System.out.println("Key Code: " + keyData[0]);
System.out.println("Key Scan: " + keyData[1]);

System.out.println("End...");
}
}


// FILE: Console.h ========================
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Console */

#ifndef _Included_Console
#define _Included_Console
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Console
* Method: getMaxRows
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_Console_getMaxRows
(JNIEnv *, jclass);

/*
* Class: Console
* Method: getMaxCols
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_Console_getMaxCols
(JNIEnv *, jclass);

/*
* Class: Console
* Method: cls
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_Console_cls
(JNIEnv *, jclass);

/*
* Class: Console
* Method: getCurRow
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_Console_getCurRow
(JNIEnv *, jclass);

/*
* Class: Console
* Method: getCurCol
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_Console_getCurCol
(JNIEnv *, jclass);

/*
* Class: Console
* Method: setCurPos
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_Console_setCurPos
(JNIEnv *, jclass, jint, jint);

/*
* Class: Console
* Method: inputKey
* Signature: ([I)C
*/
JNIEXPORT jchar JNICALL Java_Console_inputKey
(JNIEnv *, jclass, jintArray);

#ifdef __cplusplus
}
#endif
#endif

// FILE: ConsoleImp.cpp ======================
// *** Plaform-specific Header(s)
// *** Here is for Win32
#include <windows.h>
// ***

#include <jni.h>
#include "Console.h"

JNIEXPORT jint JNICALL Java_Console_getMaxRows(JNIEnv *, jclass)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;

::GetConsoleScreenBufferInfo(
::GetStdHandle(STD_OUTPUT_HANDLE), &csbi);

return csbi.dwSize.Y;
}

JNIEXPORT jint JNICALL Java_Console_getMaxCols(JNIEnv *, jclass)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;

::GetConsoleScreenBufferInfo(
::GetStdHandle(STD_OUTPUT_HANDLE), &csbi);

return csbi.dwSize.X;
}

JNIEXPORT void JNICALL Java_Console_cls(JNIEnv *, jclass)
{
COORD coordScreen = { 0, 0 };
CONSOLE_SCREEN_BUFFER_INFO csbi;

DWORD cCharsWritten;
DWORD dwConSize;

HANDLE hConsole = ::GetStdHandle(STD_OUTPUT_HANDLE);

// Get the number of character cells in the current buffer
::GetConsoleScreenBufferInfo(hConsole, &csbi);

// Compute Console size
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;

// Fill the entire screen with blanks
::FillConsoleOutputCharacter(hConsole, (TCHAR) ' ',
dwConSize, coordScreen, &cCharsWritten);

// Get the current text attribute
::GetConsoleScreenBufferInfo(hConsole, &csbi);

// Set the buffer's attributes accordingly
::FillConsoleOutputAttribute(hConsole, csbi.wAttributes,
dwConSize, coordScreen, &cCharsWritten);

// Home the cursor at (0, 0)
::SetConsoleCursorPosition(hConsole, coordScreen);

return;
}

JNIEXPORT jint JNICALL Java_Console_getCurRow(JNIEnv *, jclass)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;

::GetConsoleScreenBufferInfo(
::GetStdHandle(STD_OUTPUT_HANDLE), &csbi);

return csbi.dwCursorPosition.Y;
}

JNIEXPORT jint JNICALL Java_Console_getCurCol(JNIEnv *, jclass)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;

::GetConsoleScreenBufferInfo(
::GetStdHandle(STD_OUTPUT_HANDLE), &csbi);

return csbi.dwCursorPosition.X;
}

JNIEXPORT void JNICALL Java_Console_setCurPos(JNIEnv* env, jclass obj, jint
row, jint col)
{
COORD coord; coord.X = col; coord.Y = row;

::SetConsoleCursorPosition(
::GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

JNIEXPORT jchar JNICALL Java_Console_inputKey(JNIEnv* env, jclass obj,
jintArray keyData)
{
const char NUL = '\0',
ESC = '\x1B';

const int TIMEOUT_MILLIS = 1000;

jsize len = env->GetArrayLength(keyData);
jint* keyData_ = env->GetIntArrayElements(keyData, 0);

DWORD omode, nmode; DWORD itemsRead = 0;
INPUT_RECORD ir;
char inputBuffer[4] = { NUL };

HANDLE hConsole = ::GetStdHandle(STD_INPUT_HANDLE);

::GetConsoleMode(hConsole, &omode);
nmode = omode & ~ENABLE_LINE_INPUT & ~ENABLE_ECHO_INPUT;
::SetConsoleMode(hConsole, nmode);

do
{
::FlushConsoleInputBuffer(hConsole);
::WaitForSingleObject(hConsole, TIMEOUT_MILLIS);
::PeekConsoleInput(hConsole, &ir, 1, &itemsRead);

if (itemsRead > 0)
{
if (ir.EventType == KEY_EVENT)
{
// Discard all non-keydown events
if (ir.Event.KeyEvent.bKeyDown == FALSE)
{
::ReadConsoleInput(hConsole, &ir, 1, &itemsRead);
continue;
}

// Got ASCII key, so extract, flush, and exit
if (ir.Event.KeyEvent.uChar.AsciiChar != NUL)
{
if (ir.Event.KeyEvent.uChar.AsciiChar == ESC)
{
::ReadConsoleInput(hConsole, &ir, 1, &itemsRead);
inputBuffer[0] = ESC;
}
else
::ReadFile(hConsole, inputBuffer, 1, &itemsRead, NULL);

keyData_[0] = ir.Event.KeyEvent.wVirtualKeyCode;
keyData_[1] = ir.Event.KeyEvent.wVirtualScanCode;

break;
}

// Got 'special' key, so determine appropriate actions
switch (ir.Event.KeyEvent.dwControlKeyState)
{
case ENHANCED_KEY:
::ReadConsoleInput(hConsole, &ir, 1, &itemsRead);
break;

case LEFT_ALT_PRESSED: case LEFT_CTRL_PRESSED:
case RIGHT_ALT_PRESSED: case RIGHT_CTRL_PRESSED:
::ReadFile(hConsole, inputBuffer, 1, &itemsRead, NULL);
inputBuffer[0] = NUL;
break;

case SHIFT_PRESSED:
::ReadFile(hConsole, inputBuffer, 1, &itemsRead, NULL);
break;
}

keyData_[0] = ir.Event.KeyEvent.wVirtualKeyCode;
keyData_[1] = ir.Event.KeyEvent.wVirtualScanCode;
}
else
{
// Not Key Event, so just extract and discard
::ReadConsoleInput(hConsole, &ir, 1, &itemsRead);
}
}

} while (itemsRead == 0);

::FlushConsoleInputBuffer(hConsole);
::SetConsoleMode(hConsole, omode);

env->ReleaseIntArrayElements(keyData, keyData_, 0);

return inputBuffer[0];
}



Russell Allen
Guest
 
Posts: n/a
#19: Jul 17 '05

re: Clear the Screen


Can anyone help me with this one? I am looking for a makefile to fill
in for the one mentioned in the previous posting for so I can compile
this all myself. I have the Borland v5.5 command line tools. I have no
clue where to go here. I tried skipping the 'makefile' idea and tried
using following syntax and it compiled but I don't think it compiled
the way it supposed to (windows freaked when I tried to use the DLL)

cpp32 -I\j2sdk1.4.2_03\include -I\j2sdk1.4.2_03\include\win
32 -I\Borland\BCC55\Include -oConsoleImp.dll ConsoleImp.cpp

So I am assuming I am missing a lot here. Any help would be
appreciated.

Russ

"Anthony Borla" <ajborla@bigpond.com> wrote in message news:<UOcMb.6483$Wa.2950@news-server.bigpond.net.au>...[color=blue]
> "Denz" <RUBBISH@RUBBISHhotmail.com> wrote in message
> news:Hz%Lb.4898$Wa.2751@news-server.bigpond.net.au...[color=green]
> >
> > Something like this Console class would be
> > great. Ive just downloaded JCurses but so far looks
> > like overkill- when just a few methods like clear screen
> > and cursor position would go such a long way...
> >[/color]
>
> I quite like JCurses, *but* I fully agree with you - too much functionality.
> Having thought about it a little more, all that is minimally required:
>
> * Console information accessor [e.g. get max lines, columns, etc]
> * A clear screen method
> * Cursor position set / get methods
> * A character read method i.e. accept a sing;le character
> without needing to press ENTER [could be designed to
> also accept 'special' keys like F1, though best, I think, to
> keep it simple and ignore non-standard keys]
>
> with other functionality such as:
>
> * A string read method [e.g. up to X characters in
> length without pressing ENTER; ESC could abort
> input process; extend to not echo typed keys so
> as to allow password-type input]
> * Support character atributes like colour etc
> * Cursor hide / unhide
>
> would be purely optional.
>
> It is easy enough to make a start with this by creating a Console class:
>
> public class Console
> {
> public static native int getMaxRows();
> public static native int getMaxCols();
>
> public static native void cls();
>
> public static native int getCurRow();
> public static native int getCurCol();
>
> public static native void setCurPos(int row, int col);
>
> public static native char inputKey(int[] keyData);
> }
>
> Below you will find a JNI implementation for such a class. Since we're
> dealing with JNI such code is strictly system-specific, so will work only on
> the targeted platform, in this case, Win32 i.e. it should run ok on all
> Win9x and up platforms.
>
> The included files:
>
> * A batch file called 'mkConsole.bat' used to document / generate
> the steps in creating the native code
>
> * The Java source files:
>
> - Console.java, the Java interface to the JNI routines
> - TestConsole.java, a minimal test harness for these routines
>
> * C++ source files:
>
> - Console.h
> - ConsoleImp.cpp
>
> Assuming you use a Win32 system [I hope so :)] you will need to provide:
>
> * C++ Compiler capable of generating Win32 DLL's
> * Suitable 'make' file for this compiler
>
> The code was tested with Borland 5.5.1 and J2SDK 1.4.1, and appears to work
> ok. The code is provided 'as is' for educational purposes. It goes without
> saying that I accept no reponsibility for this code's use by others.
>
> It may be worthwhile for anyone contemplating the use of this code to first:
>
> * Read the JNI tutorial on the Sun site
> * Consult Win32 documentation regarding 'console applications'
> for some insight into the code
>
> Sadly, the codes its provision alienates a substantial segment of the Java
> community. It is hoped, though, that other may be motivated to implement
> this, or similar functionality, for their own platform, and - hopefully -
> post it. It would be interesting to see how these simple tasks are performed
> on other platforms.
>
> I hope this helps.
>
> Anthony Borla
>
> // FILE: mkConsole.bat ========================
> @echo off
>
> :: Compile JAVA Source containing Native Method calls
> javac -deprecation TestConsole.java
>
> :: Create .h header from Java Source
> javah -jni TestConsole
>
> :: Implement Native Method (C++) and create a .DLL
> :: 1) Compile ConsoleImp.cpp
> :: 2) Create ConsoleImp.dll
> :: *** You need to implement this for your compiler ***
> make -fConsoleImp.mak
>
> :: Execute Java Program which calls Native Method
> :: 1) Loads ConsoleImp.dll
> :: 2) Calls 'Console' native method
> java TestConsole
>
>
> // FILE: Console.java ========================
> public class Console
> {
> // Load DLL
> static
> {
> try
> {
> System.loadLibrary("ConsoleImp");
> }
>
> catch (UnsatisfiedLinkError e)
> {
> System.out.println("Could not locate DLL");
> System.exit(1);
> }
> }
>
> public static native int getMaxRows();
> public static native int getMaxCols();
>
> public static native void cls();
>
> public static native int getCurRow();
> public static native int getCurCol();
>
> public static native void setCurPos(int row, int col);
>
> public static native char inputKey(int[] keyData);
> }
>
> // FILE: TestConsole.java =====================
> public class TestConsole
> {
> public static void main(String[] args)
> {
> System.out.println("Start...");
>
> Console.cls();
>
> System.out.println(Console.getMaxRows());
> System.out.println(Console.getMaxCols());
>
> Console.setCurPos(10, 5);
>
> System.out.println(Console.getCurRow());
> System.out.println(Console.getCurCol());
>
> char key;
> int[] keyData = new int[]{0, 0};
>
> System.out.print("Press a key: ");
> key = Console.inputKey(keyData);
>
> System.out.print(key + ", " + (int)key);
>
> if (key == 0)
> System.out.println("A special key was pressed");
>
> System.out.println("Key Code: " + keyData[0]);
> System.out.println("Key Scan: " + keyData[1]);
>
> System.out.println("End...");
> }
> }
>
>
> // FILE: Console.h ========================
> /* DO NOT EDIT THIS FILE - it is machine generated */
> #include <jni.h>
> /* Header for class Console */
>
> #ifndef _Included_Console
> #define _Included_Console
> #ifdef __cplusplus
> extern "C" {
> #endif
> /*
> * Class: Console
> * Method: getMaxRows
> * Signature: ()I
> */
> JNIEXPORT jint JNICALL Java_Console_getMaxRows
> (JNIEnv *, jclass);
>
> /*
> * Class: Console
> * Method: getMaxCols
> * Signature: ()I
> */
> JNIEXPORT jint JNICALL Java_Console_getMaxCols
> (JNIEnv *, jclass);
>
> /*
> * Class: Console
> * Method: cls
> * Signature: ()V
> */
> JNIEXPORT void JNICALL Java_Console_cls
> (JNIEnv *, jclass);
>
> /*
> * Class: Console
> * Method: getCurRow
> * Signature: ()I
> */
> JNIEXPORT jint JNICALL Java_Console_getCurRow
> (JNIEnv *, jclass);
>
> /*
> * Class: Console
> * Method: getCurCol
> * Signature: ()I
> */
> JNIEXPORT jint JNICALL Java_Console_getCurCol
> (JNIEnv *, jclass);
>
> /*
> * Class: Console
> * Method: setCurPos
> * Signature: (II)V
> */
> JNIEXPORT void JNICALL Java_Console_setCurPos
> (JNIEnv *, jclass, jint, jint);
>
> /*
> * Class: Console
> * Method: inputKey
> * Signature: ([I)C
> */
> JNIEXPORT jchar JNICALL Java_Console_inputKey
> (JNIEnv *, jclass, jintArray);
>
> #ifdef __cplusplus
> }
> #endif
> #endif
>
> // FILE: ConsoleImp.cpp ======================
> // *** Plaform-specific Header(s)
> // *** Here is for Win32
> #include <windows.h>
> // ***
>
> #include <jni.h>
> #include "Console.h"
>
> JNIEXPORT jint JNICALL Java_Console_getMaxRows(JNIEnv *, jclass)
> {
> CONSOLE_SCREEN_BUFFER_INFO csbi;
>
> ::GetConsoleScreenBufferInfo(
> ::GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
>
> return csbi.dwSize.Y;
> }
>
> JNIEXPORT jint JNICALL Java_Console_getMaxCols(JNIEnv *, jclass)
> {
> CONSOLE_SCREEN_BUFFER_INFO csbi;
>
> ::GetConsoleScreenBufferInfo(
> ::GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
>
> return csbi.dwSize.X;
> }
>
> JNIEXPORT void JNICALL Java_Console_cls(JNIEnv *, jclass)
> {
> COORD coordScreen = { 0, 0 };
> CONSOLE_SCREEN_BUFFER_INFO csbi;
>
> DWORD cCharsWritten;
> DWORD dwConSize;
>
> HANDLE hConsole = ::GetStdHandle(STD_OUTPUT_HANDLE);
>
> // Get the number of character cells in the current buffer
> ::GetConsoleScreenBufferInfo(hConsole, &csbi);
>
> // Compute Console size
> dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
>
> // Fill the entire screen with blanks
> ::FillConsoleOutputCharacter(hConsole, (TCHAR) ' ',
> dwConSize, coordScreen, &cCharsWritten);
>
> // Get the current text attribute
> ::GetConsoleScreenBufferInfo(hConsole, &csbi);
>
> // Set the buffer's attributes accordingly
> ::FillConsoleOutputAttribute(hConsole, csbi.wAttributes,
> dwConSize, coordScreen, &cCharsWritten);
>
> // Home the cursor at (0, 0)
> ::SetConsoleCursorPosition(hConsole, coordScreen);
>
> return;
> }
>
> JNIEXPORT jint JNICALL Java_Console_getCurRow(JNIEnv *, jclass)
> {
> CONSOLE_SCREEN_BUFFER_INFO csbi;
>
> ::GetConsoleScreenBufferInfo(
> ::GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
>
> return csbi.dwCursorPosition.Y;
> }
>
> JNIEXPORT jint JNICALL Java_Console_getCurCol(JNIEnv *, jclass)
> {
> CONSOLE_SCREEN_BUFFER_INFO csbi;
>
> ::GetConsoleScreenBufferInfo(
> ::GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
>
> return csbi.dwCursorPosition.X;
> }
>
> JNIEXPORT void JNICALL Java_Console_setCurPos(JNIEnv* env, jclass obj, jint
> row, jint col)
> {
> COORD coord; coord.X = col; coord.Y = row;
>
> ::SetConsoleCursorPosition(
> ::GetStdHandle(STD_OUTPUT_HANDLE), coord);
> }
>
> JNIEXPORT jchar JNICALL Java_Console_inputKey(JNIEnv* env, jclass obj,
> jintArray keyData)
> {
> const char NUL = '\0',
> ESC = '\x1B';
>
> const int TIMEOUT_MILLIS = 1000;
>
> jsize len = env->GetArrayLength(keyData);
> jint* keyData_ = env->GetIntArrayElements(keyData, 0);
>
> DWORD omode, nmode; DWORD itemsRead = 0;
> INPUT_RECORD ir;
> char inputBuffer[4] = { NUL };
>
> HANDLE hConsole = ::GetStdHandle(STD_INPUT_HANDLE);
>
> ::GetConsoleMode(hConsole, &omode);
> nmode = omode & ~ENABLE_LINE_INPUT & ~ENABLE_ECHO_INPUT;
> ::SetConsoleMode(hConsole, nmode);
>
> do
> {
> ::FlushConsoleInputBuffer(hConsole);
> ::WaitForSingleObject(hConsole, TIMEOUT_MILLIS);
> ::PeekConsoleInput(hConsole, &ir, 1, &itemsRead);
>
> if (itemsRead > 0)
> {
> if (ir.EventType == KEY_EVENT)
> {
> // Discard all non-keydown events
> if (ir.Event.KeyEvent.bKeyDown == FALSE)
> {
> ::ReadConsoleInput(hConsole, &ir, 1, &itemsRead);
> continue;
> }
>
> // Got ASCII key, so extract, flush, and exit
> if (ir.Event.KeyEvent.uChar.AsciiChar != NUL)
> {
> if (ir.Event.KeyEvent.uChar.AsciiChar == ESC)
> {
> ::ReadConsoleInput(hConsole, &ir, 1, &itemsRead);
> inputBuffer[0] = ESC;
> }
> else
> ::ReadFile(hConsole, inputBuffer, 1, &itemsRead, NULL);
>
> keyData_[0] = ir.Event.KeyEvent.wVirtualKeyCode;
> keyData_[1] = ir.Event.KeyEvent.wVirtualScanCode;
>
> break;
> }
>
> // Got 'special' key, so determine appropriate actions
> switch (ir.Event.KeyEvent.dwControlKeyState)
> {
> case ENHANCED_KEY:
> ::ReadConsoleInput(hConsole, &ir, 1, &itemsRead);
> break;
>
> case LEFT_ALT_PRESSED: case LEFT_CTRL_PRESSED:
> case RIGHT_ALT_PRESSED: case RIGHT_CTRL_PRESSED:
> ::ReadFile(hConsole, inputBuffer, 1, &itemsRead, NULL);
> inputBuffer[0] = NUL;
> break;
>
> case SHIFT_PRESSED:
> ::ReadFile(hConsole, inputBuffer, 1, &itemsRead, NULL);
> break;
> }
>
> keyData_[0] = ir.Event.KeyEvent.wVirtualKeyCode;
> keyData_[1] = ir.Event.KeyEvent.wVirtualScanCode;
> }
> else
> {
> // Not Key Event, so just extract and discard
> ::ReadConsoleInput(hConsole, &ir, 1, &itemsRead);
> }
> }
>
> } while (itemsRead == 0);
>
> ::FlushConsoleInputBuffer(hConsole);
> ::SetConsoleMode(hConsole, omode);
>
> env->ReleaseIntArrayElements(keyData, keyData_, 0);
>
> return inputBuffer[0];
> }[/color]
Roman
Guest
 
Posts: n/a
#20: Jul 17 '05

re: Clear the Screen


I know from some experience with Linux, the native code you are making into
your library must be position independent.
So when you are making your shared library you need to compile it with the
correct switches.

On Linux you would do something of this fashion
http://www.javaworld.com/javaworld/j...javatip23.html
Look in the "Create a shared library" section of this article.

For Linux this is how it works
http://www.tldp.org/HOWTO/Program-Li...libraries.html

If the library is compiled without being position independent then when you
run it, strange things may happen or it may crap out completely.

Roman.

"Russell Allen" <whoopass069@hotmail.com> wrote in message
news:2c1e3e08.0401281915.8a1241@posting.google.com ...[color=blue]
> Can anyone help me with this one? I am looking for a makefile to fill
> in for the one mentioned in the previous posting for so I can compile
> this all myself. I have the Borland v5.5 command line tools. I have no
> clue where to go here. I tried skipping the 'makefile' idea and tried
> using following syntax and it compiled but I don't think it compiled
> the way it supposed to (windows freaked when I tried to use the DLL)
>
> cpp32 -I\j2sdk1.4.2_03\include -I\j2sdk1.4.2_03\include\win
> 32 -I\Borland\BCC55\Include -oConsoleImp.dll ConsoleImp.cpp
>
> So I am assuming I am missing a lot here. Any help would be
> appreciated.
>
> Russ
>
> "Anthony Borla" <ajborla@bigpond.com> wrote in message[/color]
news:<UOcMb.6483$Wa.2950@news-server.bigpond.net.au>...[color=blue][color=green]
> > "Denz" <RUBBISH@RUBBISHhotmail.com> wrote in message
> > news:Hz%Lb.4898$Wa.2751@news-server.bigpond.net.au...[color=darkred]
> > >
> > > Something like this Console class would be
> > > great. Ive just downloaded JCurses but so far looks
> > > like overkill- when just a few methods like clear screen
> > > and cursor position would go such a long way...
> > >[/color]
> >
> > I quite like JCurses, *but* I fully agree with you - too much[/color][/color]
functionality.[color=blue][color=green]
> > Having thought about it a little more, all that is minimally required:
> >
> > * Console information accessor [e.g. get max lines, columns, etc]
> > * A clear screen method
> > * Cursor position set / get methods
> > * A character read method i.e. accept a sing;le character
> > without needing to press ENTER [could be designed to
> > also accept 'special' keys like F1, though best, I think, to
> > keep it simple and ignore non-standard keys]
> >
> > with other functionality such as:
> >
> > * A string read method [e.g. up to X characters in
> > length without pressing ENTER; ESC could abort
> > input process; extend to not echo typed keys so
> > as to allow password-type input]
> > * Support character atributes like colour etc
> > * Cursor hide / unhide
> >
> > would be purely optional.
> >
> > It is easy enough to make a start with this by creating a Console class:
> >
> > public class Console
> > {
> > public static native int getMaxRows();
> > public static native int getMaxCols();
> >
> > public static native void cls();
> >
> > public static native int getCurRow();
> > public static native int getCurCol();
> >
> > public static native void setCurPos(int row, int col);
> >
> > public static native char inputKey(int[] keyData);
> > }
> >
> > Below you will find a JNI implementation for such a class. Since we're
> > dealing with JNI such code is strictly system-specific, so will work[/color][/color]
only on[color=blue][color=green]
> > the targeted platform, in this case, Win32 i.e. it should run ok on all
> > Win9x and up platforms.
> >
> > The included files:
> >
> > * A batch file called 'mkConsole.bat' used to document / generate
> > the steps in creating the native code
> >
> > * The Java source files:
> >
> > - Console.java, the Java interface to the JNI routines
> > - TestConsole.java, a minimal test harness for these routines
> >
> > * C++ source files:
> >
> > - Console.h
> > - ConsoleImp.cpp
> >
> > Assuming you use a Win32 system [I hope so :)] you will need to provide:
> >
> > * C++ Compiler capable of generating Win32 DLL's
> > * Suitable 'make' file for this compiler
> >
> > The code was tested with Borland 5.5.1 and J2SDK 1.4.1, and appears to[/color][/color]
work[color=blue][color=green]
> > ok. The code is provided 'as is' for educational purposes. It goes[/color][/color]
without[color=blue][color=green]
> > saying that I accept no reponsibility for this code's use by others.
> >
> > It may be worthwhile for anyone contemplating the use of this code to[/color][/color]
first:[color=blue][color=green]
> >
> > * Read the JNI tutorial on the Sun site
> > * Consult Win32 documentation regarding 'console applications'
> > for some insight into the code
> >
> > Sadly, the codes its provision alienates a substantial segment of the[/color][/color]
Java[color=blue][color=green]
> > community. It is hoped, though, that other may be motivated to implement
> > this, or similar functionality, for their own platform, and -[/color][/color]
hopefully -[color=blue][color=green]
> > post it. It would be interesting to see how these simple tasks are[/color][/color]
performed[color=blue][color=green]
> > on other platforms.
> >
> > I hope this helps.
> >
> > Anthony Borla
> >
> > // FILE: mkConsole.bat ========================
> > @echo off
> >
> > :: Compile JAVA Source containing Native Method calls
> > javac -deprecation TestConsole.java
> >
> > :: Create .h header from Java Source
> > javah -jni TestConsole
> >
> > :: Implement Native Method (C++) and create a .DLL
> > :: 1) Compile ConsoleImp.cpp
> > :: 2) Create ConsoleImp.dll
> > :: *** You need to implement this for your compiler ***
> > make -fConsoleImp.mak
> >
> > :: Execute Java Program which calls Native Method
> > :: 1) Loads ConsoleImp.dll
> > :: 2) Calls 'Console' native method
> > java TestConsole
> >
> >
> > // FILE: Console.java ========================
> > public class Console
> > {
> > // Load DLL
> > static
> > {
> > try
> > {
> > System.loadLibrary("ConsoleImp");
> > }
> >
> > catch (UnsatisfiedLinkError e)
> > {
> > System.out.println("Could not locate DLL");
> > System.exit(1);
> > }
> > }
> >
> > public static native int getMaxRows();
> > public static native int getMaxCols();
> >
> > public static native void cls();
> >
> > public static native int getCurRow();
> > public static native int getCurCol();
> >
> > public static native void setCurPos(int row, int col);
> >
> > public static native char inputKey(int[] keyData);
> > }
> >
> > // FILE: TestConsole.java =====================
> > public class TestConsole
> > {
> > public static void main(String[] args)
> > {
> > System.out.println("Start...");
> >
> > Console.cls();
> >
> > System.out.println(Console.getMaxRows());
> > System.out.println(Console.getMaxCols());
> >
> > Console.setCurPos(10, 5);
> >
> > System.out.println(Console.getCurRow());
> > System.out.println(Console.getCurCol());
> >
> > char key;
> > int[] keyData = new int[]{0, 0};
> >
> > System.out.print("Press a key: ");
> > key = Console.inputKey(keyData);
> >
> > System.out.print(key + ", " + (int)key);
> >
> > if (key == 0)
> > System.out.println("A special key was pressed");
> >
> > System.out.println("Key Code: " + keyData[0]);
> > System.out.println("Key Scan: " + keyData[1]);
> >
> > System.out.println("End...");
> > }
> > }
> >
> >
> > // FILE: Console.h ========================
> > /* DO NOT EDIT THIS FILE - it is machine generated */
> > #include <jni.h>
> > /* Header for class Console */
> >
> > #ifndef _Included_Console
> > #define _Included_Console
> > #ifdef __cplusplus
> > extern "C" {
> > #endif
> > /*
> > * Class: Console
> > * Method: getMaxRows
> > * Signature: ()I
> > */
> > JNIEXPORT jint JNICALL Java_Console_getMaxRows
> > (JNIEnv *, jclass);
> >
> > /*
> > * Class: Console
> > * Method: getMaxCols
> > * Signature: ()I
> > */
> > JNIEXPORT jint JNICALL Java_Console_getMaxCols
> > (JNIEnv *, jclass);
> >
> > /*
> > * Class: Console
> > * Method: cls
> > * Signature: ()V
> > */
> > JNIEXPORT void JNICALL Java_Console_cls
> > (JNIEnv *, jclass);
> >
> > /*
> > * Class: Console
> > * Method: getCurRow
> > * Signature: ()I
> > */
> > JNIEXPORT jint JNICALL Java_Console_getCurRow
> > (JNIEnv *, jclass);
> >
> > /*
> > * Class: Console
> > * Method: getCurCol
> > * Signature: ()I
> > */
> > JNIEXPORT jint JNICALL Java_Console_getCurCol
> > (JNIEnv *, jclass);
> >
> > /*
> > * Class: Console
> > * Method: setCurPos
> > * Signature: (II)V
> > */
> > JNIEXPORT void JNICALL Java_Console_setCurPos
> > (JNIEnv *, jclass, jint, jint);
> >
> > /*
> > * Class: Console
> > * Method: inputKey
> > * Signature: ([I)C
> > */
> > JNIEXPORT jchar JNICALL Java_Console_inputKey
> > (JNIEnv *, jclass, jintArray);
> >
> > #ifdef __cplusplus
> > }
> > #endif
> > #endif
> >
> > // FILE: ConsoleImp.cpp ======================
> > // *** Plaform-specific Header(s)
> > // *** Here is for Win32
> > #include <windows.h>
> > // ***
> >
> > #include <jni.h>
> > #include "Console.h"
> >
> > JNIEXPORT jint JNICALL Java_Console_getMaxRows(JNIEnv *, jclass)
> > {
> > CONSOLE_SCREEN_BUFFER_INFO csbi;
> >
> > ::GetConsoleScreenBufferInfo(
> > ::GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
> >
> > return csbi.dwSize.Y;
> > }
> >
> > JNIEXPORT jint JNICALL Java_Console_getMaxCols(JNIEnv *, jclass)
> > {
> > CONSOLE_SCREEN_BUFFER_INFO csbi;
> >
> > ::GetConsoleScreenBufferInfo(
> > ::GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
> >
> > return csbi.dwSize.X;
> > }
> >
> > JNIEXPORT void JNICALL Java_Console_cls(JNIEnv *, jclass)
> > {
> > COORD coordScreen = { 0, 0 };
> > CONSOLE_SCREEN_BUFFER_INFO csbi;
> >
> > DWORD cCharsWritten;
> > DWORD dwConSize;
> >
> > HANDLE hConsole = ::GetStdHandle(STD_OUTPUT_HANDLE);
> >
> > // Get the number of character cells in the current buffer
> > ::GetConsoleScreenBufferInfo(hConsole, &csbi);
> >
> > // Compute Console size
> > dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
> >
> > // Fill the entire screen with blanks
> > ::FillConsoleOutputCharacter(hConsole, (TCHAR) ' ',
> > dwConSize, coordScreen, &cCharsWritten);
> >
> > // Get the current text attribute
> > ::GetConsoleScreenBufferInfo(hConsole, &csbi);
> >
> > // Set the buffer's attributes accordingly
> > ::FillConsoleOutputAttribute(hConsole, csbi.wAttributes,
> > dwConSize, coordScreen, &cCharsWritten);
> >
> > // Home the cursor at (0, 0)
> > ::SetConsoleCursorPosition(hConsole, coordScreen);
> >
> > return;
> > }
> >
> > JNIEXPORT jint JNICALL Java_Console_getCurRow(JNIEnv *, jclass)
> > {
> > CONSOLE_SCREEN_BUFFER_INFO csbi;
> >
> > ::GetConsoleScreenBufferInfo(
> > ::GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
> >
> > return csbi.dwCursorPosition.Y;
> > }
> >
> > JNIEXPORT jint JNICALL Java_Console_getCurCol(JNIEnv *, jclass)
> > {
> > CONSOLE_SCREEN_BUFFER_INFO csbi;
> >
> > ::GetConsoleScreenBufferInfo(
> > ::GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
> >
> > return csbi.dwCursorPosition.X;
> > }
> >
> > JNIEXPORT void JNICALL Java_Console_setCurPos(JNIEnv* env, jclass obj,[/color][/color]
jint[color=blue][color=green]
> > row, jint col)
> > {
> > COORD coord; coord.X = col; coord.Y = row;
> >
> > ::SetConsoleCursorPosition(
> > ::GetStdHandle(STD_OUTPUT_HANDLE), coord);
> > }
> >
> > JNIEXPORT jchar JNICALL Java_Console_inputKey(JNIEnv* env, jclass obj,
> > jintArray keyData)
> > {
> > const char NUL = '\0',
> > ESC = '\x1B';
> >
> > const int TIMEOUT_MILLIS = 1000;
> >
> > jsize len = env->GetArrayLength(keyData);
> > jint* keyData_ = env->GetIntArrayElements(keyData, 0);
> >
> > DWORD omode, nmode; DWORD itemsRead = 0;
> > INPUT_RECORD ir;
> > char inputBuffer[4] = { NUL };
> >
> > HANDLE hConsole = ::GetStdHandle(STD_INPUT_HANDLE);
> >
> > ::GetConsoleMode(hConsole, &omode);
> > nmode = omode & ~ENABLE_LINE_INPUT & ~ENABLE_ECHO_INPUT;
> > ::SetConsoleMode(hConsole, nmode);
> >
> > do
> > {
> > ::FlushConsoleInputBuffer(hConsole);
> > ::WaitForSingleObject(hConsole, TIMEOUT_MILLIS);
> > ::PeekConsoleInput(hConsole, &ir, 1, &itemsRead);
> >
> > if (itemsRead > 0)
> > {
> > if (ir.EventType == KEY_EVENT)
> > {
> > // Discard all non-keydown events
> > if (ir.Event.KeyEvent.bKeyDown == FALSE)
> > {
> > ::ReadConsoleInput(hConsole, &ir, 1, &itemsRead);
> > continue;
> > }
> >
> > // Got ASCII key, so extract, flush, and exit
> > if (ir.Event.KeyEvent.uChar.AsciiChar != NUL)
> > {
> > if (ir.Event.KeyEvent.uChar.AsciiChar == ESC)
> > {
> > ::ReadConsoleInput(hConsole, &ir, 1, &itemsRead);
> > inputBuffer[0] = ESC;
> > }
> > else
> > ::ReadFile(hConsole, inputBuffer, 1, &itemsRead, NULL);
> >
> > keyData_[0] = ir.Event.KeyEvent.wVirtualKeyCode;
> > keyData_[1] = ir.Event.KeyEvent.wVirtualScanCode;
> >
> > break;
> > }
> >
> > // Got 'special' key, so determine appropriate actions
> > switch (ir.Event.KeyEvent.dwControlKeyState)
> > {
> > case ENHANCED_KEY:
> > ::ReadConsoleInput(hConsole, &ir, 1, &itemsRead);
> > break;
> >
> > case LEFT_ALT_PRESSED: case LEFT_CTRL_PRESSED:
> > case RIGHT_ALT_PRESSED: case RIGHT_CTRL_PRESSED:
> > ::ReadFile(hConsole, inputBuffer, 1, &itemsRead, NULL);
> > inputBuffer[0] = NUL;
> > break;
> >
> > case SHIFT_PRESSED:
> > ::ReadFile(hConsole, inputBuffer, 1, &itemsRead, NULL);
> > break;
> > }
> >
> > keyData_[0] = ir.Event.KeyEvent.wVirtualKeyCode;
> > keyData_[1] = ir.Event.KeyEvent.wVirtualScanCode;
> > }
> > else
> > {
> > // Not Key Event, so just extract and discard
> > ::ReadConsoleInput(hConsole, &ir, 1, &itemsRead);
> > }
> > }
> >
> > } while (itemsRead == 0);
> >
> > ::FlushConsoleInputBuffer(hConsole);
> > ::SetConsoleMode(hConsole, omode);
> >
> > env->ReleaseIntArrayElements(keyData, keyData_, 0);
> >
> > return inputBuffer[0];
> > }[/color][/color]


Closed Thread