0

我正在尝试在 JTextPane 中设置字体宽度,但不知何故我不知道如何做到这一点。

这是我已经拥有的代码:

Font resultFont = new Font("Courier", Font.PLAIN, 12);

JTextPane resultPane = new JTextPane();
resultPane.setText(result);
resultPane.setFont(resultFont);
resultPane.setEditable(false);

add(resultPane);

如果可以拉伸字体,那就太酷了,因为我想显示一些 ASCII-Art。

4

2 回答 2

5

你想实际拉伸字符还是只调整“字距”(字符之间的空间)。如果只是字距调整:您可以在此处找到解决方案

于 2012-09-06T12:10:03.043 回答
1

我认为您正在寻找等宽字体:SWT - OS agnostic way to get monospaced font

这是一个例子:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class TestProject extends JPanel{

    public TestProject(){
        super();

       JTextPane ta = new JTextPane();

       //If you want to adjust your line spacing too
       MutableAttributeSet set = new SimpleAttributeSet();
       StyleConstants.setLineSpacing(set, -.2f);
       ta.setParagraphAttributes(set, false);

       //Making font monospaced
       ta.setFont(new Font("Monospaced", Font.PLAIN, 20));

       //Apply your ascii art
       ta.setText(" .-.\n(o o) boo!\n| O \\\n \\   \\\n  `~~~'");

       //Add to panel
        add(ta, BorderLayout.CENTER);

    }

    public static void main(String args[])
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                frame.setContentPane(new TestProject());    
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
于 2012-09-06T20:05:39.390 回答