# [java] Swing - Draw a String onto a JPanel Centred

This topic is 3013 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello

I am trying to find a way to draw string onto a JPanel but I want to make the string centred in the JPanel (both vertically & horizontally).

I am currently using the function drawString("", x, y) & I also use some maths to find the central point of the JPanel & the string parameter. But is there a function that can do all of this for me?

I know I could also put the string into a JComponent, then set the JPanel layout to some layout that will allign the JComponent in the centre, but I am using the JPanel like a canvas & drawing shapes & stuff on it, so I (think?) it would be easier if I just use a drawing function to display my string "Welcome blah....." in the centre of the JPanel.

thx for ur time.

##### Share on other sites
Quote:
 Original post by grettyHelloI am trying to find a way to draw string onto a JPanel but I want to make the string centred in the JPanel (both vertically & horizontally).I am currently using the function drawString("", x, y) & I also use some maths to find the central point of the JPanel & the string parameter. But is there a function that can do all of this for me?I know I could also put the string into a JComponent, then set the JPanel layout to some layout that will allign the JComponent in the centre, but I am using the JPanel like a canvas & drawing shapes & stuff on it, so I (think?) it would be easier if I just use a drawing function to display my string "Welcome blah....." in the centre of the JPanel.thx for ur time.

Take a look at Font.getStringBounds(String,Graphics)

It returns a bounding rectangle (Rectangle2D)

so something like ..

Font someFont ...;Graphics g = panel.getGraphics();g.setFont(f);Rectangle2D rect = f.getStringBounds("Some Cool String",g);g.drawString("Some Cool String",panel.getWidth()/2 - rect.getWidth()/2 , panel.getHeight()/2 - rect.getHeight()/2);//ofcourse you can set y to something else if you don't want to center it vertically

##### Share on other sites
Awesome, thanks for the example code :D

##### Share on other sites
Looks like i made a slight mistake, the getStringBounds method that takes a String and a Graphics object is a part of FontMetrics , not Font , the getStringBounds method in the Font class wants a FontRenderContext.

so you probably want

Font someFont = new Font(Font.SANS_SERIF, FONT.PLAIN, 14);Graphics g = panel.getGraphics();g.setFont(f);Rectangle2D rect = g.getFontMetrics().getStringBounds("Some Cool String",g);g.drawString("Some Cool String",panel.getWidth()/2 - rect.getWidth()/2 , panel.getHeight()/2 - rect.getHeight()/2);

1. 1
Rutin
30
2. 2
3. 3
4. 4
5. 5

• 13
• 13
• 11
• 10
• 14
• ### Forum Statistics

• Total Topics
632961
• Total Posts
3009494
• ### Who's Online (See full list)

There are no registered users currently online

×