package autotextcomplete;
import java.awt.BorderLayout;
import java.io.File;
import java.io.IOException;
import java.util.EventListener;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
class Test {
final static String WORD_FILENAME = "words.txt";
interface AutoComplete {
String getCandidate(String prefix);
}
interface AutoCompleteListener extends EventListener {
void autoCompleted(int offset);
}
@SuppressWarnings("serial")
static class AutoCompleteDocument extends PlainDocument {
private final AutoComplete autoComplete;
public AutoCompleteDocument(final AutoComplete autoComplete) {
this.autoComplete = autoComplete;
}
public void addAutoCompleteListener(AutoCompleteListener listener) {
listenerList.add(AutoCompleteListener.class, listener);
}
public void removeAutoCompleteListener(AutoCompleteListener listener) {
listenerList.remove(AutoCompleteListener.class, listener);
}
public void fireAutoCompleted(int offset) {
for (AutoCompleteListener listener : listenerList.getListeners(AutoCompleteListener.class)) {
listener.autoCompleted(offset);
}
}
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
String toInsert = str;
boolean autoCompleted = false;
if (offs == getLength()) {
String prefix = getText(0, offs) + str;
String candidate = autoComplete.getCandidate(prefix);
if (candidate.length() > prefix.length()) {
toInsert = candidate.substring(offs);
autoCompleted = true;
}
}
super.insertString(offs, toInsert, a);
if (autoCompleted) {
fireAutoCompleted(offs + 1);
}
}
}
public void createAndShowGUI() {
JTextField textField = new JTextField();
AutoCompleteDocument doc = new AutoCompleteDocument(prefix -> {
WordServer words = new WordServer();
try {
words.loadWordsFromFile(WORD_FILENAME);
} catch (IOException e) {
e.printStackTrace();
}
for (String w : words) {
if (w.startsWith(prefix))
return w;
}
return prefix;
});
doc.addAutoCompleteListener(offs -> textField.select(offs, doc.getLength()));
textField.setDocument(doc);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Box box = Box.createVerticalBox();
box.add(textField);
frame.add(box, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
private static void initWordFile() {
String[] words = { "Hans", "Hans Wurst", "Peter", "Paul", "Kirche" };
File file = new File(WORD_FILENAME);
if (!file.exists()) {
WordServer wordServer = new WordServer();
for (String w : words)
wordServer.add(w);
try {
wordServer.saveWordsToFile(WORD_FILENAME);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
initWordFile();
SwingUtilities.invokeLater(() -> new Test().createAndShowGUI());
}
}