/** * Copyright 1999-2009 The Pegadi Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pegadi.swing; import org.pegadi.util.AutoCompleteCatalog; import javax.swing.*; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; /** * Use this document with a JTextField to add the autocomplete feature to it. * @author Ingar Saltvik */ public class AutoCompleteDocument extends PlainDocument { private JTextField tf; //I don't see an easy way to avoid this //model-view coupling. private AutoCompleteCatalog cat; /** * Default constructor. * @param tf The JTextField to which this document belongs. Yes, it is an ugly model-view hack. * @param filename The file which the autocompletionstexts will be read from. */ public AutoCompleteDocument(JTextField tf, String filename) { super(); this.tf = tf; cat = new AutoCompleteCatalog(filename); } /** * @see javax.swing.text.Document#insertString(int, String, AttributeSet) */ public void insertString(int offset, String str, AttributeSet a) throws BadLocationException { String precedingText = getText(0,getLength()); String completionText = cat.getCompletionText(precedingText + str); if(completionText.length()>0 && str.length()==1 && tf.getCaret().getMark()==getLength()) { super.insertString(offset,completionText,a); tf.moveCaretPosition(Math.min(getLength(),offset + str.length())); tf.getCaret().moveDot(offset+str.length()); } else { super.insertString(offset,str,a); } //I'm not sure how to pass the selection info to the //JTextField without doing it in the Document } /** * @see org.pegadi.util.AutoCompleteCatalog */ public void save(String newEntry) { cat.save(newEntry); } public static void main(String[] args) { JFrame f = new JFrame(); final JTextField t = new JTextField(15); final AutoCompleteDocument doc = new AutoCompleteDocument(t, args[0]); t.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent e) { if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) doc.save(t.getText()); } }); t.setDocument(doc); f.getContentPane().add(t); f.pack(); f.setVisible(true); } }