【问题标题】:How can I make drawString faster in Windows 10?如何在 Windows 10 中使 drawString 更快?
【发布时间】:2021-10-17 09:45:35
【问题描述】:

我的古老应用程序严重依赖于 drawString。在 Windows 10 中至少要慢 20 倍。有没有办法加快在 Windows 中绘制文本的速度?下面的代码说明了区别。

import javax.swing.*;
import java.awt.*;

public class hello{

// hello takes roughly 1 second in Ubuntu 20.04 SDK 11.
// hello takes roughly 2 seconds in Windows 7 Java SDK 1.7.
// hello takes roughly 40 seconds in Windows 10 Java SDK 16.

 public static void main(String[] args) {
        JPanel panel= new JPanel();
        JFrame frame = new JFrame();
        frame.add(panel);
        frame.pack();
        frame.setSize(100,100);
        frame.setVisible(true);
        Graphics g=panel.getGraphics();
        g.setFont(new Font("Arial", Font.PLAIN,12));

        long start_time=System.currentTimeMillis();
        for (int times=0;times<150000;times++)
            g.drawString("hello",50,50);

       System.out.println("total drawString time was "+(System.currentTimeMillis()-start_time));
       System.exit(0);
    }
}

【问题讨论】:

  • 创建一个更真实的minimal reproducible example 来展示你的问题。在实际应用程序中,您不应该使用 getGrraphics() 方法进行绘画。

标签: java swing graphics drawstring


【解决方案1】:

画好后只需要100ms左右:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class SSCCE extends JPanel
{
    public SSCCE()
    {
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        g.setFont(new Font("Arial", Font.PLAIN,12));

        long start_time=System.currentTimeMillis();
        for (int times=0;times<150000;times++)
            g.drawString("hello",50,50);

       System.out.println("total drawString time was "+(System.currentTimeMillis()-start_time));
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new SSCCE());
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//      frame.pack();
        frame.setSize(300, 100);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
    }
}

我在 Windows 10 上使用 JDK11。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 2023-03-16
    • 2015-12-27
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多