Java – How to format text in JTextArea

How to format text in JTextArea… here is a solution to the problem.

How to format text in JTextArea

I’m trying to output multiple lines of text to create ASCII art. But when I use JFrame and JTextArea, it doesn’t line up correctly. I’m trying to print out Merry Christmas in ASCII art, but when I print it out in a new window, The characters do not line up to form the words This is my current code (there will be some useless characters in ASCII art):

public class LanguageChristmas  {

public static void main(String args[]) {
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        JFrame f = new JFrame("Merry Christmas");
        f.addWindowListener(new WindowAdapter() {
           public void windowClosing(WindowEvent e) {System.exit(0); }
        });
        JTextArea text = new JTextArea(100,50);
         {
            text.append("   _____                               _________ .__          .__          __                                           "+ "\n");
            text.append("  /     \\   __________________ ___.__. \\_   ___ \\|  |_________|__| _______/  |_  _____ _____    ______   /     \\ " + "\n");
            text.append(" /  \\ /  \\_/ __ \\_  __ \\_  __ <   |  | /    \\  \\/|  |  \\_  __ \\  |/  ___/\\   __\\/     \\\\__  \\  /  ___/  /  \\ / " + "\n");
            text.append("/    Y    \\  ___/|  | \\/|  | \\/\\___  | \\     \\___|   Y  \\  | \\/  |\\___ \\  |  | |  Y Y  \\/ __ \\_\\___ \\  /    Y    " + "\n");
            text.append("\\____|__  /\\___  >__|   |__|   / ____|  \\______  /___|  /__|  |__/____  > |__| |__|_|  (____  /____  > " + "\n");
            text.append("        \\/     \\/              \\/              \\/     \\/              \\/             \\/     \\/     \\/           " + "\n");

}
        JScrollPane pane = new JScrollPane(text);
        pane.setPreferredSize(new Dimension(500,400));
        f.add("Center", pane);
               f.pack();
        f.setVisible(true);
    }
}`

I looked around and couldn’t find a solution to this problem. Any help is useful.

Solution

The problem is that, by default, text areas use variable-width fonts. Changing the font to a monospace font will solve the problem, eg

   text.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

Related Problems and Solutions