此处讨论的完整示例将RSS 提要中的条目添加到. 我在下面说明了一个变化。JTextPane
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @see https://stackoverflow.com/a/19164649/230513
* @see https://stackoverflow.com/q/10461087/230513
*/
public class NewsFeed extends JPanel {
public NewsFeed() {
this.setLayout(new GridLayout());
JTextPane newsPane = new JTextPane();
newsPane.setContentType("text/html");
newsPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(newsPane);
scrollPane.setVerticalScrollBarPolicy(
javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
RSS reader = RSS.getInstance();
String rssNews = reader.writeNews();
newsPane.setText(rssNews);
this.add(scrollPane);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame("News");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new NewsFeed());
f.pack();
f.setSize(640, 480);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
private static class RSS {
private static final String NAME =
"http://thestar.com.my.feedsportal.com/c/33048/f/534600/index.rss";
private static RSS instance = null;
public static RSS getInstance() {
if (instance == null) {
instance = new RSS();
}
return instance;
}
public String writeNews() {
String result = "";
try {
DocumentBuilder builder = DocumentBuilderFactory
.newInstance().newDocumentBuilder();
URL u = new URL(NAME);
Document doc = builder.parse(u.openStream());
NodeList nodes = doc.getElementsByTagName("item");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
result += "Title: " + getElementValue(element, "title") + "<br>";
result += "Link: " + getElementValue(element, "link") + "<br>";
result += "Publish Date: " + getElementValue(element, "pubDate") + "<br>";
result += "Description: " + getElementValue(element, "description") + "<br>";
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
return result;
}
private String getCharacterDataFromElement(Element e) {
try {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
return "";
}
protected float getFloat(String value) {
if (value != null && !value.equals("")) {
return Float.parseFloat(value);
}
return 0;
}
protected String getElementValue(Element parent, String label) {
return getCharacterDataFromElement(
(Element) parent.getElementsByTagName(label).item(0));
}
}
}