javawhile-loopfontsjframefontmetrics

My while loop for determining an appropriate font size is going too far... sometimes?


I'm doing a project for school that requires me to read a file and make a bar graph with the data read. I have made a class that makes a JFrame and paints rectangles to divide the frame into a section for the name of each data (football player name) and one for the bars (age of player). I have a method that is meant to increase a font size until the longest (printed) string takes up the width that is allotted space, and return a font of that size to be used in the paint method.

It works when the initial JFrame is created, but as I resize it, it sometimes increases the font size 1 to large, but not always. I am at a loss. The console output shows (to me) that the condition of my while loop was not met, but the font size was still increased... any insight would be greatly appreciated. Thanks!

private Font myFont(int allowedW, int allowedH, int numData) {
    // needs to check length of font and size of JFrame and set font (size)
    // accordingly
    String longest = "";
    int fontSize = 1;
    Font f = new Font("SansSerif", Font.BOLD, fontSize);
    for (BarData b : this.graphData) {
        if (getFontMetrics(f).stringWidth(b.getName()) > getFontMetrics(f)
                .stringWidth(longest)) {
            longest = b.getName();
        }
    }
    while ((getFontMetrics(f).stringWidth(longest) < allowedW)){
            //&& ((getFontMetrics(f).getHeight() * numData) < allowedH)) {
            f = new Font("SansSerif", Font.BOLD, fontSize);
        System.out.println(longest);
        System.out.println("length " + getFontMetrics(f).stringWidth(longest));
        System.out.println("allowed width " + allowedW);
        System.out.println(fontSize);
        fontSize++;
    }
    return f;
}

output looks something like this when i drag to resize the jframe:

Demaryius Thomas
length 150
allowed width 158
17
Demaryius Thomas
length 170
allowed width 158
18


Solution

  • Change your while loop like this,

    while ((getFontMetrics(f).stringWidth(longest) < allowedW)){
                //&& ((getFontMetrics(f).getHeight() * numData) < allowedH)) {
            System.out.println(longest);
            System.out.println("length " + getFontMetrics(f).stringWidth(longest));
            System.out.println("allowed width " + allowedW);
            System.out.println(fontSize);
            fontSize++;
            f = new Font("SansSerif", Font.BOLD, fontSize);//your f is not updated after increasing fontSize, if you put it as first statement.
        }
    return new Font("SansSerif", Font.BOLD, fontSize - 1);