我已经阅读了 JEditorPane 文档,据我所知,您只需要 editorpane.setText(String value);但是我对 java 很陌生,这个解决方案不适用于我的代码。我认为我错过了一些明显但完全出于想法的东西。
我用这个扩展 JEditorPane 的类创建了一个新选项卡,这个类旨在打开文件的内容,将它们放在一个数组中,反转数组(因此最新条目位于顶部),然后在 JEditorPane 中显示此列表(使用 JeditorPane 因为我需要将保存 URL 制作为超链接),
public class HistoryPane extends JEditorPane{
ArrayList<String> historyToSort = new ArrayList<String>();
public HistoryPane(){
setEditable(false);
historySort();
}
public void historySort() {
try (BufferedReader reader = new BufferedReader(new FileReader("BrowserHistory.txt")))
{
String currentLine;
String newLine = new String("\n");
while ((currentLine = reader.readLine()) != null) {
historyToSort.add(currentLine + newLine);
}
} catch (IOException e) {
e.printStackTrace();
}
Collections.reverse(historyToSort);
System.out.println(historyToSort);
}
{
}
private void displayHistory(){
String sorted = historyToSort.toString();
***** HistoryPane.setText(String sorted); <<<------ PROBLEM SYNTAX.*****
}
}
我在 setText() 括号中尝试了多个不同的条目,但没有成功。我缺少什么?谢谢。
注意:
该类无法编译,因为它依赖于另一个类(我无法粘贴所有类),但此代码位于我的主类创建的选项卡式 Pane 中:
错误消息:
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problems: Syntax error on token "setText", Identifier expected after this token Return type for the method is missing This method requires a body instead of a semicolon
最佳答案
好吧,尽管您还没有阅读错误消息,但看来您确实是新手,所以我会提供帮助。
HistoryPane.setText(String sorted);
以上内容不是有效的 Java。方法调用采用参数列表,没有类型。
HistoryPane.setText(sorted);
现在这是一个有效的方法调用。但它尝试调用 HistoryPane 类的名为 setText()
的静态方法。您想要的是在当前对象上调用实例方法setText()
。所以有效的语法是
this.setText(sorted);
或者简单地
setText(sorted);
这应该可以解决这个特定的编译错误。在修复 Eclipse 的“问题” View 中列出的每个编译错误之前,不要尝试运行您的应用程序。
请注意,上面的行不会执行您想要的操作,但我会让您研究应该做什么。
我的建议:如果您还不知道如何调用方法,请不要尝试使用 Swing,它是一个相当复杂的野兽。从非常简单的 Java 练习开始,不涉及任何 GUI,直到您熟悉 Java 语法,并了解如何阅读、理解和修复基本的编译问题。
关于java - JEditorPane - 从 ArrayList<String> 内容中设置文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15930184/