我一直试图在这里花几个小时,也在网上搜索,但根本找不到解决方案。
我需要构建一个文本区域(无论是JTextArea,JTextPane还是JEditorPane无关紧要),它可以读取和格式化HTML。
我知道JEditorPane可以通过给它一个超级链接来显示HTML,但是如果我已经获得了HTML文本,并且想要显示它怎么办?如果我使用setText()它只显示一个白色字段。什么都没有。
我得到的HTML文本来自电子邮件。我得到它,使用以下代码(只是它的片段)
String subject = message[row].getSubject();
String from = InternetAddress.toString(message[row].getFrom());
StringBuilder body = new StringBuilder();
Multipart mp = (Multipart) message[row].getContent();
for(int i = 0; i < mp.getCount(); i++) {
BodyPart bp = mp.getBodyPart(i);
String disp = bp.getDisposition();
if(disp != null && (disp.equals(BodyPart.ATTACHMENT))) {
// Do something
} else {
body.append(bp.getContent());
}
}
EmailContent ec = new EmailContent(new JFrame(),true,from,subject,body.toString());
} catch (IOException ex) {
Logger.getLogger(MailPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (MessagingException ex) {
Logger.getLogger(MailPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
帮助?
答案 0 :(得分:0)
import javax.swing.*;
public class HTMLFromString {
HTMLFromString() {
JEditorPane jep = new JEditorPane();
String html = "<html><body><h1>Title</h1><p>Paragraph..";
// Important!
jep.setContentType("text/html");
jep.setText(html);
JOptionPane.showMessageDialog(null, jep);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
new HTMLFromString();
}
});
}
}
此版本使用(主要)您的代码段(带有一些实际内容)创建一些HTML,前缀为<html>
以生成结果。
import javax.swing.*;
public class HTMLFromString {
static String SNIPPET =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional" +
"//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>" +
"<meta http-equiv=\"Content-Type\" content=\"text/html; " +
"charset=Windows-1252\" /><title></title>" +
"<style type=\"text/css\">" +
"a, a:visited" +
"{" +
" color: #406377;" +
"}" +
"</style>" +
"</head>" +
"<body bgcolor=\"#ffffff\" style=\"background-color: #ffffff; " +
"width: 600px; font-family: Arial, Verdana, Sans-serif; color: " +
"#000; font-size: 14px; margin: 0px;\"><h1>Hi!</h1>";
HTMLFromString() {
JEditorPane jep = new JEditorPane();
String html = "<html>" + SNIPPET;
// Important!
jep.setContentType("text/html");
jep.setText(html);
JOptionPane.showMessageDialog(null, jep);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
new HTMLFromString();
}
});
}
}