Lily S
Lily S

Reputation: 245

How to append result into JTextArea in another java class?

I have 2 separate java files (Main & RSS). I would like to return the result from my RSS class to my Main class. Right now the results are displayed in console. How can I append the results to my JTextArea instead? 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:

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();
}

}

Upvotes: 1

Views: 2745

Answers (3)

Radu Murzea
Radu Murzea

Reputation: 10900

You could consider the Observer Design Pattern. This way, you don't have to share the JTextArea object between classes.

Upvotes: 0

erikxiv
erikxiv

Reputation: 4075

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.

// 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);

Upvotes: 2

Kaikz
Kaikz

Reputation: 171

Instead of initializing the text area in your method, initialize it globally (like your news var), then use

Main.textArea.setText(String text);

Upvotes: 1

Related Questions