可能重复:
How to list suggestions to when typing inside the text field
有没有办法在java swing中的JTextField中获取预测文本?就像我想从用户那里得到城市名称一样,它应该预测这个城市。
答案 0 :(得分:1)
SwingX提供自动完成功能:http://swingx.java.net/
答案 1 :(得分:0)
我的某些程序中有自动完成功能。不幸的是我找不到我在互联网上获取信息的地方。我发布了我的代码,但我不是这个AutoCompleteDocument类的“原始”作者。如果你在互联网上找到它给我链接,那么可以给予原作者信用。
public class AutoCompleteDocument extends PlainDocument {
private final List<String> dictionary = new ArrayList<String>();
private final JTextComponent jTextField;
public AutoCompleteDocument(JTextComponent field, String[] aDictionary) {
jTextField = 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);
jTextField.setCaretPosition(offs + str.length());
jTextField.moveCaretPosition(getLength());
}
}
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;
}
}
然后使用它只需用类似的东西初始化它
AutoCompleteDocument autoCompleteDoc;
autoCompleteDoc = new AutoCompleteDocument(aJTextField, anArray);
aJTextField.setDocument(autoCompleteDoc);
希望它会有所帮助
答案 2 :(得分:0)
以下是一种可能的实施方式:
public class Predict
{
private final static String [] COLORS = new String [] {"red", "orange", "yellow", "green", "cyan", "blue", "violet"};
public static void main (String [] args)
{
final JTextField field = new JTextField ();
field.getDocument ().addDocumentListener (new DocumentListener()
{
@Override
public void removeUpdate (DocumentEvent e)
{
// Do nothing
}
@Override
public void insertUpdate (DocumentEvent e)
{
if (e.getOffset () + e.getLength () == e.getDocument ().getLength ())
SwingUtilities.invokeLater (new Runnable()
{
@Override
public void run ()
{
predict (field);
}
});
}
@Override
public void changedUpdate (DocumentEvent e)
{
// Do nothing
}
});
JFrame frame = new JFrame ("Auto complete");
Container contentPane = frame.getContentPane ();
contentPane.setLayout (new BorderLayout ());
contentPane.add (field, BorderLayout.CENTER);
frame.pack ();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setVisible (true);
}
private static void predict (JTextField field)
{
String text = field.getText ();
String prediction = null;
for (String color: COLORS)
{
if (color.startsWith (text) && !color.equals (text))
{
if (prediction != null) return;
prediction = color;
}
}
if (prediction != null)
{
field.setText (prediction);
field.setCaretPosition (text.length ());
field.select (text.length (), prediction.length ());
}
}
}