| Код | import javax.swing.*; import javax.swing.text.*;
public class Julietta_class extends PlainDocument { JComboBox comboBox; ComboBoxModel model; JTextComponent editor; boolean selecting=false; public Julietta_class(final JComboBox comboBox) { this.comboBox = comboBox; model = comboBox.getModel(); editor = (JTextComponent) comboBox.getEditor().getEditorComponent(); } public void remove(int offs, int len) throws BadLocationException { if (selecting) return; super.remove(offs, len); } public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (selecting) return; super.insertString(offs, str, a); Object item = lookupItem(getText(0, getLength())); if (item != null) { setSelectedItem(item); } else { item = comboBox.getSelectedItem(); offs = offs-str.length(); comboBox.getToolkit().beep(); } setText(item.toString()); highlightCompletedText(offs+str.length()); } private void setText(String text) throws BadLocationException { super.remove(0, getLength()); super.insertString(0, text, null); } private void highlightCompletedText(int start) { editor.setSelectionStart(start); editor.setSelectionEnd(getLength()); } private void setSelectedItem(Object item) { selecting = true; model.setSelectedItem(item); selecting = false; } private Object lookupItem(String pattern) { Object selectedItem = model.getSelectedItem(); if (selectedItem != null && startsWithIgnoreCase(selectedItem.toString(), pattern)) { return selectedItem; } else { for (int i=0, n=model.getSize(); i < n; i++) { Object currentItem = model.getElementAt(i); if (startsWithIgnoreCase(currentItem.toString(), pattern)) { return currentItem; } } } System.out.println("Исключение '" + pattern + "'"); return null; } private boolean startsWithIgnoreCase(String str1, String str2) { return str1.toUpperCase().startsWith(str2.toUpperCase()); }
private static void startMyGUI() { JComboBox comboBox = new JComboBox(new Object[] {"Julietta", "Juli", "Peter", "Masha", "Sveta"}); comboBox.setEditable(true); JTextComponent editor = (JTextComponent) comboBox.getEditor().getEditorComponent(); editor.setDocument(new Julietta_class(comboBox)); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(3); frame.getContentPane().add(comboBox); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { startMyGUI(); } }); } }
| |