java swing Implementation Loads Custom Fonts
- 2021-12-11 17:57:47
- OfStack
java swing Loading Custom Fonts
In the actual development, we need to make the font name and font 11 corresponding mapping relationship, and then we need to load custom fonts in a configurable way. Therefore, we have this requirement, and we will implement it.
First, we define a tool class for custom loading subclasses
import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* Font tool class , Get the required font
*/
public class FontUtil {
/**
* All font configurations
*/
private static Map<String, String> fontNameMap = new HashMap<String, String>();
/**
* Default font size
*/
private static final float defaultFontSize = 20f;
static {
// Load configuration file
Properties properties = new Properties();
// Use properties Object loads the input stream , Coding usage GBK
try {
properties.load(new InputStreamReader(FontUtil.class.getClassLoader().getResourceAsStream("font.properties"), "GBK"));
} catch (IOException e) {
System.err.println("font.properties Configuration file does not exist ");
}
// Get key Corresponding value Value
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
if (key != null && value != null) {
fontNameMap.put(String.valueOf(key), String.valueOf(value));
}
}
}
/**
* Gets the defined font
*
* @param key The name of the font
* @return
*/
public static Font getConfigFont(String key) {
return getConfigFont(key, defaultFontSize);
}
/**
* Get a custom font
*
* @param key The name of the font
* @param fontSize Font size
* @return
*/
public static Font getConfigFont(String key, float fontSize) {
String fontUrl = fontNameMap.get(key);
if (fontUrl == null) {
throw new RuntimeException(" The name is :" + key + " The font configuration of does not exist ");
}
// The default is to see if it is a system font first
Font font = new Font(fontUrl, Font.PLAIN, (int) fontSize);
// Determine whether the current font exists or not
if ("Dialog.plain".equals(font.getFontName())) {
try (
InputStream is = new FileInputStream(new File(fontUrl));
) {
Font definedFont = Font.createFont(Font.TRUETYPE_FONT, is);
// Set the font size, float Type
definedFont = definedFont.deriveFont(fontSize);
return definedFont;
} catch (Exception e) {
throw new RuntimeException(" The name is :" + key + " The font of does not exist ");
}
}
return font;
}
}
The second part is to write the test code:
import java.awt.*;
public class Demo {
public static void main(String[] args) throws Exception {
Font a = FontUtil.getConfigFont("A");
System.out.println(a.getName() + "~" + a.getSize());
Font b = FontUtil.getConfigFont("B", 100);
System.out.println(b.getName() + "~" + b.getSize());
Font c = FontUtil.getConfigFont("C");
System.out.println(c.getFontName());
Font d = FontUtil.getConfigFont("D");
}
}
Run, the fourth font does not exist, throw an exception, other normal processing, A, B have loaded their own configuration fonts.
Environment configuration, create a new font configuration file in resources: font. properties content is as follows:
# Configuration file for a font, preceded by the name of the font and followed by the path of the font A=D:/logs/Ping Square Bold-Quasi-Simple. ttf B=D:/logs/Ping Square Bold-Medium Bold-Simple. ttf C=Song D= Song 22222
Originally, I wrote the code for others, but I didn't want it at last, so I opened it directly.
Java swing Changing Global Fonts
This code is called before the jframe is displayed, such as when the main method begins:
public static void setUIFont()
{
Font f = new Font(" Song Style ",Font.PLAIN,18);
String names[]={ "Label", "CheckBox", "PopupMenu","MenuItem", "CheckBoxMenuItem",
"JRadioButtonMenuItem","ComboBox", "Button", "Tree", "ScrollPane",
"TabbedPane", "EditorPane", "TitledBorder", "Menu", "TextArea",
"OptionPane", "MenuBar", "ToolBar", "ToggleButton", "ToolTip",
"ProgressBar", "TableHeader", "Panel", "List", "ColorChooser",
"PasswordField","TextField", "Table", "Label", "Viewport",
"RadioButtonMenuItem","RadioButton", "DesktopPane", "InternalFrame"
};
for (String item : names) {
UIManager.put(item+ ".font",f);
}
}