Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set font weight in Java for Swing components

I want to set different font weights for components on my JFrame dialog. How do I do this?

In the below Java statement

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 plain. I want something in-between.

like image 499
CRM Avatar asked Jul 31 '14 08:07

CRM


People also ask

How do I change the font style in swing?

To set the font for a Swing component, use its setFont() method of the component. JButton closeButton = new JButton("Close"); closeButton. setFont(f4);

How do I increase the font size of a swing label?

We change the Font Size parameter to change the size of the JLabel Font. The use of the Font() function is shown below: Object. setFont(new Font("Font-Style", Font-Weight, Font Size));

What fonts can I use in Java Swing?

Logical fonts are the five font families defined by the Java platform which must be supported by any Java runtime environment: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical fonts are not actual font libraries.


2 Answers

welle is partially correct. You can use TextAttributes to obtain a 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 derive your font from the font installed on the Swing component by the look-and-feel:

Font font = label.getFont();

font = font.deriveFont(
    Collections.singletonMap(
        TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD));

label.setFont(font);

That will preserve the font's family and size, which users may have set in their desktop preferences for readability reasons.

like image 68
VGR Avatar answered Oct 01 '22 14:10

VGR


maybe i wrong but i think class Font has only Bold ,plain but you can change after that in number

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

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

but in class java.awt.font.TextAttribute

you have WEIGHT_BOLD and WEIGHT_SEMIBOLD ...

like image 41
csWael Avatar answered Oct 01 '22 14:10

csWael