首先,我是一个初学者编程的学生,我不知道很多Java/编程术语,所以如果你能帮助我,请尝试用更简单的语言解释。
我正在尝试在 JScrollPane 中显示单词列表。该列表由类 WordList 表示。JScrollPane 位于另一个名为 WordFinder 的类中。
在 WordFinder 中,代码类似于:
WordList words = new WordList();
// (other GUI code in between)
JScrollPane scrollPane = new JScrollPane(DONT_KNOW);
如果我将“单词”放在 DONT_KNOW 所在的位置,我会收到一条警告说“构造函数 JScrollPane(WordList) 未定义”。我可以理解, JScrollPane 不应该接受这个奇怪的随机类。但是我在那儿放什么呢?我知道您可以将 JList 放在 JScrollPane 中,但是如何将 WordList 类转换为 JList(或 JScrollPane 将接受的东西)?
我不确定这是否有帮助,但这是 WordList 类中的代码(我没有写这个;它是给我的):
import java.io.*;
import java.net.URL;
import java.text.Collator;
import java.util.*;
/**
* A WordList is a set of words loaded from a file and searchable by substring.
* A word is defined as a sequence of letters (upper case or lower case).
* WordSets ignore alphabetic case when comparing, searching, or sorting.
*/
public class WordList {
private List words;
/*
* Rep invariant: words != null
*/
public WordList() {
}
public void load(InputStream in) throws IOException {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
Set s = new TreeSet(c);
StreamTokenizer tok = new StreamTokenizer(new InputStreamReader(in));
tok.resetSyntax();
tok.wordChars('a', 'z');
tok.wordChars('A', 'Z');
while (tok.nextToken() != StreamTokenizer.TT_EOF) {
if (tok.ttype == StreamTokenizer.TT_WORD)
s.add(tok.sval);
}
words = new ArrayList(s);
}
public List find(String s) {
if (s.length() == 0) {
return Collections.unmodifiableList(words);
}
s = s.toLowerCase();
List l = new ArrayList();
for (Iterator i = words.iterator(); i.hasNext();) {
String word = (String) i.next();
if (word.toLowerCase().indexOf(s) != -1)
l.add(word);
}
return l;
}
/**
* Main method. Demonstrates how to use this class.
*
* @param args
* Command-line arguments. Ignored.
*/
public static void main(String[] args) {
WordList words = new WordList();
// Create the word list from a resource.
// The words file must be in the same directory (or jar file directory)
// as this class.
URL url = WordList.class.getResource("words.txt");
if (url == null)
throw new RuntimeException("Missing resource: words");
try {
words.load(url.openStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
// Print all the words containing "ph"
List matches = words.find("holst");
for (Iterator i = matches.iterator(); i.hasNext();) {
System.out.println(i.next());
}
}
}