Getting JTextArea to display fixed-width font without antialiasing

后端 未结 2 808
清歌不尽
清歌不尽 2020-12-10 13:46

Does anybody know how to get JTextArea to display a fixed size font on all platforms?

I want to make a simple code editor with save/open functionality, which is simp

相关标签:
2条回答
  • 2020-12-10 14:02

    I came close to a solution by using JTextPane instead of JTextArea by setting the content type of the JTextPane to text/html and setting the text as a html content.

    JtextPane textPane;
    String text;
    
    // initialization
    
    textPane.setContentType("text/html");
    textPane.setText(""
            + "<html>"
            + "<body>"
            + "<p>"
            + "<tt>"+text.replaceAll(" ", "&nbsp;").replaceAll("\n", "<br>")+"</tt>"
            + "</p>"
            + "</body>"
            + "</html>"                
            + "");
    

    <tt> tag is making the text monospaced and all white spaces and new line characters of the text have replaced with html space entity and <br> tag, respectively. I tested the output in both Windows and Ubuntu OSes and they were same.

    0 讨论(0)
  • 2020-12-10 14:24

    You can use the logical font "monospaced". While it guarantees to have a font that has the same size for all characters, it won't be the same on all platform.

    import java.awt.Font;
    
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    
    public class TestTextArea {
    
        private void initUI() {
            JFrame frame = new JFrame("test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JTextArea textArea = new JTextArea(24, 80);
            textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
            frame.add(new JScrollPane(textArea));
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new TestTextArea().initUI();
                }
            });
    
        }
    
    }
    

    Alternatively, you could look up a "free" font which meets your need, embed that font in with code and load it with java.awt.Font.createFont(int, InputStream).

    0 讨论(0)
提交回复
热议问题