Reputation: 1
so i have a drawimage and i need the string centered the drawimage is 64 pixels wide and i need the text to center its self in the center.
this is the code i have right now. this x - Component.sX Stops the item from moving away from the character.
g.drawString(username,(int) (x - Component.sx), (int) y- (int) Component.sY - 2);
this is what i need it centered to.
https://i.sstatic.net/GbxTo.png
Upvotes: 0
Views: 72
Reputation: 285430
Myself, I'd use a JLabel to display my text. You can give the container a BorderLayout, add the JLabel to the BorderLayout.PAGE_START position and then call
setHorizontalAlignement(SwingConstants.CENTER)
to be sure that its text is centered.
Edit
You state:
my game uses drawimage drawstring ect.
If you can't change this, then you'll need to use FontMetrics to help you calculate the width and height of your Strings, and then use this information and the width and height of your component to help decide where to place Strings. This will mean more error-prone calculations that will be your responsibility.
Upvotes: 1