Lucien
Lucien

Reputation: 896

Java Get Size of Font

I have JFrame with a JTextArea inside of it.

Font font = new Font("monospaced", Font.PLAIN, 14);
textarea.setFont(font);

Since the font is monospaced, all characters are the same width and height.

I'd like to know what this width and height is in pixels.

For this, I could use font.getStringBounds but I have no Graphics context to pass to it. frame.getGraphics() returns null.

How can I find the size of a character? Can it be done without a Graphics instance? I don't want an instance of it anyway. I just want to know how big my characters are.

Upvotes: 0

Views: 1378

Answers (2)

Dinh
Dinh

Reputation: 779

You can use JFrame#getFontMetrics since one of JFrame's Superclass is Component.

If this does not work, you can also use BufferedImage to get a Graphics object:

BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);

You can use the image object to get an instance of Graphics.

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347324

FYI, I am using a JFrame/JTextarea to render a text based game, so I'll use this info for scaling the text and getting the dimensions of the window in units of characters

It's probably not the best approach, it would be better to simply use JTextArea#setColumns and JTextArea#setRows which will use the font based information to make determinations about it's preferred size automatically

You can then make use of the LayoutManager APIs and simply call pack on the JFrame which will pack the window around the contents, based on it's preferred size

This will also affect the preferred size of JScrollPane

Upvotes: 1

Related Questions