tags:

views:

670

answers:

3

Is there a way to find the width of the console in which my Java program is running?

I would like this to be cross platform if possible...

I have no desire to change the width of the buffer or the window, I just want to know its width so I can properly format text that is being printed to screen.

A: 

Perhaps use libterm?

Wilfred Springer
A: 

Java 6 has a class java.io.Console, but it unfortunately lacks the functionality you're asking for. Getting the console window width is not possible with the standard Java library and pure, cross-platform Java.

Here is an alternative Java console library which allows you to get the screen size, but it includes a Windows-specific DLL. You might be able to take the source code and compile the C part into a Linux or Mac OS X shared library, so that it will work on those platforms as well.

Jesper
I found the Console API and was excited; and then I wasn't... For what I want to do, learning C and how to cross-compile is sort of like hammering a nail with a wrecking ball.
masher
+3  A: 

There are no cross-platform solutions to this problem. Indeed, there are situations where it is not possible to know what the real console width is.

For example, on a Linux system you can typically find out the notional terminal dimensions from the LINES and COLUMNS environment variables. While these variables are automatically updated when you resize some "terminal emulator" windows, this is not always the case. Indeed, in the case of a remote console connected via telnet protocol, there is no way to get the actual terminal dimensions to the user's shell.

EDIT: Just to add that if the user changes the dimensions of his/her xterm on Linux after launching a Java app, the Java app won't be notified, and it won't see the new dimensions reflected in its copy of the LINES and COLUMNS environment variables!

Stephen C
I was hoping there'd be something that would return the width/height etc or -1 if it can't be determined... oh well. Welcome hard-coded constants!
masher
@masher: the problem is that on Linux, the answer would nearly always have to be "cannot be determined with any certainty".
Stephen C