2012-03-31 77 views
6

Por favor, ¿hay otra manera de cómo cambiar la fuente en tiempo de ejecución como el uso de FontUIResource, para toda la GUI AWT/Swing, sin ningún conocimiento/intereses sobre si hay variables locales y tipo de JComponentsCambiar fuente en tiempo de ejecución

enter image description hereenter image description here

import java.awt.*; 
import java.awt.event.*; 
import java.util.Locale; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
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(Locale.getDefault()); 
     fontsBox = new JComboBox(fontFamilyNames); 
     fontsBox.setSelectedItem(0); 
     fontsBox.setRenderer(new ComboRenderer()); 
     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); 
       /*try { 
        LookAndFeel lnf = UIManager.getLookAndFeel().getClass().newInstance(); 
        final FontUIResource res = new FontUIResource(fnt); 
        UIDefaults uiDefaults = lnf.getDefaults(); 
        uiDefaults.put("Button.font", res); 
        uiDefaults.put("TextField.font", res); 
        uiDefaults.put("Label.font", res); 
        UIManager.getLookAndFeel().uninitialize(); 
        UIManager.setLookAndFeel(lnf); 
       } catch (InstantiationException ex) { 
        Logger.getLogger(SystemFontDisplayer.class.getName()).log(Level.SEVERE, null, ex); 
       } catch (IllegalAccessException ex) { 
        Logger.getLogger(SystemFontDisplayer.class.getName()).log(Level.SEVERE, null, ex); 
       } catch (UnsupportedLookAndFeelException ex) { 
        Logger.getLogger(SystemFontDisplayer.class.getName()).log(Level.SEVERE, null, ex); 
       } 
       UIDefaults defaults = UIManager.getDefaults(); 
       final FontUIResource res = new FontUIResource(fnt); 
       defaults.put("Button.font", res); 
       defaults.put("TextField.font", res); 
       defaults.put("Label.font", res); 
       SwingUtilities.updateComponentTreeUI(frame);*/ 
       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[]) { 
     /*try { 
      for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) { 
       if ("Nimbus".equals(laf.getName())) { 
        UIManager.setLookAndFeel(laf.getClassName()); 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     }*/ 
     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; 

     @Override 
     public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
      super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); 
      final Object fntObj = value; 
      final String fontFamilyName = (String) fntObj; 
      setFont(new Font(fontFamilyName, Font.PLAIN, 16)); 
      return this; 
     } 
    } 
} 

.

EDIT: He publicado narrativa con Nimbus, luego el código para Nimbus

import java.awt.*; 
import java.awt.event.*; 
import java.util.Locale; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
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(Locale.getDefault()); 
     fontsBox = new JComboBox(fontFamilyNames); 
     fontsBox.setSelectedItem(0); 
     fontsBox.setRenderer(new ComboRenderer()); 
     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); 
       try { 
        LookAndFeel lnf = UIManager.getLookAndFeel().getClass().newInstance(); 
        final FontUIResource res = new FontUIResource(fnt); 
        UIDefaults uiDefaults = lnf.getDefaults(); 
        uiDefaults.put("Button.font", res); 
        uiDefaults.put("TextField.font", res); 
        uiDefaults.put("Label.font", res); 
        UIManager.getLookAndFeel().uninitialize(); 
        UIManager.setLookAndFeel(lnf); 
       } catch (InstantiationException ex) { 
        Logger.getLogger(SystemFontDisplayer.class.getName()).log(Level.SEVERE, null, ex); 
       } catch (IllegalAccessException ex) { 
        Logger.getLogger(SystemFontDisplayer.class.getName()).log(Level.SEVERE, null, ex); 
       } catch (UnsupportedLookAndFeelException ex) { 
        Logger.getLogger(SystemFontDisplayer.class.getName()).log(Level.SEVERE, null, ex); 
       } 
       UIDefaults defaults = UIManager.getDefaults(); 
       final FontUIResource res = new FontUIResource(fnt); 
       defaults.put("Button.font", res); 
       defaults.put("TextField.font", res); 
       defaults.put("Label.font", res); 
       SwingUtilities.updateComponentTreeUI(frame); 
       /*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[]) { 
     try { 
      for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) { 
       if ("Nimbus".equals(laf.getName())) { 
        UIManager.setLookAndFeel(laf.getClassName()); 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     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; 

     @Override 
     public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
      super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); 
      final Object fntObj = value; 
      final String fontFamilyName = (String) fntObj; 
      setFont(new Font(fontFamilyName, Font.PLAIN, 16)); 
      return this; 
     } 
    } 
} 
+0

+1 para [sscce] (http://sscce.org/); ver también ['FontShower'] (http://mindprod.com/applet/fontshower.html). – trashgod

+0

Notas secundarias: solo necesita una instancia de 'javax.swing.Timer'; solo necesita un 'setSelectedItem()'; considere 'getAvailableFontFamilyNames (Locale.getDefault())'. Funciona en Mac OS. – trashgod

+0

@trashgod seguro una vez más parte de mis balasts inútiles, anteriormente he auto_select para JComboBox de Timer y luego cambio la fuente por valor del elemento seleccionado de JComboBox, lo siento por eso – mKorbel

Respuesta

1

Por ejemplo: Crear una nueva fuente de la lista FontFamily, y aplicarlo a su componente con c.setFont (fuente);

Un segundo enfoque es, para buscar archivos TTF (por ejemplo), y crear nuevas fuentes con el método estático Font.createFont (nuevo archivo ("..."));

Esta sencilla aplicación creará una Lista de fuentes por familia y la aplicará a un JButton y JTextField.

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 
/** 
    FontSwitcher 

    @author Stefan Wagner 
    @date So 13. Mai 03:25:23 CEST 2012  
*/ 
public class FontSwitcher extends JFrame implements ActionListener 
{ 
    private static final String progname = "FontSwitcher 0.1"; 

    private JTextField feedback; 
    private JButton jb; 
    private JList fontList; 

    public FontSwitcher() 
    { 
     super (progname); 
     JPanel mainpanel = new JPanel(); 
     mainpanel.setLayout (new BorderLayout()); 
     this.getContentPane().add (mainpanel); 

     GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); 
     String [] fonts = ge.getAvailableFontFamilyNames(); 
     fontList = new JList (fonts); 
     JScrollPane js = new JScrollPane (fontList); 

     feedback = new JTextField ("Feedback"); 
     jb = new JButton ("apply font"); 
     jb.addActionListener (this); 
     mainpanel.add (feedback, BorderLayout.NORTH); 
     mainpanel.add (js, BorderLayout.CENTER); 
     mainpanel.add (jb, BorderLayout.SOUTH); 

     setSize (400, 800); 
     setLocation (100, 100); 
     setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
     setVisible (true); 
    } 

    public void actionPerformed (final ActionEvent e) 
    { 
     SwingWorker worker = new SwingWorker() 
     { 
      protected String doInBackground() throws InterruptedException 
      { 
       String cmd = e.getActionCommand(); 
       if (cmd.equals ("apply font")) 
       { 
        String selectedFont = fontList.getSelectedValue().toString(); 
        Font font = new Font (selectedFont, Font.TRUETYPE_FONT, 14); 
        jb.setFont (font); 
        feedback.setFont (font); 
       } 
       return "done"; 
      } 
      protected void done() 
      { 
       feedback.setText ("done"); 
      } 
     }; 
     worker.execute(); 
    } 

    public static void main (final String args[]) 
    { 
     Runnable runner = new Runnable() 
     { 
      public void run() 
      { 
       new FontSwitcher(); 
      } 
     }; 
     EventQueue.invokeLater (runner); 
    } 
} 
+0

aaach ahora veo que mi pregunta no está bien hecha, seguro que extraño allí para toda la interfaz gráfica de AWT/Swing, sin ningún interés sobre la variable local, danke – mKorbel

+0

@mKorbel: Lo siento, no estoy seguro si lo entiendo. Solo está interesado en cambiar todo el aspecto, las fuentes para todos los componentes, ¿no individualmente? Y está buscando un segundo enfoque, solo por puro interés, ¿no con un problema específico que no puede resolver? ¿Has buscado "LookAndFeel"? Leí algo al respecto hace años, pero no lo investigué. Creo que se trata de cambiar toda la apariencia de una aplicación, y también debería cambiar las fuentes. –

+0

Otra idea sería un visitante, que recorre todo su GUI-Tree (no sé qué tan difícil es) y aplica alguna fuente en todas partes. –

Cuestiones relacionadas