Установка шрифта по умолчанию для программы Swing
мне было интересно, как установить шрифт по умолчанию для всей моей программы Java swing. Из моих исследований кажется, что это можно сделать с UIManager, то с LookAndFeel, но я не могу найти конкретно, как это сделать, и UIManager кажется довольно сложным.
12 ответов:
попробуй:
public static void setUIFont (javax.swing.plaf.FontUIResource f){ java.util.Enumeration keys = UIManager.getDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); Object value = UIManager.get (key); if (value instanceof javax.swing.plaf.FontUIResource) UIManager.put (key, f); } }звонок ...
setUIFont (new javax.swing.plaf.FontUIResource("Serif",Font.ITALIC,12));
UIManager.put("Button.font", /* font of your liking */); UIManager.put("ToggleButton.font", /* font of your liking */); UIManager.put("RadioButton.font", /* font of your liking */); UIManager.put("CheckBox.font", /* font of your liking */); UIManager.put("ColorChooser.font", /* font of your liking */); UIManager.put("ComboBox.font", /* font of your liking */); UIManager.put("Label.font", /* font of your liking */); UIManager.put("List.font", /* font of your liking */); UIManager.put("MenuBar.font", /* font of your liking */); UIManager.put("MenuItem.font", /* font of your liking */); UIManager.put("RadioButtonMenuItem.font", /* font of your liking */); UIManager.put("CheckBoxMenuItem.font", /* font of your liking */); UIManager.put("Menu.font", /* font of your liking */); UIManager.put("PopupMenu.font", /* font of your liking */); UIManager.put("OptionPane.font", /* font of your liking */); UIManager.put("Panel.font", /* font of your liking */); UIManager.put("ProgressBar.font", /* font of your liking */); UIManager.put("ScrollPane.font", /* font of your liking */); UIManager.put("Viewport.font", /* font of your liking */); UIManager.put("TabbedPane.font", /* font of your liking */); UIManager.put("Table.font", /* font of your liking */); UIManager.put("TableHeader.font", /* font of your liking */); UIManager.put("TextField.font", /* font of your liking */); UIManager.put("PasswordField.font", /* font of your liking */); UIManager.put("TextArea.font", /* font of your liking */); UIManager.put("TextPane.font", /* font of your liking */); UIManager.put("EditorPane.font", /* font of your liking */); UIManager.put("TitledBorder.font", /* font of your liking */); UIManager.put("ToolBar.font", /* font of your liking */); UIManager.put("ToolTip.font", /* font of your liking */); UIManager.put("Tree.font", /* font of your liking */);
java -Dswing.aatext=true -Dswing.plaf.metal.controlFont=Tahoma -Dswing.plaf.metal.userFont=Tahoma …Это не только установит Tahoma на вашем полном пользовательском интерфейсе, но и включит сглаживание, что сразу же сделает любой шрифт намного красивее.
Я думаю, что это лучше, вызывая его для текущего laf вместо всего UIManager положите это
UIManager.getLookAndFeelDefaults() .put("defaultFont", new Font("Arial", Font.BOLD, 14));где-то в основном перед созданием экземпляра объекта JFrame. Это прекрасно работало для меня. Помните, что это шрифт по умолчанию, для компонентов, которые не имеют указанного шрифта.
источник:http://www.java.net/node/680725
имейте в виду, что способ установки шрифта по умолчанию зависит от внешнего вида, который вы используете. Решение, описанное Роменом Гиппо, отлично работает с большим количеством LAF, но не с Nimbus. Тот, который опубликовал шериф, отлично работает с нимбом, но не с другими (например, с металлом).
объединение обоих может работать на большинстве LAF, но ни одно из этих решений не работает с GTK+ LAF.
Я думаю (но я не уверен), что нет кросс-платформенного решения.
вдохновленный Ромен Гиппо, используйте этот код, если вы хотите установить только размер шрифта.
for (Map.Entry<Object, Object> entry : javax.swing.UIManager.getDefaults().entrySet()) { Object key = entry.getKey(); Object value = javax.swing.UIManager.get(key); if (value != null && value instanceof javax.swing.plaf.FontUIResource) { javax.swing.plaf.FontUIResource fr=(javax.swing.plaf.FontUIResource)value; javax.swing.plaf.FontUIResource f = new javax.swing.plaf.FontUIResource(fr.getFamily(), fr.getStyle(), FONT_SIZE); javax.swing.UIManager.put(key, f); } }
Я использую Nimbus L & F.
С помощью кода от @Ромен Гиппо, мне пришлось использовать
UIManager.getLookAndFeelDefaults()вместоUIManager.getDefaults()и использовать возвращенную ссылку наputизмененные значения:int szIncr = 5; // Value to increase the size by UIDefaults uidef = UIManager.getLookAndFeelDefaults(); for (Entry<Object,Object> e : uidef.entrySet()) { Object val = e.getValue(); if (val != null && val instanceof FontUIResource) { FontUIResource fui = (FontUIResource)val; uidef.put(e.getKey(), new FontUIResource(fui.getName(), fui.getStyle(), fui.getSize()+szIncr)); } }по какой-то причине он не работает с L&F. По умолчанию... (на основе ограниченных тестов, которые я выполнил)
чтобы решить эту проблему, я просто реализовать AWTEventListener и слушать COMPONENT_ADDED ContainerEvent.
все описание истории по адресу:http://wiki.idempiere.org/en/Swing_Miss_Support_Some_Language
- выполнить AWTEventListener
public void eventDispatched(AWTEvent event) { if (!isMissSupportGlyph || !(event instanceof ComponentEvent) || !(event instanceof ContainerEvent)) return; if (event instanceof ContainerEvent){ ContainerEvent containerEvent = (ContainerEvent)event; if (containerEvent.getID() == ContainerEvent.COMPONENT_ADDED){ updateChildControlFont(containerEvent.getChild()); } } }
- добавить прослушиватель реестра (лучшее место для запуска это при запуске программы)
Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.COMPONENT_EVENT_MASK | AWTEvent.CONTAINER_EVENT_MASK);
ни одно из этих решений не работает нормально для меня, я строю свой собственный (глупый) , но он работает:
private void changeFontRecursive(Container root, Font font) { for (Component c : root.getComponents()) { c.setFont(font); if (c instanceof Container) { changeFontRecursive((Container) c, font); } } }
правильный ответ-Это Амир Раминфар, но вы должны инкапсулировать шрифт в FontUIResource. Например :
UIManager.put("Button.font", new FontUIResource(new Font ("Helvetica", Font.BOLD, 16)));
я использовал Synth look and feel XML-файл и определил шрифты там. Легкий, гибкий и континент.
Вам нужно создать классcreateFontкак:public class CustomFontResource { public static FontUIResource createFont(String path, final int size) throws IOException, FontFormatException { Font font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(path)); return new FontUIResource(font.deriveFont(Font.PLAIN, size)); }и в вашем синтезаторе xml определить шрифт, как:
<object id="Basic_Regular" class="<your CustomFontResource class>" method="createFont"> <string>path_to_your_font</string> <int>font_size</int> </object>тогда вы можете использовать его в качестве ссылки везде, где вы хотите в xml.
как завершение ответа @Amir, это полный список ключей
Я использую эту функцию
private void setFont(FontUIResource myFont) { UIManager.put("CheckBoxMenuItem.acceleratorFont", myFont); UIManager.put("Button.font", myFont); UIManager.put("ToggleButton.font", myFont); UIManager.put("RadioButton.font", myFont); UIManager.put("CheckBox.font", myFont); UIManager.put("ColorChooser.font", myFont); UIManager.put("ComboBox.font", myFont); UIManager.put("Label.font", myFont); UIManager.put("List.font", myFont); UIManager.put("MenuBar.font", myFont); UIManager.put("Menu.acceleratorFont", myFont); UIManager.put("RadioButtonMenuItem.acceleratorFont", myFont); UIManager.put("MenuItem.acceleratorFont", myFont); UIManager.put("MenuItem.font", myFont); UIManager.put("RadioButtonMenuItem.font", myFont); UIManager.put("CheckBoxMenuItem.font", myFont); UIManager.put("OptionPane.buttonFont", myFont); UIManager.put("OptionPane.messageFont", myFont); UIManager.put("Menu.font", myFont); UIManager.put("PopupMenu.font", myFont); UIManager.put("OptionPane.font", myFont); UIManager.put("Panel.font", myFont); UIManager.put("ProgressBar.font", myFont); UIManager.put("ScrollPane.font", myFont); UIManager.put("Viewport.font", myFont); UIManager.put("TabbedPane.font", myFont); UIManager.put("Slider.font", myFont); UIManager.put("Table.font", myFont); UIManager.put("TableHeader.font", myFont); UIManager.put("TextField.font", myFont); UIManager.put("Spinner.font", myFont); UIManager.put("PasswordField.font", myFont); UIManager.put("TextArea.font", myFont); UIManager.put("TextPane.font", myFont); UIManager.put("EditorPane.font", myFont); UIManager.put("TabbedPane.smallFont", myFont); UIManager.put("TitledBorder.font", myFont); UIManager.put("ToolBar.font", myFont); UIManager.put("ToolTip.font", myFont); UIManager.put("Tree.font", myFont); UIManager.put("FormattedTextField.font", myFont); UIManager.put("IconButton.font", myFont); UIManager.put("InternalFrame.optionDialogTitleFont", myFont); UIManager.put("InternalFrame.paletteTitleFont", myFont); UIManager.put("InternalFrame.titleFont", myFont); }и я вызываю его в
mainперед вызовом пользовательского интерфейсаsetFont(new FontUIResource(new Font("Cabin", Font.PLAIN, 14)));полный список Swing UI Manager keys проверить это ссылке
Comments