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 some JComponent
So let’s say you’re trying to draw some fancy graphics inside some custom JPanel. You’ve created your own class MyClass which extends JPanel, and you’ve overrided the paintComponent(Graphics g) class.
You can use Graphics g from within paintComponent(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 Graphics2D and FontMetrics. 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:
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
And there we have it! Nicely smooth and centered strings!