Note that there are some explanatory texts on larger screens.

plurals
  1. POFontMetrics generates NullPointerException
    primarykey
    data
    text
    <p>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:</p> <pre><code>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) &gt; 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) &gt; maxStringWidth()) { newStr = str.substring(0, str.length() - i); i++; } return i; } private int maxStringWidth() { return fm.stringWidth("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@lll"); } } </code></pre> <p>In place of "// Instatiate FontMetrics", I've tried a few different things. At first I tried to create a FontMetrics object using "new"...</p> <pre><code>fm = new FontMetrics(); </code></pre> <p>...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: </p> <p><a href="https://stackoverflow.com/questions/1434201/default-font-for-swing-text">How do I get the default font for Swing JTabbedPane labels?</a></p> <p>My code looked like this:</p> <pre><code>fm = getFontMetrics(UIManager.getDefaults().getFont("TabbedPane.font")); </code></pre> <p>This threw a NullPointerException. I also tried:</p> <pre><code>fm = getGraphics().getFontMetrics(UIManager.getDefaults().getFont("TabbedPane.font")); </code></pre> <p>This gave me a NullPointerException as well. Perhaps I'm not understanding how to use FontMetrics. Any insight is well appreciated.</p> <p>Edit: Alright, now I've additionally tried the two above snippets again, replacing UIManager.getDefaults().getFont(...) with getFont(). The same NullPointerException is thrown.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload