import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.text.Document;
/*
* Erstellt am 08.09.2005 15:30:53
*/
/**
* @author oxis
*
*/
public class AutoComboBox2 extends JTextField implements KeyListener, ActionListener
{
private String[] ItemList;
private JPopupMenu pum = new JPopupMenu();
private String aktInhalt;
private boolean popupIsShowing = false;
public AutoComboBox2()
{
super();
initiate();
}
public AutoComboBox2(String arg0)
{
super(arg0);
initiate();
}
public AutoComboBox2(int arg0)
{
super(arg0);
initiate();
}
public AutoComboBox2(String arg0, int arg1)
{
super(arg0, arg1);
initiate();
}
public AutoComboBox2(Document arg0, String arg1, int arg2)
{
super(arg0, arg1, arg2);
initiate();
}
private void initiate()
{
this.setComponentPopupMenu(pum);
this.addKeyListener(this);
pum.setBackground(this.getBackground());
}
public static void main(String[] args)
{
JFrame frame = new JFrame("ComboBoxTest");
String [] list = {"hallo", "test", "was", "los", "denis", "berna", "kaan", "cenk", "toll", "he", "ho", "hi"};
AutoComboBox2 acb = new AutoComboBox2();
acb.setItemList(list);
frame.getContentPane().add(acb);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setItemList(String[] list)
{
this.ItemList = list;
}
public void keyTyped(KeyEvent arg0)
{
}
public void keyPressed(KeyEvent arg0)
{
}
public void keyReleased(KeyEvent arg0)
{
System.out.println("key");
fillPopUp();
pum.setVisible(false);
if(pum.getComponentCount() != 0)
{
pum.show(this, 0, this.getHeight());
pum.setVisible(true);
if(arg0.getKeyCode() != KeyEvent.VK_DOWN)
this.requestFocus();
}
if(arg0.getKeyCode() == KeyEvent.VK_ENTER)
pum.setVisible(false);
}
private void fillPopUp()
{
pum.removeAll();
pum.setVisible(false);
aktInhalt = this.getText();
System.out.println(aktInhalt);
for(int i = 0; i < ItemList.length; i++)
{
if(ItemList[i].startsWith(aktInhalt))
{
JMenuItem mi = new JMenuItem(ItemList[i]);
mi.addActionListener(this);
pum.add(mi);
}
}
}
public void actionPerformed(ActionEvent arg0)
{
this.setText(arg0.getActionCommand());
pum.setVisible(false);
}
}