我之前用 DocumentListener 试过这个,但这也给了我在听到一些东西后编辑 Document 的问题。现在我正在尝试对 DocumentFilter 做同样的事情,它似乎正在工作。
public class InputField extends JComboBox<String>{
//for finding suggestions
private SuggestionFinder _finder;
//the model to use for adding items
private DefaultComboBoxModel<String> _model;
public InputField(SuggestionFinder finder){
super();
_model = new DefaultComboBoxModel();
this.setModel(_model);
maximumRowCount = 5;
this.setEditable(true);
Dimension d = new Dimension(300, 75);
this.setMinimumSize(d);
this.setMaximumSize(d);
_finder = finder;
Component edComp = editor.getEditorComponent();
Document document = ((JTextComponent)edComp).getDocument();
if (document instanceof PlainDocument) {
((PlainDocument) document).setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset,
String string, AttributeSet attr) throws BadLocationException {
System.out.println("1");
Document d = fb.getDocument();
giveSuggestions(d.getText(0, d.getLength()));
super.insertString(fb, offset, string, attr);
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
System.out.println("2");
Document d = fb.getDocument();
giveSuggestions(d.getText(0, d.getLength()));
super.remove(fb, offset, length);
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
System.out.println("3");
Document d = fb.getDocument();
giveSuggestions(d.getText(0, d.getLength()));
super.replace(fb, offset, length, text, attrs);
}
});
}
}
private void giveSuggestions(String word){
System.out.println(word);
_model.removeAllElements();
if (word.equals("")){
this.hidePopup();
}
else{
this.showPopup();
/*List<String> suggs = _finder.getSuggestions(word);
for (int i = 1; i <= suggs.size(); i++){
_model.addElement(suggs.get(i-1));
}*/
for (int i = 0; i < 5; i++){
System.out.println("adding");
_model.addElement("" + Math.floor(Math.random()*100));
}
}
System.out.println("done");
}
public static void main(String[] args) throws IOException{
//instantiate a finder, how I do this isn't really relevant to my issue
InputField field = new InputField(finder);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(field);
frame.pack();
frame.setVisible(true);
}