I ran into a little problem today while I was coding. I'm no expert in java, and I'm only just starting to learn GUI, so bear with me please.
I'm creating a game that involves a map that is composed of this 2D array, I've created a method to put that 2D array in a textArea.
public void viewMap(String[][] matrix)
{
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[0].length; c++)
{
textArea.setText(textArea.getText() + "\t" + String.valueOf(matrix[r][c]));
}
textArea.setText(textArea.getText() + "\n" );
}
}
If you notice the "\t" that i use to space each element. This works well for evenly spacing it, but the space is extremely large. My array turns out something like this:
x H f f x x
x f x f D x
x x x x x x
This kind of spacing is great because the different letters not offset the position of the other letters, but it is way to large for my purposes, but if i simply put a few spaces in place of the "\t" i get something that doesn't line up like it does when i use /t, instead that different sizes of the letters throws off the rest of the row.
So i was wondering if anyone could help me come up with a solution in order to evenly space these letters when printing them out. I would really appreciate any feedback and help.
Thanks.
If you want to use the JTextField, it has the method JTextArea#setTabSize(int), with which you can reduce the tabwidth.
EDIT: JTextArea doesn't seem to align tabs, so you will need to use a monospaced font.
Text components aren't really well designed for formatting data in this way (at least not components that are designed to display plain text).
You could use a
JTable
instead, for example...If you don't need to edit the values or need anything really fancy (like selection), you could use a
JLabel
and wrap your text within a HTML TABLE...And... If you "really" want to use a text component, then something like
JEditorPane
would probably be a better choice, as you don't need to worry about mono-spaced fonts...