Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Centering text on object drawn with Graphics

 
Michael Boehm
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, Graphics is not such an easy class :S

I have a a derived JPanel inside a JFrame. In the Panel I have a circle drawn using drawOval in Graphics which takes the x- and y-coords for the upper left point in the box bounding the oval and with and height. I need to write a single character in the center of the drawn circle. Is there any methods which can assist in doing this precisely or do I have to "hack around" ?
 
Martin Vanyavchich
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hack around
 
Darryl Burke
Bartender
Posts: 5126
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Create an Icon that draws the circle, set the Icon and text to a JLabel with appropriate horizontal and vbertical text position and alignments. No hacking at all. Something like (uncompiled, untested, imports omitted)JLabel = new JLabel(text, new CircleIcon(diameter), JLabel.CENTER);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);[/code]Apologies for any and all typos.
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Class FontMetrics will return the width of Strings when painted using its matching Font.
 
Michael Boehm
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the hints !
This
Rob Prime wrote:Class FontMetrics will return the width of Strings when painted using its matching Font.

lead me to the getStringBounds method in FontMetrics. Very useful for this particular problem, now I just have to do a bit of elementary school trig
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to our GUIs forum, where we usually discuss such questions.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> now I just have to do a bit of elementary school trig

a circle is just a square with rounded corners,
so it shouldn't be that hard to get height/2, width/2
 
pete stein
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For my money, Darryl's solution is the laziest, and I'm all about effective but lazy programming.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic