1

Im In this code, I have a window with a blue box in one of the corners.

I need to get text center aligned on this box.

public class drawComponent extends JComponent {
public void paintComponent(Graphics g){ //called on window update
    int clueHeightDiff= 0;
    int gap = 5;
    int border = 10;
    Font font = new Font("Ariel", Font.PLAIN, 30);
Color blue = new Color(0,0,255);
Color white = new Color(255,255,255);

int winH = Jeopardy.window.getBounds().getSize().height;
int winW = Jeopardy.window.getBounds().getSize().width;
int width = (winW - ((2 * border) + (5 * gap))) / 6 ;
int height = ((winH - ((4*border) + (5 * gap) + clueHeightDiff ))) / 6;
int clueHeight = height + clueHeightDiff;
int Fx = border + (5* width) + (5*gap);
int foY = border + (2*gap) + (2*height) + clueHeightDiff;
Rectangle F2 = new Rectangle(Fx,foY, width , height);
Graphics2D g2f2 = (Graphics2D) g;
g2f2.draw(F2);
g2f2.fill(F2);
g2f2.setColor(blue);
FontMetrics metrics = g2f2.getFontMetrics(font);
    int height = metrics.getHeight();
    int width = metrics.stringWidth(text);
    Dimension size = new Dimension(width+2, height+2);

Given the X and Y bounds of this box, I need the text to fit comfortably inside. I just can't find a way to do this effectively, as according to the documentation, stringwidth() returns the value of only the first character.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
cd3
  • 117
  • 1
  • 9
  • You mean something like [this](http://stackoverflow.com/questions/14284754/java-center-text-in-rectangle/14287270#14287270) – MadProgrammer Mar 25 '15 at 05:04
  • Beware, painting is performed from within the context of the component, that is, 0x0 is the top/left corner of the component, regardless of where it's positioned within it's parent container, you shouldn't be calculating positions relative to other components – MadProgrammer Mar 25 '15 at 05:05
  • @MadProgrammer Im not calculating positions relative to other components... I have widths of borders and gaps between 36 of these squares. This is only a small excerpt of the program, as the whole thing presents a window like this: (http://imgur.com/vwhgLmd) – cd3 Mar 25 '15 at 05:11
  • That's not what `Jeopardy.window.getBounds().getSize().height;` seems to be suggesting...Depending on what you are trying to achieve the, width/height values should be calculated from the component it self, as windows can have other artifacts that can affect their size and not reflect the size of the viewable area. – MadProgrammer Mar 25 '15 at 05:15
  • That's code to get the dimensions of the JFrame, passed from another class. It's set up so the boxes scale according to window size. – cd3 Mar 25 '15 at 05:25
  • Yep, which, if you've setup the layout correctly, the component will already do. The width and height properties of the component will give you the available painting area for the component itself – MadProgrammer Mar 25 '15 at 05:26

1 Answers1

4

FontMetrics#stringwidth will, generally, return the amount of pixels required to render the text

In the box

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane(new Rectangle(150, 150, 50, 50)));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Rectangle boxIn;

        public TestPane(Rectangle boxIn) {
            this.boxIn = boxIn;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            String text = "Hello";
            FontMetrics fm = g2d.getFontMetrics();

            int x = boxIn.x + ((boxIn.width - fm.stringWidth(text)) / 2);
            int y = boxIn.y + (((boxIn.height - fm.getHeight()) / 2) + fm.getAscent());

            g2d.setColor(Color.BLUE);
            g2d.fill(boxIn);
            g2d.setColor(Color.WHITE);
            g2d.drawString(text, x, y);

            g2d.dispose();
        }

    }

}

You can also use TextLayout, which is a little more complictated, but provides you with a bounding box, representing the area that would required to render the text. This is more useful for attributed text, but can still be useful

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • this bounding box, does it also wrap text? – cd3 Mar 25 '15 at 05:23
  • Not in of itself, it can be used in conjunction with a `LineBreakMeasurer`, demonstrated [here](http://docs.oracle.com/javase/tutorial/2d/text/drawmulstring.html) – MadProgrammer Mar 25 '15 at 05:28