2012-03-31 20 views
6

prega c'è un altro modo per cambiare il font in fase di esecuzione come l'utilizzo FontUIResource, per tutta la GUI AWT/Swing, senza alcuna conoscenza/interesse per se ci sono le variabili locali e tipo di JComponentsCambia carattere in fase di esecuzione

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: ho postato narrativa con Nimbus, poi il codice per 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 per [sscce] (http://sscce.org/); vedere anche ['FontShower'] (http://mindprod.com/applet/fontshower.html). – trashgod

+0

Note secondarie: serve solo un'istanza di 'javax.swing.Timer'; solo bisogno di un 'setSelectedItem()'; considera 'getAvailableFontFamilyNames (Locale.getDefault())'. Funziona su Mac OS. – trashgod

+0

@trashgod sicuramente parte dei miei inutili balasts, in precedenza ho auto_select per JComboBox da Timer e poi cambio Font in base al valore dell'elemento selezionato di JComboBox, mi dispiace per l'aggiornamento – mKorbel

risposta

1

Per esempio: Creazione di un nuovo tipo di carattere dall'elenco FontFamily, e applicarlo al componente con c.setFont (font);

Un secondo approccio è la ricerca di file TTF (ad esempio) e la creazione di nuovi tipi di carattere con il metodo statico Font.createFont (nuovo file ("..."));

Questa semplice applicazione creerà un elenco di caratteri per famiglia e lo applicherà a JButton e 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 ora vedo che la mia domanda non è stata posta correttamente, sicuramente mi manca lì per l'intera GUI AWT/Swing, senza alcun interesse sulla variabile locale, danke – mKorbel

+0

@mKorbel: Mi dispiace, non sono sicuro se capisco. Ti interessa solo cambiare l'intero look, i font per tutti i componenti, non singolarmente? E stai cercando un secondo approccio, solo dal puro interesse - non con un problema specifico che non puoi risolvere? Hai cercato "LookAndFeel"? Ho letto qualcosa a riguardo anni fa, ma non l'ho investigato. Penso che si tratti di cambiare l'aspetto di un'applicazione, e anche di cambiare i caratteri. –

+0

Un'altra idea sarebbe un visitatore, che attraversa l'intero albero della GUI (non so quanto sia difficile) e applica un font ovunque. –

Problemi correlati