简体   繁体   English

如何将结果附加到另一个java类的JTextArea中?

[英]How to append result into JTextArea in another java class?

I have 2 separate java files (Main & RSS). 我有2个单独的java文件(Main和RSS)。 I would like to return the result from my RSS class to my Main class. 我想将结果从我的RSS类返回到我的Main类。 Right now the results are displayed in console. 现在结果显示在控制台中。 How can I append the results to my JTextArea instead? 如何将结果附加到我的JTextArea? Thanks! 谢谢!

In my Main class: 在我的主课:

public void news()
{
    news = new JPanel();
    news.setLayout( null );

    JTextArea textArea = new JTextArea();
    textArea.setBackground(SystemColor.window);
    textArea.setBounds(10, 11, 859, 512);       
    textArea.setWrapStyleWord(true);
    news.add(textArea);

    TextSamplerDemo reader = TextSamplerDemo.getInstance();
    reader.writeNews();     
}

In my RSS class: 在我的RSS课程中:

public void writeNews(){
try{                
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    URL u = new URL("http://rss.cnn.com/rss/cnn_world.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);

        System.out.println("Title: " + getElementValue(element,"title"));
        System.out.println("Link: " + getElementValue(element,"link"));             
    }
}

catch(Exception ex){
    ex.printStackTrace();
}

} }

If you modify your RSS.writeNews method to return the parsed RSS feed, the Main class can easily insert the data into the text area. 如果修改RSS.writeNews方法以返回已解析的RSS提要,则Main类可以轻松地将数据插入文本区域。

// In the RSS class
public String writeNews() 
{
  String result = "";
  ...
  // Instead of printing to console, store text in a String variable
  result += "Title: " + getElementValue(element,"title");
  result += "Link: " + getElementValue(element,"link");
  ...
  // Return result
  return result
}

// In the Main.news method
String rssNews = reader.writeNews();
textArea.append(rssNews);

不是在方法中初始化文本区域,而是全局初始化它(如新闻var),然后使用

Main.textArea.setText(String text);

You could consider the Observer Design Pattern . 您可以考虑观察者设计模式 This way, you don't have to share the JTextArea object between classes. 这样,您就不必在类之间共享JTextArea对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM