2

im trying to change font globally for whole application, the problem is, i am able to do this only once. here is the code which helps you recreate the problem.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test;

import java.awt.Font;
import java.util.Enumeration;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**
 *
 * @author osiris
 */
public class Test {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws InterruptedException {
        // TODO code application logic here
        JFrame frame = new JFrame();
        frame.setSize(600, 600);
        frame.setVisible(true);
        JButton button = new JButton("test");
        frame.add(button);
        frame.repaint();
        Thread.sleep(2000);
         Font font = new Font("Berlin Sans FB",java.awt.Font.PLAIN,14);
        Enumeration test = UIManager.getDefaults().keys();

        while ( test.hasMoreElements() ) {  

            Object key = test.nextElement();  
            Object value = UIManager.get( key );  
            if ( value instanceof Font ) {  
                UIManager.put( key, font );  
            }  
        }
        SwingUtilities.updateComponentTreeUI(frame);

        Thread.sleep(2000);
         Font font2 = new Font("Tempus Sans ITC",java.awt.Font.PLAIN,14);

         test = UIManager.getDefaults().keys();

        while ( test.hasMoreElements() ) {  

            Object key = test.nextElement();  
            Object value = UIManager.get( key );  
            if ( value instanceof Font ) {  
                UIManager.put( key, font2 );  
            }  
        }
        SwingUtilities.updateComponentTreeUI(frame);
    }
}

The font on the button is changed only once, why is that ? why it is not changed for the second time ?

Anton Giertli
  • 896
  • 2
  • 10
  • 29

2 Answers2

4

Any/all changes to the already visible Container by set/change/modify value(s) to the UIManager/UIDeafaults is Look and Feel rellated issues, than you have to call

SwingUtilities.updateComponentTreeUI(frame);

EDIT if you want to update Font on runtime then you have to change for FontUIResource not simple Font

enter image description hereenter image description hereenter image description here

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import javax.swing.plaf.basic.BasicComboBoxRenderer;

public class SystemFontDisplayer extends JFrame {

    private static final long serialVersionUID = 1L;
    private JFrame frame = new JFrame("Nimbus UIDeafaults and Font");
    private JComboBox fontsBox;
    private javax.swing.Timer timer = null;
    private JButton testButton = new JButton("testButton");
    private JTextField testTextField = new JTextField("testTextField");
    private JLabel testLabel = new JLabel("testLabel");

    public SystemFontDisplayer() {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontFamilyNames = ge.getAvailableFontFamilyNames();
        fontsBox = new JComboBox(fontFamilyNames);
        fontsBox.setSelectedItem(0);
        fontsBox.setRenderer(new ComboRenderer(fontsBox));
        fontsBox.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    final String fontName = fontsBox.getSelectedItem().toString();
                    fontsBox.setFont(new Font(fontName, Font.PLAIN, 16));
                    start();
                }
            }
        });
        fontsBox.setSelectedItem(0);
        fontsBox.getEditor().selectAll();
        frame.setLayout(new GridLayout(4, 0, 20, 20));
        frame.add(fontsBox);
        frame.add(testButton);
        frame.add(testTextField);
        frame.add(testLabel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(200, 105);
        frame.pack();
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                fontsBox.setPopupVisible(true);
                fontsBox.setPopupVisible(false);
            }
        });
        frame.setVisible(true);
    }

    private void start() {
        timer = new javax.swing.Timer(750, updateCol());
        timer.setRepeats(false);
        timer.start();
    }

    public Action updateCol() {
        return new AbstractAction("text load action") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                final Font fnt = new Font(fontsBox.getSelectedItem().toString(), Font.PLAIN, 12);
                final FontUIResource res = new FontUIResource(fnt);
                UIManager.getLookAndFeelDefaults().put("Button.font", res);
                UIManager.getLookAndFeelDefaults().put("TextField.font", res);
                UIManager.getLookAndFeelDefaults().put("Label.font", res);
                SwingUtilities.updateComponentTreeUI(frame);
            }
        };
    }

    public static void main(String arg[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                SystemFontDisplayer systemFontDisplayer = new SystemFontDisplayer();
            }
        });
    }

    private class ComboRenderer extends BasicComboBoxRenderer {

        private static final long serialVersionUID = 1L;
        private JComboBox comboBox;
        final DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
        private int row;

        private ComboRenderer(JComboBox fontsBox) {
            comboBox = fontsBox;
        }

        private void manItemInCombo() {
            if (comboBox.getItemCount() > 0) {
                final Object comp = comboBox.getUI().getAccessibleChild(comboBox, 0);
                if ((comp instanceof JPopupMenu)) {
                    final JList list = new JList(comboBox.getModel());
                    final JPopupMenu popup = (JPopupMenu) comp;
                    final JScrollPane scrollPane = (JScrollPane) popup.getComponent(0);
                    final JViewport viewport = scrollPane.getViewport();
                    final Rectangle rect = popup.getVisibleRect();
                    final Point pt = viewport.getViewPosition();
                    row = list.locationToIndex(pt);
                }
            }
        }

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (list.getModel().getSize() > 0) {
                manItemInCombo();
            }
            final JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, row, isSelected, cellHasFocus);
            final Object fntObj = value;
            final String fontFamilyName = (String) fntObj;
            setFont(new Font(fontFamilyName, Font.PLAIN, 16));
            return this;
        }
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Thanks for this, it certainly helped, but ive still got some issues. I have changed the font to the BOLD, and you see, that the font on the menu is BOLD, but the menu items are still plain, look at the screenshot http://i39.tinypic.com/vfi939.png . Any thoughts why is it like that ? – Anton Giertli Mar 31 '12 at 11:05
  • @Povedz Heslo edit your post with [SSCCE](http://sscce.org/), another issue could be initializations from static class, maybe not relevant, maybe yes – mKorbel Mar 31 '12 at 11:52
  • I edited my first post, dont know what more should i add there – Anton Giertli Mar 31 '12 at 12:41
  • @Povedz Heslo (k***, partizan) this is another issue, this about Nimbus, please that another leaguage, [Changing the Color Theme](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/color.html) for [Numbis UIDefault](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/_nimbusDefaults.html#primary), for more deatails you have to search on this forum about Nimbus change Color, Font, Bachgroung, Painter... – mKorbel Mar 31 '12 at 12:46
  • If i use the default UIManager, then the all items have new changed font, but i still can change this font only once, on the second change, the font on the menu items remains the same and i can see new changed font only when inputting some text :/ – Anton Giertli Mar 31 '12 at 12:53
  • Sorry, but i have no idea what you are talking about and yes, i visited the site. – Anton Giertli Mar 31 '12 at 12:55
  • i have read sscce.org , and i think i provided you with Short, Self Contained, Correct Example – Anton Giertli Mar 31 '12 at 12:58
  • @Povedz Heslo I can't be able to see over your arms to your monitor, and battery not included in my magic globe, simple picture tlaking mi nothing about very specific Look and Feel issue(s) – mKorbel Mar 31 '12 at 12:58
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/9533/discussion-between-povedz-heslo-and-mkorbel) – Anton Giertli Mar 31 '12 at 12:58
  • this's comomn issue about Concurency in Swing, Thread.sleep(int) locking current EventDispatchThread, sometimes with repaint to the GUI, in most cases as demonstrated your code, simple nothing happned, nothing repainted, don't use Thread.sleep(int), use Swing Timer, dirty solution in your case is wrapping code line `SwingUtilities.updateComponentTreeUI(frame);` to the `invokeLater`, please read http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html – mKorbel Mar 31 '12 at 13:37
  • I dont use Thread.sleep() in my application, i used it just to help you see the problem. it does not work even if i dont use sleep. – Anton Giertli Mar 31 '12 at 16:17
  • @Povedz Heslo nothing helped, then another shot to the dark, see may edit to answer :-) – mKorbel Mar 31 '12 at 16:58
  • I have already found the answer, just need to wait hour (there this waiting limit for users with low reputation) and i will post it as an aswer. – Anton Giertli Mar 31 '12 at 17:14
1

The default is a value that is applied when a new UI component is created and no specific override is specified.

If you want to change the default, you must do it before creating the first frame.

To change the font of your whole application after is has created the UI, you need to iterate over all existing components and change their font field (plus force a redraw and possibly a relayout if the font has a different size).

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820