Auto Complete ComboBox (sem levar em conta acentuação) [RESOLVIDO]

Solucionado… a resposta esta no meu post

solução aqui => http://www.guj.com.br/posts/list/116499.java#630627

exemplo

Eu já vi isso no fórum antes… procure por “remover acentos” (se não me engano, foi postado por thingol.

é mesmo… já vi várias pérolas…

eu até guardei nos meus Utils uma classe dessas… hehehe

public static String removeCaracteresEspeciais(String str) {
		return str.replace('Á', 'A').replace('À', 'A').replace('Â', 'A').replace('Ä', 'A').replace('Ã', 'A').replace('É', 'E')
				.replace('È', 'E').replace('Ê', 'E').replace('Ë', 'A').replace('Í', 'I').replace('Ì', 'I').replace('Î', 'I')
				.replace('Ï', 'I').replace('Ó', 'O').replace('Ò', 'O').replace('Ô', 'O').replace('Ö', 'O').replace('Õ', 'O')
				.replace('Ú', 'U').replace('Ù', 'U').replace('Û', 'U').replace('Ü', 'U').replace('Ç', 'C').replace('á', 'a')
				.replace('à', 'a').replace('â', 'a').replace('ä', 'a').replace('ã', 'a').replace('é', 'e').replace('è', 'e')
				.replace('ê', 'e').replace('ë', 'e').replace('í', 'i').replace('ì', 'i').replace('î', 'i').replace('ï', 'i')
				.replace('ó', 'o').replace('ò', 'o').replace('ô', 'o').replace('ö', 'o').replace('õ', 'o').replace('ú', 'u')
				.replace('ù', 'u').replace('û', 'u').replace('ü', 'u').replace('ç', 'c');
	}

Bom, esta objeto não fui eu que fiz, mas eu modifiquei, foi um moderador aqui do GUJ que fez o objeto, mas não lembro quem…

ele funciona como um AUTO-COMPLETE de ComboBox, porem ele dava um erro quando o index era = a -1 e distinguia caracters acentuados…

Fiz um que não difere caracters acentuados… pra usar é muito simples adcionar a linha de comando AutoComplete.enable(yourComboBox), so colocar o combobox que vc quer autocompletar, que ele já funciona automaticmante

Exemplo de uso:

[code]import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;

import javax.swing.WindowConstants;
import org.jdesktop.layout.GroupLayout;
import org.jdesktop.layout.LayoutStyle;

import com.superlocar.view.util.AutoCompletion;

import javax.swing.SwingUtilities;

public class Teste extends javax.swing.JFrame {
private JComboBox cbxUf;
private JLabel lblUf;

/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
	SwingUtilities.invokeLater(new Runnable() {
		public void run() {
			Teste inst = new Teste();
			inst.setLocationRelativeTo(null);
			inst.setVisible(true);
		}
	});
}

public Teste() {
	super();
	initGUI();
	AutoCompletion.enable(cbxUf); //<== esta linha ativa o autoComplete
	//Ps.: ela podia estar logo apos a definição do cbx
}

private void initGUI() {
	try {
		GroupLayout thisLayout = new GroupLayout((JComponent)getContentPane());
		getContentPane().setLayout(thisLayout);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		{
			ComboBoxModel cbxUfModel = 
				new DefaultComboBoxModel(
						new String[] { "Acre","Alagoas","Amazonas","Amapá","Bahia","Ceará","Distrito Federal","Espírito Santo","Goiás","Maranhão","Minas Gerais","Mato Grosso do Sul","Mato Grosso","Pará","Paraíba","Pernambuco","Piauí","Paraná","Rio de Janeiro","Rio Grande do Norte","Rondônia","Roraima","Rio Grande do Sul","Santa Catarina","Sergipe","São Paulo","Tocantins" });
			cbxUf = new JComboBox();
			cbxUf.setModel(cbxUfModel);
			cbxUf.setSelectedIndex(-1);
		}
		{
			lblUf = new JLabel();
			lblUf.setName("lblUf");
			lblUf.setText("UF: ");
		}
			thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
				.add(7)
				.add(thisLayout.createParallelGroup(GroupLayout.BASELINE)
				    .add(GroupLayout.BASELINE, cbxUf, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
				    .add(GroupLayout.BASELINE, lblUf, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
				.addContainerGap());
			thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup()
				.addContainerGap()
				.add(lblUf, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(LayoutStyle.RELATED)
				.add(cbxUf, GroupLayout.PREFERRED_SIZE, 99, GroupLayout.PREFERRED_SIZE)
				.addContainerGap());
		pack();
		this.setTitle("Auto Complete UF");
		this.setSize(250, 78);
		//Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(getContentPane());
	} catch (Exception e) {
		e.printStackTrace();
	}
}

}[/code]

Objeto AutoComplete

[code]import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.Collator;
import java.util.Locale;

import javax.swing.;
import javax.swing.text.
;

/* This work is hereby released into the Public Domain.

  • To view a copy of the public domain dedication, visit

  • http://creativecommons.org/licenses/publicdomain/
    */
    public class AutoCompletion extends PlainDocument {
    private static final long serialVersionUID = 5157735565710292356L;
    JComboBox comboBox;
    ComboBoxModel model;
    JTextComponent editor;
    // flag to indicate if setSelectedItem has been called
    // subsequent calls to remove/insertString should be ignored
    boolean selecting=false;
    boolean hidePopupOnFocusLoss;
    boolean hitBackspace=false;
    boolean hitBackspaceOnSelection;

    KeyListener editorKeyListener;
    FocusListener editorFocusListener;

    public AutoCompletion(final JComboBox comboBox) {
    this.comboBox = comboBox;
    model = comboBox.getModel();
    comboBox.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    if (!selecting) highlightCompletedText(0);
    }
    });
    comboBox.addPropertyChangeListener(new PropertyChangeListener() {
    @Override
    public void propertyChange(PropertyChangeEvent e) {
    if (e.getPropertyName().equals(“editor”)) configureEditor((ComboBoxEditor) e.getNewValue());
    if (e.getPropertyName().equals(“model”)) model = (ComboBoxModel) e.getNewValue();
    }
    });
    editorKeyListener = new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
    if (comboBox.isDisplayable()) comboBox.setPopupVisible(true);
    hitBackspace=false;
    switch (e.getKeyCode()) {
    // determine if the pressed key is backspace (needed by the remove method)
    case KeyEvent.VK_BACK_SPACE : hitBackspace=true;
    hitBackspaceOnSelection=editor.getSelectionStart()!=editor.getSelectionEnd();
    break;
    // ignore delete key
    case KeyEvent.VK_DELETE : e.consume();
    comboBox.getToolkit().beep();
    break;
    }
    }
    };
    // Bug 5100422 on Java 1.5: Editable JComboBox won’t hide popup when tabbing out
    hidePopupOnFocusLoss=System.getProperty(“java.version”).startsWith(“1.5”);
    // Highlight whole text when gaining focus
    editorFocusListener = new FocusAdapter() {
    @Override
    public void focusGained(FocusEvent e) {
    highlightCompletedText(0);
    }
    @Override
    public void focusLost(FocusEvent e) {
    // Workaround for Bug 5100422 - Hide Popup on focus loss
    if (hidePopupOnFocusLoss) comboBox.setPopupVisible(false);
    }
    };
    configureEditor(comboBox.getEditor());
    // Handle initially selected object
    Object selected = comboBox.getSelectedItem();
    if (selected!=null) setText(selected.toString());
    highlightCompletedText(0);
    }

    public static void enable(JComboBox comboBox) {
    // has to be editable
    comboBox.setEditable(true);
    // change the editor’s document
    new AutoCompletion(comboBox);
    }

    void configureEditor(ComboBoxEditor newEditor) {
    if (editor != null) {
    editor.removeKeyListener(editorKeyListener);
    editor.removeFocusListener(editorFocusListener);
    }

      if (newEditor != null) {
          editor = (JTextComponent) newEditor.getEditorComponent();
          editor.addKeyListener(editorKeyListener);
          editor.addFocusListener(editorFocusListener);
          editor.setDocument(this);
      }
    

    }

    @Override
    public void remove(int offs, int len) throws BadLocationException {
    // return immediately when selecting an item
    if (selecting) return;
    if (hitBackspace) {
    // user hit backspace => move the selection backwards
    // old item keeps being selected
    if (offs>0) {
    if (hitBackspaceOnSelection) offs–;
    } else {
    // User hit backspace with the cursor positioned on the start => beep
    comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
    }
    highlightCompletedText(offs);
    } else {
    super.remove(offs, len);
    }
    }

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
    // return immediately when selecting an item
    if (selecting) return;
    // insert the string into the document
    super.insertString(offs, str, a);
    // lookup and select a matching item
    Object item = lookupItem(getText(0, getLength()));
    if (item != null) {
    setSelectedItem(item);
    } else {
    // keep old item selected if there is no match
    item = comboBox.getSelectedItem();
    // imitate no insert (later on offs will be incremented by str.length(): selection won’t move forward)
    offs = offs-str.length();
    // provide feedback to the user that his input has been received but can not be accepted
    comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
    }
    if(item != null)
    setText(item.toString());
    else
    setText("");
    // select the completed part
    highlightCompletedText(offs+str.length());

    }

    private void setText(String text) {
    try {
    // remove all text and insert the completed string
    super.remove(0, getLength());
    super.insertString(0, text, null);
    } catch (BadLocationException e) {
    throw new RuntimeException(e.toString());
    }
    }

    private void highlightCompletedText(int start) {
    editor.setCaretPosition(getLength());
    editor.moveCaretPosition(start);
    }

    private void setSelectedItem(Object item) {
    selecting = true;
    model.setSelectedItem(item);
    selecting = false;
    }

    private Object lookupItem(String pattern) {
    Object selectedItem = model.getSelectedItem();
    // only search for a different item if the currently selected does not match
    if (selectedItem != null && startsWithIgnoreAccentsAndCase(selectedItem.toString(), pattern)) {
    return selectedItem;
    } else {
    // iterate over all items
    for (int i=0, n=model.getSize(); i < n; i++) {
    Object currentItem = model.getElementAt(i);
    // current item starts with the pattern?
    if (currentItem != null && startsWithIgnoreAccentsAndCase(currentItem.toString(), pattern)) {
    return currentItem;
    }
    }
    }
    // no item starts with the pattern => return null
    return null;
    }
    private static Collator collator = null;
    private static Collator getCollator() {
    if (collator == null) {
    collator = Collator.getInstance (new Locale (“pt”, “BR”));
    collator.setStrength(Collator.PRIMARY);
    }
    return collator;
    }
    public static boolean startsWithIgnoreAccentsAndCase(String source,String target) {
    if (target.length() > source.length())
    return false;
    return getCollator().compare(source.substring(0, target.length()),target) == 0;
    }
    }[/code]

Alguem sabe me dizer como eu add diretorios em um comboBox? :?:

adcionar diretorios em que sentido ?? se vc fizer

[code]File[] arrayContendoOsDiretorios = getDiretorios();//onde getDiretorios é um metodo seu para listar os diretorios

combobox.setModel(new DefaultComboBoxModel(arrayContendoOsDiretorios));[/code]

Sabe o que eu quero fazer eu quero colocar em um comboBox os diretorios para o usuario escolher onde ele quer salvar o arquivo eu tentei fileChooser mas ele abri uma javela e eu so quero a parte dos diretorio por que eu quero que fique assim:

por que esse NSA vai ser o nome do arquivo que o usuario vai digitar!
Vc entedeu o que eu quero fazer?

Lembrando que o método listFiles() da classe File já retorna um array com todos os arquivos e diretórios de determinada pasta. Por exemplo:

		File[] todosOsArquivos = new File(System.getProperty("user.home"))
				.listFiles();
// agora todosOsArquivos contém um array com os arquivos do diretório do usuários
// para criar um combo box bastaria usar: JComboBox combo = new JComboBox(todosOsArquivos);
		for (File f : todosOsArquivos) {
			System.out.println(f.getPath());
		}

aconselho a vc colocar no ComboBox os proprios objetos files, e não os path, ate pq o combo ja exebira os path, visto que toString() chama getPath()

conforme esta ali no comentario do marco use a propria array de files

Olá pessoal!

Estou com o seguinte problema:
Quando eu implemento a jcombobox e habilito ela

AutoCompletion.enable(jcombobox)

jtable.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(jcombobox));

, em uma jtable não funciona(não autocompleta na jtable).
Alguem já passou por este problema?
Tem a solução?
Mto obrigado

Já ia me esquecendo estou usando o NetBeans 6.5, e criei a jtable atráves da paleta

Olá gostaria de saber se da pra fazer o mesmo com um jTextfield, qual o codigo a ser usado, o tipo digitar um digito que seria o codigo e preencher o jtextfield com o “nome” ou "descrição.