在我的应用程序中,我大量使用了 JEditorPane 中显示的动画 gif 图像(这是一个聊天)。现在我意识到 GIF 消耗了大量的 CPU(在某些情况下接近 100%),并且使用的内存继续无限增加。
如何避免这种情况?或者,您能否推荐另一个组件来替换 JEditorPane 以获得更好的性能?
这是一个可以显示内存增加和 CPU 使用率的示例。
public class TestCPU extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestCPU frame = new TestCPU();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestCPU() {
setIconImage(Toolkit.getDefaultToolkit().getImage(TestCPU.class.getResource("/images/asd.png")));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{1.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 0;
contentPane.add(scrollPane, gbc_scrollPane);
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
String html = "<html>";
for (int i = 0; i < 500; i++) {
html = html + "<img src="+ TestCPU.class.getResource("/images/asd.gif") + ">";
}
editorPane.setText(html);
scrollPane.setViewportView(editorPane);
}
}
测试中使用的图像