0

I'm trying to set the font width in a JTextPane, but somehow I didn't find out how this could be done.

Here is the code I already have:

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

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

add(resultPane);

It would be really cool, if there was any possibility to stretch the font, because I want to display some ASCII-Art.

evotopid
  • 5,288
  • 2
  • 26
  • 41
  • *"any possibility to stretch the font"* What DYM? – Andrew Thompson Sep 06 '12 at 12:00
  • Why don't you use JTextArea instead, it's almost he same thing, but I doesn't support styled documents like JTextPane does. This should mean that setting font should work – MadProgrammer Sep 06 '12 at 12:07
  • As said in the answer below, I think that setting kerning would work for me... I'll try out that and if it doesn't work I'll give JTextArea a try – evotopid Sep 06 '12 at 12:22

2 Answers2

5

Do you want to actually stretch the characters or only adjust the "kerning" (space between characters). If it's just the kerning: you can find a solution here

Community
  • 1
  • 1
jeroen_de_schutter
  • 1,843
  • 1
  • 18
  • 21
1

I think you're looking for monospace font: SWT - OS agnostic way to get monospaced font

And here's an example:

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);
            }
        });
    }
}
Community
  • 1
  • 1
Nick Rippe
  • 6,465
  • 14
  • 30