如何在 JTextArea 中格式化文本
How to Format text in JTextArea
我正在尝试输出多行文本来创建 ASCII 艺术。但是当我使用 JFrame 和 JTextArea 时,它没有正确排列。我正在尝试打印 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这是我当前的代码(ASCII 艺术中会有一些无用的字符):
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);
}
}`
我找遍了,没有找到解决这个问题的方法。任何帮助都是有用的。
问题是,默认情况下,文本区域使用可变宽度字体。将字体更改为等宽字体将解决问题,例如
text.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
我正在尝试输出多行文本来创建 ASCII 艺术。但是当我使用 JFrame 和 JTextArea 时,它没有正确排列。我正在尝试打印 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这是我当前的代码(ASCII 艺术中会有一些无用的字符):
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);
}
}`
我找遍了,没有找到解决这个问题的方法。任何帮助都是有用的。
问题是,默认情况下,文本区域使用可变宽度字体。将字体更改为等宽字体将解决问题,例如
text.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));