2

Is it possible to get how much width and height is painted by Graphics2D instance in method paintComponent?

For example, in the following MessageUnit,

    class MessageUnit extends JPanel {
        String msg;
        JPanel msgBox;

        public MessageUnit(String msg, JPanel msgBox) {
            this.msg = msg;
            this.msgBox = msgBox;
            setPreferredSize(new Dimension(msgBox.getWidth(), 10));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            final Graphics2D g2D = (Graphics2D) g;
            g2D.drawString(msg, 10, 30);
        }
    }

Can I get the height and width used by G2D painting the string so that I can reset size to achieve an effect similar to a responsive layout?

for example, if paining the msg occupy 100px, then I can set the width of MessageUnit to 120px so it looks like that the message is just centred.

And the next message may occupy 60px, then I set the width of the MessageUnit to 80px, it looks like that the message is centred again.

is it possible? Thanks

ildvzg68472
  • 157
  • 1
  • 9
  • I'm not sure what you mean. DYM moving the drawn string around (e.g. to keep it centered in the painted area)? [Yes, base the position on the `getWidth()` & `getHeight()` of the component.] DYM to shrink or expand the string to fill a certain width of the component? [Use `FontMetrics`.] DYM .. ? – Andrew Thompson Dec 01 '21 at 09:12
  • @AndrewThompson I edit the question, Does this revision make the question clear? – ildvzg68472 Dec 01 '21 at 09:29
  • Looks like duplicate of https://stackoverflow.com/questions/27706197/how-can-i-center-graphics-drawstring-in-java?noredirect=1&lq=1 – chptr-one Dec 01 '21 at 09:43
  • *"Does this revision make the question clear?"* Yep. You'll need to combine the two suggestions in my first comment. The `FontMetrics` will provide the width, then `getWidth()` will provide a raw number used to put it at the center. Have at it. – Andrew Thompson Dec 01 '21 at 09:54
  • There is no need to do custom painting. Just use a JLabel and set the text. You can configure the JLabel to center the text in the space available. – camickr Dec 01 '21 at 14:42

1 Answers1

0

If you only need to draw a String you can get it's futur size depending of font & string itself.

public static void setSizeFromFont(Component component, Font font, String text){
    component.setSize((int)(Math.ceil(component.getFontMetrics(font).stringWidth(text))), font.getSize());
  }
Hydrolien
  • 36
  • 4