• Advertisement
Sign in to follow this  

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

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by gretty
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.


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 this post


Link to post
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);

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement