Search code examples
javacharacterlimitjtextareajtextpane

Java JTextPane or JTextArea set characters per line before wrapping


I have a 64-character "key" (text) that I want to display in a limited amount of space (width) using a swing JPanel containing a JTextPanel or JTextArea. All the text is alphanumeric, with no spaces, and I am using a monospace font to display it. I'd like to print the key in 4 lines of 16 characters. My code:

JTextArea key = new JTextArea();
key.setColumns(16);
key.setRows(4);
key.setLineWrap(true);
key.setWrapStyleWord(true);
key.setText("475EC49A50F35BA50FE5791B8ECFC12515393A5A200C6BA2C82B290C053A6C85");
JPanel keypanel = new JPanel();
keypanel.add(privatekeybackuptext);

When I run it, it prints more than 16 characters per line. It just prints as many as it can fit in the arbitrarily-sized box and the textarea/textpane ends up with 2.5 lines of hex characters. I am guessing that either setColumns and setRows has nothing to do with how text is displayed or the layout manager is overriding something? So far, I have tried setting the layoutmanager of the panel to the default FlowLayout and I have also tried GridBagConstraints with fill = GridBagConstraints.BOTH. Neither worked. I know I could fake it by counting off 16 characters and adding a newline, but I'd rather do it correctly. What is the easiest way to do this?


Solution

  • I am guessing that either setColumns and setRows has nothing to do with how text is displayed

    Set columns will size the text area so that it can contain 16 "W" characters.

    When I run it, it prints more than 16 characters per line

    You will need to use a monospaced font.

    textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
    

    Now an "I" is the same as a "W" so you should have 16 characters on each row.