【发布时间】:2021-04-05 16:56:09
【问题描述】:
我需要将一个 URL 加载到 JEditorPane 中,然后从 JEditorPane 中获取一个 BufferedImge,我下面的代码将为我提供一个空白/黑色图像:
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.html.*;
import java.io.*;
public class Html_Browser
{
public static void main(String[] args)
{
Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
JEditorPane editorPane=new JEditorPane();
editorPane.setEditorKit(new HTMLEditorKit());
editorPane.setEditable(false);
try
{
editorPane.setPage("https://news.yahoo.com/");
Thread.sleep(3000);
BufferedImage saveimg=new BufferedImage((int)screenSize.getWidth(),(int)screenSize.getHeight()-36,BufferedImage.TYPE_INT_RGB);
Graphics2D g2=saveimg.createGraphics();
editorPane.paint(g2);
ImageIO.write(saveimg,"png",new File("test.png"));
}
catch (Exception e)
{
editorPane.setContentType("text/html");
editorPane.setText("<html>Connection issues!</html>");
}
JFrame frame=new JFrame();
frame.getContentPane().add(editorPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(0,0,(int)screenSize.getWidth(),(int)screenSize.getHeight()-36);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
我添加了 3 秒的延迟,但没有奏效,正确的做法是什么?
【问题讨论】:
-
您需要 1) 在事件线程上加载 Swing 应用程序,以及 2) 摆脱 Thread.sleep,因为它会阻止 Swing GUI 更新和绘图,并且完全没有任何优势。如果您需要延迟,请使用 Swing Timer,或者使用 SwingWorker 加载网页,并在工作人员完成工作后在
done()回调方法中收集图像。 -
您还需要渲染组件才能创建图像。这意味着它应该首先显示,然后绘制图像。
标签: java swing bufferedimage jeditorpane