JTextField crops text when using custom TrueType font. How to make it display text normally?

馋奶兔 提交于 2020-01-25 03:36:08

问题


So, the problem is definitely with the font. Question is how to make the text field display text fully. Example:

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

class Example extends JFrame{
    public Example(){
        setLayout(new BorderLayout());
        Font myFont = null;
        try {
            URL link = new URL("http://rghost.ru/download/50564305/e6efddd74f598b86f7ac704cab72e430a490bc7f/digital-7.ttf");
            ReadableByteChannel rbc = Channels.newChannel(link.openStream());
            File font_file = new File("font.ttf");
            if(!font_file.exists())
                font_file.createNewFile();

            FileOutputStream fos = new FileOutputStream(font_file);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            myFont = Font.createFont(Font.TRUETYPE_FONT, font_file);
        } catch (FontFormatException e) {
            e.printStackTrace(); 
        } catch (IOException e) {
            e.printStackTrace();
        }
        JTextField myField = new JTextField("sample text");
        myField.setFont(myFont.deriveFont(32.0f));
        add(myField, BorderLayout.NORTH);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300, 400);
        setVisible(true);
    }

    public static void main(String[] args){
        new Example();
    }
}

The font is Digital 7: dafont.com
PROBLEM SOLVED The solution is to convert the font here (or other such place) to PFM and use it like that:

Font myFont = Font.createFont(Font.TYPE1_FONT, new File("res/my_font.pfm"));

回答1:


I suspect the problem is with the Font rather than Java.

I found a page at http://onlinefontconverter.com/font?id=p1 that claims to (sometimes) fix invalid fonts, but cannot locate one that will simply report the validity. Try running it through that first.




回答2:


myField.setPreferredSize(new Dimension(40,40)); // where the first argument is the width of the component,
                                                //  and 2nd is the height(that's what you need )


来源:https://stackoverflow.com/questions/20310719/jtextfield-crops-text-when-using-custom-truetype-font-how-to-make-it-display-te

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!