Home arrow static arrow Java Programming [Archive] - Problem matching JTextField input to an item in a JList box
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Problem matching JTextField input to an item in a JList box
This topic has 2 replies on 1 page.

Posts:3
Registered: 6/18/04
Problem matching JTextField input to an item in a JList box  
Aug 1, 2004 10:13 PM



 
Hello,

I am trying to read the user's input in a text field and take the user to a match in a list box located underneath the textfield. To do that I have implemented the following code:

m_pathwayNameTextField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
m_pathwayNameTextField_KeyTyped(e);
}
});

private void m_pathwayNameTextField_KeyTyped(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_TYPED) {
String prefix = m_pathwayNameTextField.getText();
char c = e.getKeyChar();
if (e.getKeyChar() >= KeyEvent.VK_SPACE && e.getKeyCode() < 127) {
prefix = prefix + e.getKeyChar();
}
int position = m_pathwayNamesList.getNextMatch(prefix, 0,
Position.Bias.Forward);
if (position != -1) {
m_pathwayNamesList.ensureIndexIsVisible(position);
}
}

Although the above kind of works, it still has some problems. The first is that if I press a "backspace" character, it won't try to match any results. Also, if I highlight the whole text in the textfield and press a letter, it won't attempt to match either. The reason for the later is that the textfield at that time is not blank and so prefix becomes the textfield plus the newly entered letter, whereas it should be the newly entered letter.

Any help on this is highly appreciated.

Thanks.
 

Posts:24,517
Registered: 98-02-27
Re: Problem matching JTextField input to an item in a JList box  
Aug 1, 2004 10:25 PM (reply 1 of 2)



 
The best way to do this is to use a DocumentListener instead of a KeyListener. When the DocumentEvent is fired the document has already been updated and you can just use getText() to get the contents of the Document. No need to play around with backspace characters.

 

Posts:3
Registered: 6/18/04
Re: Problem matching JTextField input to an item in a JList box  
Aug 2, 2004 7:04 AM (reply 2 of 2)



 
Thanks a lot for your help. It works now :)
 
This topic has 2 replies on 1 page.