How to set a new source font (external) to a JtextPane

2

I have a JTextPane and want to set a new source (found on the internet) for it. I have seen several tutorials, but none of them have been able to define the source, I would like to make it as simple as possible.

Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));

I tried this, however the error

Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor
    
asked by anonymous 30.07.2015 / 02:00

1 answer

2

I can not reproduce the problem through the code you submitted. As pointed out by re22, it looks like the problem is exception handling - your code works . Here is a sample (note that it is not exactly "correct", many details have been omitted to reduce the code):

import java.awt.*;
import java.io.File;
import java.io.IOException;

import javax.swing.*;

public class TesteFonte extends JPanel {

    JTextArea textArea;
    String texto = "Testando uma fonte diferente!";

    public TesteFonte() throws Exception {

        super(new GridBagLayout());
        textArea = new JTextArea(5, 20);

        Font minhaFonte = Font.createFont(Font.TRUETYPE_FONT,
            new File("C:\Users\Daniel\Downloads\oliver__.ttf"))
            .deriveFont(Font.PLAIN, 28);

        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        add(textArea, c);

        textArea.setFont(minhaFonte);
        textArea.append(texto + "\n");
    }

    private static void createAndShowGUI() throws Exception {
        JFrame frame = new JFrame("Teste de Fonte");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new TesteFonte());
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                try {
                    createAndShowGUI();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Here is the result:

Isuggestthatyouincludeyourentirecodeinthequestion-ifitistoolarge,youshouldtryreducingit,butinawaythatitcanstillbeexecuted.Soexperiencedprogrammers(it'snotmycase)willsolvecaseslikethisintheblinkofaneye!

Originalcode:Javadocs

Source Code: SOen (Neil Derno)

Source used in sample text: "Oliver" (dafont)

    
31.07.2015 / 02:43