Home > database >  Is it possible to get adaptive Width & Height after Graphics2D finish painting in paintComponent?
Is it possible to get adaptive Width & Height after Graphics2D finish painting in paintComponent?

Time:12-03

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

CodePudding user response:

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());
  }
  • Related