我一直在尝试在我的Swing应用程序中使用自定义字体(包含在包装中)。我已经看过许多有关此主题的代码片段和教程,但是我似乎无法使其正常工作。 在将13个错误缩小为1个错误之后,我可能已将代码修改为无法完全实现我想要的功能。不幸的是,我才刚刚开始学习Java,却无法弄清楚。下面是我的代码,然后是我的错误。任何帮助将不胜感激,非常感谢!
import javax.swing.*;
import java.awt.Toolkit;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.io.FileInputStream;
import java.io.IOException;
import java.awt.FontFormatException;
public class welcomeWindow extends JFrame {
public static void main(String[] args) {
new welcomeWindow();
}
public welcomeWindow() {
// opens window to specifications
Toolkit toolkit=Toolkit.getDefaultToolkit();
this.setSize(toolkit.getScreenSize().width, toolkit.getScreenSize().height);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("window title");
this.setVisible(true);
this.setLocationRelativeTo(null);
// creates panel, adds panel to frame
JPanel welcomePanel = new JPanel();
this.add(welcomePanel);
// font (where i THINK the problem may be)
try {
Font childTitle = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("comic_andy.ttf")).deriveFont(30f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("comic_andy.ttf")));
} catch (IOException | FontFormatException e) {
e.printStackTrace();
Font childTitle = new Font("Helvetica", Font.BOLD, 30);
System.err.println("caught error");
}
// creates title label and adds to panel
JLabel welcomeTitle = new JLabel("title");
welcomeTitle.setFont(childTitle);
welcomePanel.add(welcomeTitle);
}
}
如前所述,这是我遇到的错误(确实很简单):
welcomeWindow.java:40: error: cannot find symbol
welcomeTitle.setFont(childTitle);
^
symbol: variable childTitle
location: class welcomeWindow
1 error
我一直在想我没有正确创建字体,但是我认为我错了,因为我无法解决问题。如果有人可以指出我的代码出了问题的地方,那将是惊人的。谢谢!
答案 0 :(得分:2)
将变量myFont
声明为try..catch
块的局部变量。将其移到块外。
Font myFont;
try {
myFont = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("comic_andy.ttf")).deriveFont(30f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("comic_andy.ttf")));
} catch (IOException | FontFormatException e) {
e.printStackTrace();
myFont = new Font("Helvetica", Font.BOLD, 30);
System.err.println("caught error");
}