Set the same font for all component Java
Solution 1
Here is a simple method that allows you to specify Font to the whole components tree under any Container (or just a simple Component, doesn't matter):
public static void changeFont ( Component component, Font font )
{
component.setFont ( font );
if ( component instanceof Container )
{
for ( Component child : ( ( Container ) component ).getComponents () )
{
changeFont ( child, font );
}
}
}
Simply pass your panel and specific Font into this method and you will get all childs refactored aswell.
Solution 2
- You can use UIManager
to do this....
Eg:
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);
}
}
Solution 3
Set the font values in UIManager
for the components you want to change. For example, you can set the font used for labels by doing:
Font labelFont = ... ;
UIManager.put("Label.font", labelFont);
Note that different look and feels (L&F) may have different properties for the UIManager
class, so if you switch from one L&F to another, you may have issues.
Solution 4
Inspired from Mikle Grains Answer I used his code to increase the font of each component in percentage by getting the old fontsize
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);
}
}
}
Luca
Updated on July 27, 2022Comments
-
Luca almost 2 years
I want to set a specific font for all component in a
JPanel
but I prefer that the question is still more general and not limited to the JPanel. How can I set the font to a list of component in a container (JFrame or JPanel)?