我不确定它是否真的是JTextArea问题或ActionListener或其他东西。
我的程序所做的是它从给定的URL获取详细信息,并在按下按钮时在JTextArea中显示它。这是我遇到问题的代码:
public void displayResults(String url, JTextArea area) {
//number of episode
int num = 1;
//Get the URL from JTextField that will be passed as a parameter of this method
webData.setup(url);
String result = "";
for (int i = 0; i < webData.getDates().size(); i++) {
result += "Episode " + num++ + ": " + webData.getEpisodeTitle().get(i) + "\n" + "Air date: "
+ webData.getDates().get(i) + "\n\n";
}
//Set the text of JTextArea with the values produced in loop above
area.setText(result);
}
和ActionListener:
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submitButton && !urlField.getText().equals("")) {
displayResults(urlField.getText(), resultsTextArea);
}
问题是,每次提供新的URL时,它都会显示上一个URL的结果。例如,如果我运行程序并给它URL#1,它将显示20个结果(假设它有20个结果),并且当提供下一个URL时,它仍将显示URL#1的前20个结果和然后显示来自21的URL#2的结果。像这样:
Episode 22: Not aired yet!
Air date: 18 May 2018
Episode 23: The Flash Reborn
Air date: 10 Oct. 2017
^这些是两个不同URL的结果。我希望URL#2结果从num = 1开始,而不是在URL#1停止的地方增加。有没有办法在每次按下按钮时重置JTextArea值?我对此非常陌生,所以任何帮助都将不胜感激!
编辑:这是webData.setup()
的方法public void setup(String url) {
try {
site = Jsoup.connect(url).get();
} catch (IOException e) {
e.printStackTrace();
}
dateData = site.select("div.airdate");
titleData = site.select("a[itemprop='name']");
showTitle = site.select("a.subnav_heading").first();
for(Element results : dateData) {
dates.add(results.text());
}
for(Element results : titleData) {
if(results.text().contains("Episode #")) {
episodeTitles.add("Not aired yet!");
} else {
episodeTitles.add(results.text());
}
}
}
答案 0 :(得分:1)
问题就在这里
for(Element results : dateData) {
dates.add(results.text());
}
您正在向Element
添加新的dates
个实例,但从不删除它们。
只需添加
dates.clear();
之前webData.setup(url);
所以
public void displayResults(String url, JTextArea area) {
//number of episode
int num = 1;
dates.clear();
//Get the URL from JTextField that will be passed as a parameter of this method
webData.setup(url);
String result = "";
for (int i = 0; i < webData.getDates().size(); i++) {
result += "Episode " + num++ + ": " + webData.getEpisodeTitle().get(i) + "\n" + "Air date: "
+ webData.getDates().get(i) + "\n\n";
}
//Set the text of JTextArea with the values produced in loop above
area.setText(result);
}