我在JTextPanel中显示RSS提要。显示的结果不会转到新行。如何在JTextPane中插入\ n?谢谢!
writeNews类:
public String writeNews()
{
String result = "";
try
{
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL u = new URL("http://thestar.com.my.feedsportal.com/c/33048/f/534600/index.rss");
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 += "\nTitle: " + getElementValue(element,"title");
result += "\nLink: " + getElementValue(element,"link");
result += "\nPublish Date: " + getElementValue(element,"pubDate");
result += "\nDescription: " + getElementValue(element,"description");
System.out.println("Title: " + getElementValue(element,"title"));
System.out.println("Link: " + getElementValue(element,"link"));
System.out.println("Publish Date: " + getElementValue(element,"pubDate"));
System.out.println("Description: " + getElementValue(element,"description"));
System.out.println();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return result;
}
结果显示在一个简单的JTextPane上:
public void news()
{
news = new JPanel(new GridLayout());
news.setBackground(SystemColor.inactiveCaptionBorder);
JTextPane newsTextPane = new JTextPane();
newsTextPane.setContentType("text/html");
newsTextPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(newsTextPane);
news.add(scrollPane);
TextSamplerDemo reader = TextSamplerDemo.getInstance();
reader.writeNews();
String rssNews = reader.writeNews();
newsTextPane.setText(rssNews);
}
JTextPane查看:
控制台视图:
答案 0 :(得分:3)
这是一种可行的解决方法,
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
public class TestLineBreak {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append("Text goes here <br>"); //<br> tag to insert line breaks
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextPane newsTextPane = new JTextPane();
newsTextPane.setContentType("text/html");
newsTextPane.setEditable(false);
newsTextPane.setText(sb.toString());
JScrollPane scrollPane = new JScrollPane(newsTextPane);
frame.add(scrollPane);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
答案 1 :(得分:2)
result += "Title: " + getElementValue(element,"title");
result += "Link: " + getElementValue(element,"link");
result += "Publish Date: " + getElementValue(element,"pubDate");
result += "Description: " + getElementValue(element,"description");
创建String
时,永远不会使用新行。将换行符添加到每行的开头(第一行除外)或将换行符附加到每行的末尾(除最后一行之外)。
答案 2 :(得分:-1)
箱.. 以上2个答案的工作方式在逻辑上是正确的,但我们应该从java提供的内置类和功能中获得帮助。
如果您要添加与
上的问题类似的其他功能,您也可以采用以下方式请参阅http://docs.oracle.com/javase/7/docs/api/javax/swing/text/DefaultEditorKit.html