Part of a GUI I'm creating for a bookkeeping program in Java needs to display a varied String. Before displaying this String, it must add line breaks where appropriate. To do this, I've created a class which extends JTextArea, and overridden the setText() method as such:
public class ContentPane extends JTextArea {
private FontMetrics fm;
public ContentPane() {
super();
// Instatiate FontMetrics
}
public ContentPane(String string) {
super(string);
// Instatiate FontMetrics
}
@Override
public void setText(String text) {
int n;
String remainder;
while (fm.stringWidth(text) > maxStringWidth()) {
n = numberOfCharsToCut(text);
remainder = text.substring(text.length() - n);
text = text.substring(0, text.length() - n) + "\n" + remainder;
}
super.setText(text);
}
private int numberOfCharsToCut(String str) {
String newStr = str;
int i = 0;
while (fm.stringWidth(newStr) > maxStringWidth()) {
newStr = str.substring(0, str.length() - i);
i++;
}
return i;
}
private int maxStringWidth() {
return fm.stringWidth("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@lll");
}
}
In place of "// Instatiate FontMetrics", I've tried a few different things. At first I tried to create a FontMetrics object using "new"...
fm = new FontMetrics();
...only to find you can't instantiate FontMetrics in such a way. I tried retrieving a FontMetrics object using getFontMetrics(font), getting the default swing font from an answer in this question:
How do I get the default font for Swing JTabbedPane labels?
My code looked like this:
fm = getFontMetrics(UIManager.getDefaults().getFont("TabbedPane.font"));
This threw a NullPointerException. I also tried:
fm = getGraphics().getFontMetrics(UIManager.getDefaults().getFont("TabbedPane.font"));
This gave me a NullPointerException as well. Perhaps I'm not understanding how to use FontMetrics. Any insight is well appreciated.
Edit: Alright, now I've additionally tried the two above snippets again, replacing UIManager.getDefaults().getFont(...) with getFont(). The same NullPointerException is thrown.