本文目录一览:
Java 关于Font类的字体设置
import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.Label;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;import javax.swing.JLabel;public class Test_24 extends Frame implements ItemListener { private static final long serialVersionUID = 1L;
Choice c;
JLabel l; public static void main(String[] args) {
new Test_24(); } public Test_24() {
super();
initialize();
} private void initialize() {
this.setSize(300, 200);
this.setTitle("Frame");
GraphicsEnvironment g = GraphicsEnvironment
.getLocalGraphicsEnvironment();
String fontName[] = g.getAvailableFontFamilyNames();
c = new Choice();
for (int i = 0; i fontName.length; i++)
c.add(fontName[i]);
l = new JLabel("", JLabel.CENTER);
this.add(c, BorderLayout.NORTH);
this.add(l, BorderLayout.CENTER);
this.setVisible(true);
c.addItemListener(this);
this.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
} public void itemStateChanged(ItemEvent e) {
String name = (String) e.getItem();
System.out.println(name);
Font f = new Font(name, Font.ITALIC, 40);
l.setForeground(Color.red);
l.setFont(f);
l.setText("测试字体");
double x=l.getLocation().getX();
double y=l.getLocation().getY();
int h = l.getSize().height;
int w = l.getSize().width;
System.out.println(x+","+y);
System.out.println(h+","+w);
}}
为什么java 中我用了font没有改变字体只能改变自形和大小
很简单,因为你把一个表达式fontName[id_font]用双引号括起来了。变成了一个字符串常量"fontName[id_font]" . 而用这个字符串常量,根本就找不到对应字体,所以无法更改字体
解决办法去掉双引号即可
java中如何读取ttf字体文件,生成Font数组
1.读取
import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
public class Loadfont
{
public static Font loadFont(String fontFileName, float fontSize) //第一个参数是外部字体名,第二个是字体大小
{
try
{
File file = new File(fontFileName);
FileInputStream aixing = new FileInputStream(file);
Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, aixing);
Font dynamicFontPt = dynamicFont.deriveFont(fontSize);
aixing.close();
return dynamicFontPt;
}
catch(Exception e)//异常处理
{
e.printStackTrace();
return new java.awt.Font("宋体", Font.PLAIN, 14);
}
}
public static java.awt.Font Font(){
String root=System.getProperty("user.dir");//项目根目录路径
Font font = Loadfont.loadFont(root+"/data/PRISTINA.ttf", 18f);//调用
return font;//返回字体
}
public static java.awt.Font Font2(){
String root=System.getProperty("user.dir");//项目根目录路径
Font font = Loadfont.loadFont(root+"/data/XXXX.ttf", 18f);
return font;//返回字体
}
}
2.转换:
public static String ascii2native(String ascii) {
int n = ascii.length() / 6;
StringBuilder sb = new StringBuilder(n);
for (int i = 0, j = 2; i n; i++, j += 6) {
String code = ascii.substring(j, j + 4);
char ch = (char) Integer.parseInt(code, 16);
sb.append(ch);
}
return sb.toString();
}