我正在编写一个程序,允许用户提供 RSS 提要的 URL,下载并解析信息,然后将其显示到 JTextArea
。
- 用户可以根据需要添加任意数量的 Feed 类别。 (每个类别都在单独的 Pane 中表示)
- 用户可以根据需要在类别中添加任意数量的 Feed。
- 用户可以添加新的 Feed 或新的类别。
我有一个 ArrayList(ArrayList) = CategoryList。它的每个项目都是category = ArrayList。 Feed 对象包含一个返回 ArrayList 的 getContents() 方法。
我想将每个 Feed 与 JTextArea 相关联。然后我想迭代 FeedItems,同时将它们显示在相应的 JTextArea 中。
我真的一直在寻找一种在 Feed <=> JTextArea 之间关联一对一映射的方法。
这是我的尝试:
if (category_list.size() > 0)
{
final java.util.Iterator<ArrayList<Feed>> categoryListIterator = category_list.iterator();
final ArrayList<Feed> currCategory;
final java.util.Iterator<Feed> currFeedIterator;
while (categoryListIterator.hasNext())
{
currCategory = categoryListIterator.next();
while (((java.util.Iterator<ArrayList<Feed>>) currCategory).hasNext())
{
ArrayList<Feed> currFeed = ((java.util.Iterator<ArrayList<Feed>>) currCategory).next();
currFeedIterator = currFeed.iterator();
while (currFeedIterator.hasNext())
{
Feed feed = currFeedIterator.next();
final java.util.Iterator<FeedItem> feedIterator = feed.getContents().iterator();
while (feedIterator.hasNext())
{
// find the appropriate JTextArea
// iterate through the articles.
correspondingJtextArea.setText(feedIterator.next().toString());
}
}
}
}
}
请告诉我,跟踪我应该在哪个 JTextArea
中更改文本的最佳方式是什么。
我是否正确地迭代了这里的所有提要? 一个简短的例子来说明我的情况将会非常有帮助。
更新:
好的,现在我可以遍历所有提要了。我只需要找到一种方法来编写将 Feed 与 JTextArea 关联起来的 HashMap。
最佳答案
是否有与每个 Feed 相关的标识?如果是,您可以拥有一个 HashMap,其中键为 id,值作为 JTextArea 对象。如果不是,那么您可以为每个 feed 创建一个自定义 ID 并使用 HashMap 进行关联。 关于迭代您的 feed,您需要使用循环而不是 if。
public static JTextArea getTextAreaByFeedId(int id)
{
JTextArea correspondingJtextArea = id_txtareaMap.get(id);
if(correspondingJtextArea == null)
{
correspondingJtextArea = new JTextArea();
id_txtareaMap.put(id, new JTextArea());
}
return correspondingJtextArea;
}
// Reads in an array of integers, sorts them,
// then prints them in sorted order.
public static void main (String[] args) {
HashMap<Integer, JTextArea> id_txtareaMap = new HashMap<>();
if (category_list.size() > 0)
{
final java.util.Iterator<ArrayList<Feed>> categoryListIterator = category_list.iterator();
final ArrayList<Feed> currCategory;
final java.util.Iterator<Feed> currFeedIterator;
while (categoryListIterator.hasNext())
{
currCategory = categoryListIterator.next();
while (((java.util.Iterator<ArrayList<Feed>>) currCategory).hasNext())
{
ArrayList<Feed> currFeed = ((java.util.Iterator<ArrayList<Feed>>) currCategory).next();
currFeedIterator = currFeed.iterator();
while (currFeedIterator.hasNext())
{
Feed feed = currFeedIterator.next();
final java.util.Iterator<FeedItem> feedIterator = feed.getContents().iterator();
while (feedIterator.hasNext())
{
// find the appropriate JTextArea
// iterate through the articles.
JTextArea correspondingJtextArea = getTextAreaByFeedId(FeedItem.getId());
correspondingJtextArea.setText(feedIterator.next().toString());
}
}
}
}
}
}
关于java - 如何关联JTextArea和Object?如何知道哪个对象属于哪个jtextArea?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13638971/