How to set font weight in Java for Swing components

I want to set various fonts> for components in a JFrame dialog. How to do it?

In the Java instruction below

setFont(new Font("Dialog", Font.BOLD, 12)); 

when I use Font.BOLD it is too bold and when I use Font.Plain it is too simple. I want something in between.

+8
java fonts swing font-size
source share
2 answers

welle is partially correct. You can use TextAttributes to get the font:

 Map<TextAttribute, Object> attributes = new HashMap<>(); attributes.put(TextAttribute.FAMILY, Font.DIALOG); attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD); attributes.put(TextAttribute.SIZE, 12); label.setFont(Font.getFont(attributes)); 

A better approach is to get the font from the font installed on the Swing component using appearance:

 Font font = label.getFont(); font = font.deriveFont( Collections.singletonMap( TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD)); label.setFont(font); 

This will preserve the font family and size that users can set in their desktop settings for easy reading.

+6
source share

maybe I'm wrong, but I think the Font class only has a Bold, simple, but you can change it after the number

 setFont(new Font("Dialog", Font.BOLD, 12)); setFont(new Font("Dialog", Font.plain, 27)); 

but in java.awt.font.TextAttribute class

you have WEIGHT_BOLD and WEIGHT_SEMIBOLD ...

+1
source share

All Articles