Search code examples
javaswinguser-interfacejtextfield

How to set letter spacing in Java Swing GUI?


In CSS, there is a letter-spacing property that we can use to increase spacing per letter in a word.

Is there a way I can increase a letter space or text space? I was hoping I can increase the space of the text in a field.


Solution

  • Here is an example:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JLabel label = new JLabel("This is a text.");
            Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
            attributes.put(TextAttribute.TRACKING, 0.5);
    
            label.setFont(label.getFont().deriveFont(attributes));
            JOptionPane.showMessageDialog(null, label);
        });
    }
    

    Result:

    preview