String width via fontmetrics calculation is very slow if there are arabic or persian letters in text

后端 未结 4 1408
一向
一向 2021-01-04 03:50

I have a problem. My application interface works much slower if i use eastern languages there. Especially i felt it in components such as JList, JCombobox, JTable.

4条回答
  •  孤独总比滥情好
    2021-01-04 04:06

    I use a cache when calculating the string widths. It don't solve the internal calls that javas own classes do but it solved my performance issues with persian letters (I use a lot of own renders and so on). The Pair class is just a typed bean of two objects...

    public class GuiUtils {
    private static final Map>, Integer> stringWidthCache = new HashMap>, Integer>();
    
    public static int getStringWidth(FontMetrics fm, String text){
        return getStringWidth(null, fm, text);
    }
    
    public static int getStringWidth(Graphics g, FontMetrics fm, String text){
        if(text == null || text.equals("")) {
            return 0;
        }
        Pair> cacheKey = 
                new Pair>(g != null, new Pair(fm, text));
        if (!stringWidthCache.containsKey(cacheKey)) {
            stringWidthCache.put(
                    cacheKey, 
                    g != null ? 
                            (int)Math.ceil(fm.getStringBounds(text, g).getWidth()) :
                                fm.stringWidth(text));
        }
        return stringWidthCache.get(cacheKey);
    }
    

    }

提交回复
热议问题