0

How can I resize the font from a textfield? I have written a paintText method, which is called with paintComponent. The resizing in a smaller font size works like a charm but scaling it up again does not, because I have no minimum width.

How can I get the minimum char size of a font to achieve a scaling up?

g.setColor(getForeground());
        if (this.getFont() != null && this.getText() != null) {
            FontMetrics fm = getFontMetrics(getFont());

            if(fm.stringWidth(this.getText()) >= (this.getWidth()-(4*borderWidth+1))) {
                if(this.getFont().getSize() >= 8) {
                    this.setFont(new Font(this.getFont().getName(), this.getFont().getStyle(), this.getFont().getSize() - 2));
                    //fm = getFontMetrics(getFont());
                }

            } else if(fm.stringWidth(this.getText()) < (this.getWidth()-(4*borderWidth+fm.stringWidth(getText())))) {
                this.setFont(new Font(this.getFont().getName(), this.getFont().getStyle(), this.getFont().getSize() + 2));
                //fm = getFontMetrics(getFont());
            }
            fm = getFontMetrics(getFont());
            //g.setColor(this.getForeground());
            g.drawString(this.getText(), ((this.getWidth() / 2) - (fm.stringWidth(this.getText()) / 2)),
                    ((this.getHeight() / 2) + fm.getMaxDescent()));

The bordersize is just a distance to the couter edge of the component.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
F_Schmidt
  • 902
  • 1
  • 11
  • 32
  • Set the new font, draw a String, measure the font in pixels. Repeat by increasing the font size 2 points at a time until the font is too large. Back off 2 points. – Gilbert Le Blanc Mar 31 '20 at 13:23
  • I am setting a font and then drawing the string. Now I just need a small ɛ that represents the distance between the size where the font needs to be smaller and the minimum size where the old font reaches a maximum size. Therefore I thought that I should get the minimum char size of a font. How is that possible? – F_Schmidt Mar 31 '20 at 13:26

0 Answers0