2012-10-04 37 views
7

我想爲JPanel中的所有組件設置特定的字體,但我更喜歡這個問題仍然更一般,並且不限於JPanel。如何將字體設置爲容器中的組件列表(JFrame或JPanel)?爲所有組件設置相同的字體Java

回答

3

爲您想要更改的組件設置UIManager的字體值。例如,你可以通過執行設定用於標籤的字體:

Font labelFont = ... ; 
UIManager.put("Label.font", labelFont); 

注意,不同的外觀和感覺(L & F)可能對UIManager類不同的屬性,因此,如果您從一個L & F開關到另一個,你可能會有問題。

+0

增加百分比每個組件的字體。如果我使用UIManager我改變字體的組件在整個應用程序,但我只能在特定的「JFrame」或「JPanel」中進行更改。謝謝 – Luca

8

-您可以使用UIManager做到這一點....

如:

public class FrameTest { 

    public static void setUIFont(FontUIResource f) { 
     Enumeration keys = UIManager.getDefaults().keys(); 
     while (keys.hasMoreElements()) { 
      Object key = keys.nextElement(); 
      Object value = UIManager.get(key); 
      if (value instanceof FontUIResource) { 
       FontUIResource orig = (FontUIResource) value; 
       Font font = new Font(f.getFontName(), orig.getStyle(), f.getSize()); 
       UIManager.put(key, new FontUIResource(font)); 
      } 
     } 
    } 

    public static void main(String[] args) throws InterruptedException { 

     setUIFont(new FontUIResource(new Font("Arial", 0, 20))); 

     JFrame f = new JFrame("Demo"); 
     f.getContentPane().setLayout(new BorderLayout()); 

     JPanel p = new JPanel(); 
     p.add(new JLabel("hello")); 
     p.setBorder(BorderFactory.createTitledBorder("Test Title")); 

     f.add(p); 

     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setSize(300, 300); 
     f.setVisible(true); 
    } 
} 
+0

如果我使用UIManager,我會在整個應用程序中將字體更改爲組件,但我不會只在特定的「JFrame」或「JPanel」中更改它。謝謝 – Luca

16

這裏有一個簡單的方法,使您可以指定字體,以在整個組件樹任何容器(或​​只是一個簡單的組件,無所謂):

public static void changeFont (Component component, Font font) 
{ 
    component.setFont (font); 
    if (component instanceof Container) 
    { 
     for (Component child : ((Container) component).getComponents()) 
     { 
      changeFont (child, font); 
     } 
    } 
} 

只需傳遞y我們的面板和特定的字體到這個方法,你會得到所有的孩子重構。

+0

真棒,它的工作很棒,我已經改變了你的代碼這樣,並幫助我,我在答覆中發佈代碼 –

2

從Mikle穀物啓發回答 我用他的代碼,通過讓老字號

public static void changeFont(Component component, int fontSize) { 
    Font f = component.getFont(); 
    component.setFont(new Font(f.getName(),f.getStyle(),f.getSize() + fontSize)); 
    if (component instanceof Container) { 
     for (Component child : ((Container) component).getComponents()) { 
      changeFont(child, fontSize); 
     } 
    } 
} 
相關問題