How to set a new (external) source for a Jtextpane

Asked

Viewed 713 times

2

I have a JTextPane and I want to define a new source (found on the internet) for it. I saw several tutorials, but none of them could 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 it, but it makes a mistake

Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor

1 answer

2


I can’t reproduce the problem through the code you presented. As pointed out by re22, it seems that the problem is exception treatment - your code works. Follow 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:

Resultado

I suggest that you include your entire code in the question - if it is too big, that you try to reduce it, but so that it can still be executed. So experienced programmers (not my case), will solve cases like this in the blink of an eye!

Original code: Javadocs

Code to insert source: Soen (Neil Derno)

Font used in example text: "Oliver" (dafont)

  • It worked perfectly. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.