除了摆动似乎附带的基本 5 之外,我正在尝试更改我的 GUI 的字体。如何导入字体并在我的代码中实际使用它们?
问问题
4552 次
3 回答
6
默认情况下通常有 5 个以上可用,但它们会因系统而异。这个答案检查了现有字体,以及如何加载和注册新字体。
它使用可从下载免费字体(通过热链接 URL 获得)获得的“Airacobra Condensed”字体。应用程序 Jar 中的字体。也可以通过 URL 访问。
import java.awt.*;
import javax.swing.*;
import java.net.URL;
class LoadFont {
public static void main(String[] args) throws Exception {
// This font is < 35Kb.
URL fontUrl = new URL("http://www.webpagepublicity.com/" +
"free-fonts/a/Airacobra%20Condensed.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
JList fonts = new JList( ge.getAvailableFontFamilyNames() );
JOptionPane.showMessageDialog(null, new JScrollPane(fonts));
}
}
好的,这很有趣,但是这个字体实际上是什么样子的?
import java.awt.*;
import javax.swing.*;
import java.net.URL;
class DisplayFont {
public static void main(String[] args) throws Exception {
URL fontUrl = new URL("http://www.webpagepublicity.com/" +
"free-fonts/a/Airacobra%20Condensed.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
font = font.deriveFont(Font.PLAIN,20);
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
JLabel l = new JLabel(
"The quick brown fox jumped over the lazy dog. 0123456789");
l.setFont(font);
JOptionPane.showMessageDialog(null, l);
}
}
于 2012-05-02T16:46:51.013 回答
3
你可以试试这个:
Font font = Font.createFont(Font.TRUETYPE_FONT, fontStream);
下一个,
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font);
和,
new Font("nameOfFont", Font.BOLD, 13)
于 2012-05-02T16:39:02.620 回答
1
这是一种加载打包在 jar 文件 + xml 文件中的字体以读取字体大小、字体名称和字体文件名的方法:
1)字体库类:
package be.nicholas.font.loading;
import java.awt.Font;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import be.nicholas.font.CustomFont;
import be.nicholas.utils.Logger;
import be.nicholas.utils.Misc;
public class FontLibrary {
public static Map<String, Font> fonts = null;
private static Logger logger = Logger.getInstance();
public FontLibrary() { }
/**
* Get the font by it's name.
* @param fontname the font name
* @return The font for the given id if it exists.
*/
public static Font getFont(String fontname)
{
Font f = FontLibrary.fonts.get(fontname);
if(f == null)
logger.error("Font ("+fontname+") could not be found.");
return f;
}
/**
* Get the font by it's name and change the fontsize
* @param fontname the font name.
* @param fontsize
* @return Font
*/
public static Font getFont(String fontname, int fontsize)
{
Font f = FontLibrary.fonts.get(fontname).deriveFont((float) fontsize);
if(f == null)
logger.error("Font ("+fontname+") could not be found.");
return f;
}
public static void load()
{
try
{
InputStream fontStream = FontLibrary.class.getResourceAsStream("/data/fonts/fonts.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fontStream);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("font");
fonts = new HashMap<String, Font>();
logger.error("Starting to load fonts...");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fontElement = (Element) nNode;
CustomFont f = new CustomFont();
f.setName(getTagValue("name", fontElement));
f.setFont(CustomFont.load(getTagValue("filename", fontElement), Integer.parseInt(getTagValue("fontsize", fontElement))));
f.setSize(Integer.parseInt(getTagValue("fontsize", fontElement)));
fonts.put(f.getName(), f.getFont());
/**
* Calculate percentage
*/
int percent = Misc.getPercentage(fonts.size(), nList.getLength());
String msg = percent+"% of fonts loaded("+fonts.size()+" of "+nList.getLength()+")";
}
}
} catch (Exception e) {
logger.error("Error: "+e);
}
logger.error("All fonts loaded!"+"("+fonts.size()+" fonts int total).");
//logger.info(fonts.size()+" = size of fontsmap. -> name ofzo: "+fonts.get("rssmall"));
}
private static String getTagValue(String sTag, Element eElement)
{
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
}
2)自定义字体类:
package be.nicholas.font;
import java.awt.Font;
import java.io.InputStream;
import be.nicholas.font.loading.FontLibrary;
import be.nicholas.utils.Misc;
public class CustomFont {
public String name;
public Font fontObject;
public int size;
public CustomFont() {
//super(font);
}
public void setFont(Font fontObject)
{
this.fontObject = fontObject;
}
public Font getFont()
{
return this.fontObject;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setSize(int size)
{
this.size = size;
}
public int getSize()
{
return this.size;
}
public static Font load(String filename,int fontSize)
{
InputStream fontStream = CustomFont.class.getResourceAsStream("/be/nicholas/fonts/"+filename);
if (fontStream != null)
{
try
{
Font labelFont;
labelFont = Font.createFont(Font.TRUETYPE_FONT, fontStream);
labelFont = labelFont.deriveFont((float) fontSize);
return labelFont;
} catch (Exception e)
{
System.out.println("error " + e);
}
}
return null;
}
}
3)XML结构:
<fonts>
<font>
<name>mycustomfontname</name>
<filename>myfont.ttf</filename>
<fontsize>16</fontsize>
</font>
<font>
<name>champagne</name>
<filename>ChampagneAndLimousines.ttf</filename>
<fontsize>50</fontsize>
</font>
</fonts>
4)加载字体:
JLabel label = new JLabel('testText');
//load it with the default given font size
label.setFont(FontLibrary.fonts.get("mycustomfontname"));
//load a font with a custom font size:
label.setFont(FontLibrary.fonts.get("mycustomfontname").deriveFont(22));
我希望这会有所帮助:)......我是一个真正的java新手,我在玩java的第5天做了这个,所以它远非完美,但它会完成这项工作
于 2012-09-27T15:54:14.373 回答