Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Using Graphics::drawString() to center some text

Posted on 2007-11-29
6
Medium Priority
?
4,067 Views
Last Modified: 2012-08-13
Hi,

Is there  a way to render text centered, using Graphics::drawString()?

Thanks
0
Comment
Question by:DJ_AM_Juicebox
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 7

Expert Comment

by:UrosVidojevic
ID: 20376113
You want to center text inside some rectangle for example?
0
 
LVL 17

Expert Comment

by:contactkarthi
ID: 20376139
drawString(String str, int x,  int y)

try something like
x = widthOfApplet/2 - str.length()/2
0
 

Author Comment

by:DJ_AM_Juicebox
ID: 20376186
@UrosVidojevic:
yes i want to center it inside a rectangle. I can't find anything like we have under win32 development!

@contactkarthi:
doesn't that assume a fixed width font?
0
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 
LVL 7

Expert Comment

by:UrosVidojevic
ID: 20376232
Here is an example of how you can center text inside a panel.

http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter06/text.html
0
 
LVL 25

Accepted Solution

by:
InteractiveMind earned 2000 total points
ID: 20376344
Use the FontMetrics for your font, to calculate the width of the string.


Font myFont = new Font("Verdana", Font.PLAIN, 11);
FontMetrics myFontMetrics = getFontMetrics(myFont);
..
String str="I am in the centre!";

int stringWidth=myFontMetrics.stringWidth(str);
int stringHeight=myFontMetrics.getHeight();

g.setFont(myFont);
g.drawString(str, panelWidth/2 - stringWidth/2, panelHeight/2+stringHeight/2);
0
 
LVL 7

Expert Comment

by:UrosVidojevic
ID: 20376404
Example of centring text inside specified rectangle.

import java.awt.*;
import javax.swing.*;

class CenterPanel extends JPanel {
      private int x, y, w, h;
      private String txt;
      
      CenterPanel(int x, int y, int w, int h, String txt) {
            this.x = x; this.y = y; this.w = w; this.h = h; this.txt = txt;
      }
      
      public void paintComponent(Graphics g) {
            super.paintComponent(g);
            
            /* this part draws centred text */
            FontMetrics fm = g.getFontMetrics ();
            
            int txt_width = fm.stringWidth (txt);
            int ascent = fm.getMaxAscent ();
            int descent= fm.getMaxDescent ();

            int txt_x = x + (w-txt_width) / 2;
          int txt_y = y+h/2 - descent/2 + ascent/2;

          g.drawString (txt, txt_x, txt_y);
          g.drawRect(x, y, w, h);
            
      }
}

public class CenterText extends JFrame {
      public CenterText() {
            super("Center Text");
            
            getContentPane().add(new CenterPanel(100, 100, 300, 200, "Center this text"));
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            setSize(600, 400);
      }
      
      public static void main(String[] args) {
            new CenterText();
      }
}
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Suggested Courses

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question