- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do you get the font metrics in Java Swing?
To get the font metrics, use the FontMetrics class:
Graphics2D graphics = (Graphics2D) gp.create(); String str = getWidth() + "(Width) x (Height)" + getHeight(); FontMetrics m = graphics.getFontMetrics();
Now to display it:
int xValue = (getWidth() - m.stringWidth(str)) / 2; int yValue = ((getHeight() - m.getHeight()) / 2) + m.getAscent(); graphics.drawString(str, xValue, yValue);
The following is an example to get the font metrics in Java Swing:
Example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Color; import javax.swing.JFrame; import javax.swing.JPanel; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Font Metrics"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new Demo()); frame.pack(); frame.setVisible(true); System.out.println(frame.getSize()); } } class Demo extends JPanel { @Override public Dimension getPreferredSize() { return new Dimension(500, 500); } @Override protected void paintComponent(Graphics gp) { super.paintComponent(gp); Graphics2D graphics = (Graphics2D) gp.create(); String str = getWidth() + "(Width) x (Height)" + getHeight(); FontMetrics m = graphics.getFontMetrics(); int xValue = (getWidth() - m.stringWidth(str)) / 2; int yValue = ((getHeight() - m.getHeight()) / 2) + m.getAscent(); graphics.drawString(str, xValue, yValue); graphics.dispose(); } }
Output
- Related Articles
- How to change font size with HTML in Java Swing JEditorPane?
- How do you change the default font color for all text in Matplotlib?
- How do you get the index of an element in a list in Java?
- How do you get the file size in C#?
- How to get the number of rows and columns of a JTable in Java Swing
- How do you get a timestamp in JavaScript?
- How do you get the purest form of Cocaine?
- How to maximize JFrame in Java Swing
- Explain the architecture of Java Swing in Java?
- How do you add two lists in Java?
- How do you copy a list in Java?
- How do you create a list in Java?
- How to change Button Border in Java Swing
- How to make a canvas in Java Swing?
- How do you get the current figure number in Python's Matplotlib?

Advertisements