IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Composants Java Discussion :

JTextField + autocompletion


Sujet :

Composants Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Inscrit en
    Juin 2008
    Messages
    36
    Détails du profil
    Informations forums :
    Inscription : Juin 2008
    Messages : 36
    Par défaut JTextField + autocompletion
    Bonsoir,
    je voudrais creer un champs texte avec autocompletion
    exemple :
    jai une liste de mots {a, ab, abc, b, c}
    lorsque je clique dans le jtextfield une liste apparait avec a, ab, abc, b, c
    et lorsque je tappe la lettre 'a' la liste des mots présentés devient : a, ab, abc

    enfin ... l'autocompletion bateau....

    mais comment faire ? j'ai une idée pour le faire à la mano avec un jcombobox...
    mais n'y aurait il pas un autre moyen plus simple ? une API peut etre ??

    merci d'avance !

  2. #2
    Membre à l'essai
    Inscrit en
    Septembre 2007
    Messages
    6
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations forums :
    Inscription : Septembre 2007
    Messages : 6
    Par défaut Reponse
    solution 1 :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    package com.myjmailbox.frames;
     
    import java.awt.event.ItemEvent;
    import java.util.ArrayList;
    import java.util.List;
     
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.plaf.basic.BasicComboBoxEditor;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.PlainDocument;
     
    public class Java2sAutoTextField extends JTextField {
    	class AutoDocument extends PlainDocument {
     
    		public void replace(int i, int j, String s, AttributeSet attributeset)
    				throws BadLocationException {
    			super.remove(i, j);
    			insertString(i, s, attributeset);
    		}
     
    		public void insertString(int i, String s, AttributeSet attributeset)
    				throws BadLocationException {
    			if (s == null || "".equals(s))
    				return;
    			String s1 = getText(0, i);
    			String s2 = getMatch(s1 + s);
    			int j = (i + s.length()) - 1;
    			if (isStrict && s2 == null) {
    				s2 = getMatch(s1);
    				j--;
    			} else if (!isStrict && s2 == null) {
    				super.insertString(i, s, attributeset);
    				return;
    			}
    			if (autoComboBox != null && s2 != null)
    				autoComboBox.setSelectedValue(s2);
    			super.remove(0, getLength());
    			super.insertString(0, s2, attributeset);
    			setSelectionStart(j + 1);
    			setSelectionEnd(getLength());
    		}
     
    		public void remove(int i, int j) throws BadLocationException {
    			int k = getSelectionStart();
    			if (k > 0)
    				k--;
    			String s = getMatch(getText(0, k));
    			if (!isStrict && s == null) {
    				super.remove(i, j);
    			} else {
    				super.remove(0, getLength());
    				super.insertString(0, s, null);
    			}
    			if (autoComboBox != null && s != null)
    				autoComboBox.setSelectedValue(s);
    			try {
    				setSelectionStart(k);
    				setSelectionEnd(getLength());
    			} catch (Exception exception) {
    			}
    		}
     
    	}
     
    	public Java2sAutoTextField(List list) {
    		isCaseSensitive = false;
    		isStrict = true;
    		autoComboBox = null;
    		if (list == null) {
    			throw new IllegalArgumentException("values can not be null");
    		} else {
    			dataList = list;
    			init();
    			return;
    		}
    	}
     
    	Java2sAutoTextField(List list, Java2sAutoComboBox b) {
    		isCaseSensitive = false;
    		isStrict = true;
    		autoComboBox = null;
    		if (list == null) {
    			throw new IllegalArgumentException("values can not be null");
    		} else {
    			dataList = list;
    			autoComboBox = b;
    			init();
    			return;
    		}
    	}
     
    	private void init() {
    		setDocument(new AutoDocument());
    		if (isStrict && dataList.size() > 0)
    			setText(dataList.get(0).toString());
    	}
     
    	private String getMatch(String s) {
    		for (int i = 0; i < dataList.size(); i++) {
    			String s1 = dataList.get(i).toString();
    			if (s1 != null) {
    				if (!isCaseSensitive
    						&& s1.toLowerCase().startsWith(s.toLowerCase()))
    					return s1;
    				if (isCaseSensitive && s1.startsWith(s))
    					return s1;
    			}
    		}
     
    		return null;
    	}
     
    	public void replaceSelection(String s) {
    		AutoDocument _lb = (AutoDocument) getDocument();
    		if (_lb != null)
    			try {
    				int i = Math.min(getCaret().getDot(), getCaret().getMark());
    				int j = Math.max(getCaret().getDot(), getCaret().getMark());
    				_lb.replace(i, j - i, s, null);
    			} catch (Exception exception) {
    			}
    	}
     
    	public boolean isCaseSensitive() {
    		return isCaseSensitive;
    	}
     
    	public void setCaseSensitive(boolean flag) {
    		isCaseSensitive = flag;
    	}
     
    	public boolean isStrict() {
    		return isStrict;
    	}
     
    	public void setStrict(boolean flag) {
    		isStrict = flag;
    	}
     
    	public List getDataList() {
    		return dataList;
    	}
     
    	public void setDataList(List list) {
    		if (list == null) {
    			throw new IllegalArgumentException("values can not be null");
    		} else {
    			dataList = list;
    			return;
    		}
    	}
     
    	private List dataList;
     
    	private boolean isCaseSensitive;
     
    	private boolean isStrict;
     
    	private Java2sAutoComboBox autoComboBox;
     
    	public static void main(String[] args) {
    		JFrame frame = new JFrame();
    		List<String> list = new ArrayList<String>();
    		list.add("JAVA");list.add("JAVA SE");list.add("JAVA EE");list.add("JAVA ME");
    		list.add("WELCOME TO");list.add("ALEF++");list.add("NEW LANGUAGE");list.add("PROGRAMMING");
    		Java2sAutoComboBox autoComboBox = new Java2sAutoComboBox(list);
    		Java2sAutoTextField autoTextField = new Java2sAutoTextField(list,autoComboBox);
    		frame.add(autoTextField);
    		frame.pack();
    		frame.setVisible(true);
    	}
    }
     
    class Java2sAutoComboBox extends JComboBox {
    	private class AutoTextFieldEditor extends BasicComboBoxEditor {
     
    		private Java2sAutoTextField getAutoTextFieldEditor() {
    			return (Java2sAutoTextField) editor;
    		}
     
    		AutoTextFieldEditor(java.util.List list) {
    			editor = new Java2sAutoTextField(list, Java2sAutoComboBox.this);
    		}
    	}
     
    	public Java2sAutoComboBox(java.util.List list) {
    		isFired = false;
    		autoTextFieldEditor = new AutoTextFieldEditor(list);
    		setEditable(true);
    		setModel(new DefaultComboBoxModel(list.toArray()) {
     
    			protected void fireContentsChanged(Object obj, int i, int j) {
    				if (!isFired)
    					super.fireContentsChanged(obj, i, j);
    			}
     
    		});
    		setEditor(autoTextFieldEditor);
    	}
     
    	public boolean isCaseSensitive() {
    		return autoTextFieldEditor.getAutoTextFieldEditor().isCaseSensitive();
    	}
     
    	public void setCaseSensitive(boolean flag) {
    		autoTextFieldEditor.getAutoTextFieldEditor().setCaseSensitive(flag);
    	}
     
    	public boolean isStrict() {
    		return autoTextFieldEditor.getAutoTextFieldEditor().isStrict();
    	}
     
    	public void setStrict(boolean flag) {
    		autoTextFieldEditor.getAutoTextFieldEditor().setStrict(flag);
    	}
     
    	public java.util.List getDataList() {
    		return autoTextFieldEditor.getAutoTextFieldEditor().getDataList();
    	}
     
    	public void setDataList(java.util.List list) {
    		autoTextFieldEditor.getAutoTextFieldEditor().setDataList(list);
    		setModel(new DefaultComboBoxModel(list.toArray()));
    	}
     
    	void setSelectedValue(Object obj) {
    		if (isFired) {
    			return;
    		} else {
    			isFired = true;
    			setSelectedItem(obj);
    			fireItemStateChanged(new ItemEvent(this, 701, selectedItemReminder,
    					1));
    			isFired = false;
    			return;
    		}
    	}
     
    	protected void fireActionEvent() {
    		if (!isFired)
    			super.fireActionEvent();
    	}
     
    	private AutoTextFieldEditor autoTextFieldEditor;
     
    	private boolean isFired;
     
    }

    sinon voici une autre solution plus efficace que la première
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    package com.myjmailbox.frames;
     
    import java.awt.FlowLayout;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Iterator;
    import java.util.List;
     
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.JTextComponent;
    import javax.swing.text.PlainDocument;
     
    public class AutoCompleteDocument extends PlainDocument {
     
    	private final List<String> dictionary = new ArrayList<String>();
     
    	private final JTextComponent _textField;
     
    	public AutoCompleteDocument(JTextComponent field, String[] aDictionary) {
    		_textField = field;
    		dictionary.addAll(Arrays.asList(aDictionary));
    	}
     
    	public void addDictionaryEntry(String item) {
    		dictionary.add(item);
    	}
     
    	@Override
    	public void insertString(int offs, String str, AttributeSet a)
    			throws BadLocationException {
    		super.insertString(offs, str, a);
    		String word = autoComplete(getText(0, getLength()));
    		if (word != null) {
    			super.insertString(offs + str.length(), word, a);
    			_textField.setCaretPosition(offs + str.length());
    			_textField.moveCaretPosition(getLength());
    			// _textField.setCaretPosition(getLength());
    			// _textField.moveCaretPosition(offs + str.length());
    		}
    	}
     
    	public String autoComplete(String text) {
    		for (Iterator<String> i = dictionary.iterator(); i.hasNext();) {
    			String word = i.next();
    			if (word.startsWith(text)) {
    				return word.substring(text.length());
    			}
    		}
    		return null;
    	}
     
    /**
     * 
     * @param dictionary
     * @return
     */
    	public static JTextField createAutoCompleteTextField(String[] dictionary) {
    		JTextField field = new JTextField(20);
     
    		AutoCompleteDocument doc = new AutoCompleteDocument(field, dictionary);
    		field.setDocument(doc);
    		return field;
    	}
     
    	public static void main(String args[]) {
    		String[] dict = { "Alef++", "alef++", "sourceForge", "SourceFORGE", "JAVA",
    				"PROGRAMMATION", "programmation", "Team" };
    		JTextField field = AutoCompleteDocument
    				.createAutoCompleteTextField(dict);
     
    		JFrame frame = new JFrame("Autocomplete");
    		frame.setLayout(new FlowLayout());
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.add(new JLabel("Text Field: "));
    		frame.add(field);
    		frame.pack();
    		frame.setVisible(true);
    	}
    }

  3. #3
    Membre averti
    Inscrit en
    Septembre 2008
    Messages
    14
    Détails du profil
    Informations forums :
    Inscription : Septembre 2008
    Messages : 14
    Par défaut
    Hum UP ....

    Solution 2 est pas mal mais si on met JAVA et JAVA2 il va pas voir le JAVA2

    dommage

    et la solution 1 tourne pas convenablement.

    Ou se situe le problème ?

  4. #4
    Membre très actif
    Inscrit en
    Février 2006
    Messages
    707
    Détails du profil
    Informations forums :
    Inscription : Février 2006
    Messages : 707
    Par défaut
    Bonjour,

    J'ai une jcombobox avec des élément dedant qui provienne d'une base de donnée. je voudrais la rataché à un jTextField. Mon idée est de créer un système d'autocomplete similaire à celui que l'on trouve dans eclipse sans le control barre d'espace. Quand l'utilisateur tappe une lettre, il y a la liste qui s'ouvre. il peut choisir, presser sur tab ou entrée pour valider ou echape pour sortir. Le seule problème, c'est que je ne connais pas ce genre de chose du point de vue programmation et je ne sais pas comment m'y prendre pour que ça marche.

    Les algorithme du ce sujet (que je n'ai pas testé) vont-il dans ce sens et si oui, lequel répond exactement à mon problème ?

    Merci pour votre aide.

    Salutations

Discussions similaires

  1. Réponses: 5
    Dernier message: 31/03/2014, 16h21
  2. Autocompletion évoluée JTextField ou JCombobox
    Par Tazz54oli dans le forum Général Java
    Réponses: 1
    Dernier message: 24/06/2013, 13h05
  3. Autocompletion JTextField
    Par titou31000 dans le forum Composants
    Réponses: 6
    Dernier message: 15/01/2013, 11h47
  4. JTextField et l'autocomplete
    Par kldamr dans le forum Composants
    Réponses: 2
    Dernier message: 04/07/2010, 12h26
  5. [JtextField]Creer un masque pour Ip
    Par bibx dans le forum Composants
    Réponses: 8
    Dernier message: 11/01/2005, 17h31

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo