Skip to content
Advertisement

Java – JTextArea refuses to print strings that are just whitespace [closed]

I have written a command terminal using Swing components. The snippets of code below contain everything I think could be part of the problem. What is happening is in Snippet #1, when I call printBoard(), it ignores the whitespace in the values[][] array. I tried switching to String[][] instead of char[][] but it didn’t work.

If you need more information, please ask. Thanks for your help!

EDIT: https://github.com/GlitchGamer1459/Windows-Command-Prompt-Clone

Snippet #1:

JavaScript

Snippet #2:

JavaScript

Snippet #3:

JavaScript

Advertisement

Answer

So, I pulled your code, and ignoring the over use of static, null layouts and KeyListener, I changed:

JavaScript

to

JavaScript

and it now prints

enter image description here

You need to make use of a monospaced font in order to ensure that all the characters have equal widths

Also, you should follow Andrew’s advice…

JavaScript

Now you get platform independence.

what’s wrong with the null layout?

Without a layout manager…

enter image description here

With a layout manager…

enter image description here

Resiability for free. You also don’t have to worry about the DPI or what things like accessibility might do.

null or “pixel perfect” layouts are an illusion. To many factor go into determining how a component should be sized and how components should be laid out in relationship to each other.

A lot of work has gone into solving these issues, Swing makes use of layout managers, other frameworks do similar things.

Rather then spending a lot of time tearing your hair out over why the layout breaks on some others computer, just make use of the layout managers that are already available to you – for example, BorderLayout would be a fantastic for your current layout

what’s wrong with KeyListener?

KeyListener is too low level a API for your needs. Since all you’re doing is monitoring for the Enter key anyway, you might as well make use of the ActionListener support. You’re also assuming the key code is constant.

If you want to filter the input, then you should use a DocumentFilter.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement