Help centering text
I'm trying to center a line of text in the text area.
If the text entered can be displayed on one line, I would like the text centered; otherwise it should use the word wrap.
I tried creating a method called center:
// Defined outside this method, but shown since it is being referenced.
int textAreaWidth = (int) textArea.getPreferredScrollableViewportSize().getWidth();
public String center(String text)
{
int stringWidth = metrics.stringWidth(text);
if (stringWidth > textAreaWidth)
{
// Only handles text shorter than one line.
return text;
}
int availableWidth = textAreaWidth - stringWidth;
int availableSpaces = availableWidth / metrics.charWidth(' ');
int spacesToAdd = availableSpaces / 2;
// Adds the leading spaces to the text to center it.
// Adds a trailing space as well to test the actual metrics length.
for (int index = 0; index < spacesToAdd; index++)
{
text =" " + text +" ";
}
return text;
}
I coudln't find anything to use in the Java Doc, so I thought I'd write one to help me out.
Testing it, I used:
textArea.setText(center("m"));
The issue is that the JTextArea is returning a width of 300. That is correctly set, and returning the right width.
The string width is returning at 11, which is expected for the letter m.
The available width is 289. Also correct. 300 - 11 = 289
The metrics character width of a space is 3.
The spacesToAdd returns at 48.
A string with a metrics width of 299 is returned. That being, 48 spaces and the letter m.
However, the JTextArea displayed in the JPanel shows this text wrapping onto a second line -- indicating the JTextArea displayed is not the actual width I set it to.
The code to setup the JTextArea is as follows:
JPanel panel =new JPanel();
textArea =new JTextArea();
textArea.setPreferredSize(new Dimension(300, 60));
textArea.setLineWrap(true);
textArea.setFocusable(false);
textArea.setEditable(false);
textArea.setWrapStyleWord(true);
textArea.setFont(APP_FONT);
scrollPane =new JScrollPane(textArea);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
panel.add(scrollPane);
What am I doing wrong?
I suppose I could use a document and set styles... but ... I was trying to get this working...
Help would be appreciated.. Thanks!

