I'm currently writing a customized text editor in Java, and as part of that, I want to make it easy for the user to increase or decrease the font size in the text editing area (technically a JTextPane). I didn't expect this to be easy, but I've been pleasantly surprised that the following approach seems to work just fine:
/**
* Reduce the size of the font in the JTextPane editor area.
*/
public void doSmallerFontSizeAction()
{
// get the current font
Font f = editingArea.getFont();
// create a new, smaller font from the current font
Font f2 = new Font(f.getFontName(), f.getStyle(), f.getSize()-1);
// set the new font in the editing area
editingArea.setFont(f2);
}
Java smaller font size action - discussion
As you can see from that code, I do the following things:
- I get the current font from the JTextPane.
- I create the Font
f2by using that font information, but making the font size one size smaller. - I set my new font on the JTextPane.
This changes the font for the entire JTextPane, which is what I want. (Although the JTextPane has many more font features, I'm just creating a simple text editor, so I'm only using one font at a time in the text editing area.)
It's also worth mentioning that I have a similar method that increases the text area font size. As you can imagine, the code is identical, except I increment the font size by one instead of decrementing it.
Java font size methods comes from JTextComponent
As mentioned, I'm using this code with a JTextPane but the getFont and setFont methods both come from the JTextComponent class, so I expect this same approach would work with the JTextField JTextArea and JEditorPane classes as well.

