The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
February 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

solution

Posted by jq on October 04, 2001 at 10:55 PM

> Hi,

> I would like to know how to use the KeyListener in the JComboBox.
> You should be able to start typing in an editable JComboBox and everytime a key is typed you should select the entered element or the closest one. (please include example)

> Thanks,


import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class CustomComboEditor extends BasicComboBoxEditor {
int rowCount;
String[] names;
public CustomComboEditor( final String[] names, final int rowCount ) {
super();
this.names = names;
this.rowCount = rowCount;
editor.addKeyListener( new KeyAdapter() {
public void keyReleased( KeyEvent e ) {
processEvent();
}
});

editor.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e) {
processEvent();
}
});

editor.addFocusListener( new FocusAdapter() {
public void focusGained( FocusEvent e) {
((JTextField) e.getComponent()).selectAll();
}
public void focusLost( FocusEvent e) {
processEvent();
}
});
}

void processEvent() {
String wordTyped = editor.getText();
for ( int i = 0; i < rowCount; i++ ) {
if (( (String)names[ i ] ).toUpperCase().startsWith( wordTyped.toUpperCase() ) ) {
editor.selectAll();
editor.setText( (String)names[ i ] );
editor.setSelectionStart( wordTyped.length() );
break;
}
}
}
}

import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.io.File;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TestFrame extends JFrame
{
public TestFrame(){
JComboBox cmb = new JComboBox();
final JLabel label = new JLabel("test");
JTextField textField = new JTextField();

String[] items = new String[10];
for(int i=0; i<10; i++) {
if(i==9) {
items[i]="ttt";
cmb.addItem("ttt");
}
else {
cmb.addItem("Item"+i);
items[i] = "Item"+i;
}
}

cmb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
JComboBox source = (JComboBox)evt.getSource();
int iIdx = source.getSelectedIndex();
label.setText(""+iIdx);
}
});
cmb.setEditor(new CustomComboEditor(items, 10));
cmb.setEditable(true);
this.getContentPane().setLayout(new FlowLayout());
this.getContentPane().add(cmb);
this.getContentPane().add(label);
this.getContentPane().add(textField);

}

public static void main(String argv[]) {
try {
TestFrame tf = new TestFrame();

tf.setSize(new Dimension(200, 200));
tf.setVisible(true);
}
catch (Exception ex) {System.out.println("Exception" + ex);
ex.printStackTrace();}
}
}






Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us