Luca
Luca

Reputation: 35

How to Format text in JTextArea

I am trying to Output multiple lines of text to create ASCII art. But when I use JFrame and JTextArea it does not line up correctly. I am 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 wordsThis is my current code (There will be some characters in the ASCII art that are useless):

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 have searched around and have not found the solution to this problem. Any help is useful.

Upvotes: 3

Views: 3441

Answers (1)

ThomasEdwin
ThomasEdwin

Reputation: 2145

The problem is that, by default, text area uses variable width font. Changing font to monospaced one will solve the problem, e.g.

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

Upvotes: 4

Related Questions