Solved

Using Graphics::drawString() to center some text

Posted on 2007-11-29
6
4,053 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
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
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 500 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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
array6 challenfge 6 62
What is JNDI datasource in spring 1 38
Error with Java/Cache JDBC Classpath 2 19
Java Jpanels and Jframe 8 20
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
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 will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

706 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now