I'm trying to center a String in a Panel.
Currently I'm doing this:
public void paintComponent(Graphics g) {
super.paintComponent(g);
int stringWidth = 0;
int stringAccent = 0;
int xCoordinate = 0;
int yCoordinate = 0;
// get the FontMetrics for the current font
FontMetrics fm = g.getFontMetrics();
/** display new message */
if (currentMessage.equals(message1)) {
removeAll();
/** Centering the text */
// find the center location to display
stringWidth = fm.stringWidth(message2);
stringAccent = fm.getAscent();
// get the position of the leftmost character in the baseline
xCoordinate = getWidth() / 2 - stringWidth / 2;
yCoordinate = getHeight() / 2 + stringAccent / 2;
// draw String
g.drawString(message2, xCoordinate, yCoordinate);
currentMessage = message2; // alternate message
}
}
Is there a single method I can use to simplify this task?
For example:
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (currentMessage.equals(message1)) {
removeAll();
// draw String centered (with one line of code)
}
}
Just seems like I'm doing a lot of work just to center text.
In the java standard library? No, you can always do something along this
With
Try something like ...
Instead.
Take a look at Java center text in rectangle for additional details
Also, you could achieve the same thing using a
JLabel
on aJPanel
with aGridBagLayout
Updated
Just noticed
removeAll();
inpaintComponent
. This is not a good idea, as it can cause a new repaint request to posted to the event queue, putting your code into an infinte loop which could consume your CPU...Updated with example
Side by side comparison of
drawString
andJLabel
...(drawString
on left,JLabel
on right)