Popular Posts
-
Blogs I Follow:
- Victoria Mui - Blog
Close preview
Loading... - Frank Macchia - Allow Me To Be Frank
Close preview
Loading... - Damian Mellin - Daylightz Design
Close preview
Loading... - Greg Wilson - The Third Bit
Close preview
Loading... - Mike Yoo - Living as Minhoon
Close preview
Loading... - Brian Shim - Now & Then
Close preview
Loading... - Stephen Khuu := Steve Khuu
Close preview
Loading... - Sensorial'Org
Close preview
Loading... - Seriously? @Pi/Pi
Close preview
Loading... - Misa - Trails...
Close preview
Loading...
- Victoria Mui - Blog
-
RSS Links
-
Meta
Drawing Strings in Swing using Graphics2D
I’ve started a new project again, and this time I’m working on a speed-reader application using Java (more details on that later)
One of the problems that I’ve always had with Java Swing UIs is figuring out how to directly draw centered Strings while inside of a
paintComponent(Graphics g)method of someJComponentSo let’s say you’re trying to draw some fancy graphics inside some custom
JPanel. You’ve created your own classMyClasswhich extendsJPanel, and you’ve overrided thepaintComponent(Graphics g)class.You can use
Graphics gfrom withinpaintComponent(Graphics g)to draw a string on the screen at position (x,y) by using the following snippet:g.setColor(Color.black); Font textFont = new Font("Arial", Font.BOLD, 16); g.setFont(textFont); g.drawString("This is my string", this.getWidth()/2, this.getHeight()/2);However, doing so will give you a jaggy, uncentered string. The problem is that Graphics will draw the string starting at the center of the string.
We can work around this by using
Graphics2DandFontMetrics. We can use these two objects to help us find the width and height of the drawn text, and from there we can adjust the coordinates:Graphics2D g2d = (Graphics2D) g; String words = "This is my string"; g2d.setColor(Color.black); Font textFont = new Font("Arial", Font.BOLD, 16); FontMetrics textMetrics = g2d.getFontMetrics(textFont); g2d.setFont(textFont); int centeredX = (this.getWidth()/2) - (textMetrics.stringWidth(words)/2); int centeredY = (this.getHeight()/2) + (textMetrics.getHeight()/2); g2d.drawString(words, centeredX, centeredY);Now, you might notice that the text itself is very jaggie. We can fix this by telling Graphics2D Rendering Hints to turn on anti-aliasing. This can be done by using the line:
And there we have it! Nicely smooth and centered strings!