gpt4 book ai didi

java - 自定义字体未显示/非常小?

转载 作者:行者123 更新时间:2023-11-30 06:15:19 25 4
gpt4 key购买 nike

我正在尝试使用 Google Fonts 中的字体。 FontFormatException 告诉我存在“读取字体数据时出现问题”,这似乎会导致文本非常小。我的空框上有一条细黑线,我猜那是我的标签。不知道为什么我会得到这个异常(exception)。我尝试了一堆不同的字体,全部来自 Google Fonts,问题总是相同的。

public class View extends JFrame implements MouseListener {
private JPanel content;
private Font font;

public View(){

content = new JPanel();
content.setPreferredSize(new Dimension(500, 500));

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(content);
pack();
setLocationRelativeTo(null);
setVisible(true);

try {
InputStream file = Canvas.class.getResourceAsStream("RammettoOne-Regular.ttf");
font = Font.createFont(Font.TRUETYPE_FONT, file);

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);

font.deriveFont(Font.PLAIN, 25);

} catch (IOException | FontFormatException ex) {
System.out.println(ex.getMessage());
}

addLabel();
revalidate();
}

public void addLabel(){
JLabel label = new JLabel("this is a test");
label.setFont(font);
label.setForeground(Color.BLACK);
content.add(label);
}
}

我尝试在deriveFont中将字体变大,但没有任何变化。知道为什么会发生这种情况吗?

最佳答案

font.deriveFont(Font.PLAIN, 25);

需要:

// assign the derived (resized) font to the local attribute reference! 
font = font.deriveFont(Font.PLAIN, 25);

结果

enter image description here

代码

这是显示上述屏幕截图的 MCVE。

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.URL;
import java.io.*;

public class TestRammettoFont {

private JComponent ui = null;
String fontAddress = "jar:http://dl.1001fonts.com/rammetto-one.zip"
+ "!/RammettoOne-Regular.ttf";

TestRammettoFont() {
try {
initUI();
} catch (Exception ex) {
ex.printStackTrace();
}
}

public final void initUI() throws Exception {
if (ui != null) {
return;
}

ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(14, 14, 14, 14));

URL url = new URL(fontAddress);
InputStream is = url.openStream();
Font font = Font.createFont(Font.TRUETYPE_FONT, is);

font = font.deriveFont(Font.PLAIN, 25);
JLabel l = new JLabel("The quick brown fox (etc.)");
l.setFont(font);
ui.add(l);
}

public JComponent getUI() {
return ui;
}

public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
TestRammettoFont o = new TestRammettoFont();

JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);

f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());

f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

关于java - 自定义字体未显示/非常小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49336254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com