开发者

Swing load available font family slow down the performance

开发者 https://www.devze.com 2023-01-07 15:41 出处:网络
After I add in this code to load the available font family and add it in to combobox GraphicsEnvironment ge = GraphicsEnvironment.

After I add in this code to load the available font family and add it in to combobox

 GraphicsEnvironment ge = GraphicsEnvironment.
  getLocalGraphicsEnvironment();
String[] fontNames = ge.getAvailableFontFamilyNames();

It load very slow took about 7 seconds to show the page when i trigger the page. After i take it out it load fine as normal. Is there any solution, any people facein开发者_如何学编程g the same problem?


The delay is due to the fact that getAvailableFontFamilyNames creates a 1 pt font for every font it can find. It allows the JVM to distinguish between fonts it can use and things that only look like they may be fonts.

The best approach is to call it in a SwingWorker and then update the combo from the done method.

update: The poster's code updated to use the generified SwingWorker. Note: I am returning the array of names as it eliminates the need for synchronization.

SwingWorker aWorker<String[],Void> = new SwingWorker<String[],Void>() {
    protected void done() { 
        String[] fontNames = get();
        for (int i = 0; i < fontNames.length; i++) 
            fontFamily.addItem(fontNames[i]);
    }
    @Override
    protected String[] doInBackground() throws Exception {
        GraphicsEnvironment env = GraphicsEnvironment .getLocalGraphicsEnvironment();
        return env.getAvailableFontFamilyNames(); 
    }
};
aWorker.run();


Just load it in the background () when you app starts. By the time user opens the page it will be loaded.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号