Popup in JTextField

I am developing an application in which I have to implement a search facility.
In order to implement a sub-string search I want that whenever the user types the first few characters of the name (of the thing to be searched) the list of possible names starting with those characters should popup above the JTextField.
Is this possible?
Thanx in advance
ats

Thanx for the help .. but I want all the possible options displayed in a small box above the TextField ......
Is this possible?
TIA
ats

Similar Messages

  • About popup hide

    Question F
    1.How dose JPopupMenu or JMenuItem hiden ,when click any where .
    2.How dose JComboBox's dropdown hidden ,when click any where.
    3.Question1,2 is one answer?
    I tried to read JComponent ,Popup ,PopupFactory ,JPopupMenu,JCombox and others source code,but in few day I can't find the way .Please help me and give directions B
    JTextField editing ,dropdown a JPopupMenu contain maybe input words,but focus lost,can't still edit JTextField;
    Edited by: tlw_ray on Oct 22, 2008 11:40 PM

    Thans for you camickr .
    My question is I dosen't know the theory , how swing manage popup item hiden;
    I want a JTextField ,when I input word,it can drop down a popup assistant help me auto complete.
    First I use PopupFactory to implement the function,but finally I notice that I can't hide the popup in an evnent.
    Then I think maybe use somethin like menu can implement the function.So I use JPopupMenu ,but when it popup,the JTextField's focuse lose,I can't input still.then when JPopupMenu shown I set jTextField to requestFocuse().That's all .My problem resolved.But I still dose't know how the JPopupMenu hiden ,when click any where but the menu.And I tried use JWindow ,but it dosen't catch the deActive window event.
    I hope can understand how swing manager popup show or hiden,maybe intro some article or indicate some code block can help me .I like java for he tell me what he do when a program running,
    Utility Class:
    import java.awt.Component;
    import javax.swing.JFrame;
    Author:唐力伟
    E-Mail:[email protected]
    Date:2008-10-22
    Description:
    public class Shower {
         public static void show(Component comp,int width,int height){
              JFrame f=new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setSize(width, height);
              f.setLocationRelativeTo(null);
              f.add(comp,"Center");
              f.setVisible(true);
         public static void show(Component comp){
              show(comp,400,300);
    }Here is my exmaple code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Window;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JTextField;
    import javax.swing.JWindow;
    import javax.swing.Popup;
    import javax.swing.PopupFactory;
    import tlw.example.Shower;
    Author:tlw_ray
    E-Mail:[email protected]
    Date:2008-10-23
    Description:input assistant
    public class JTextFieldKindsOfPopup extends JPanel{
         private static final long serialVersionUID = 1L;
         public static void main(String[] args) {
              JTextFieldKindsOfPopup wp=new JTextFieldKindsOfPopup();
              Shower.show(wp);
         JTextField jtfWindowPopuup=new JTextField("Edit for Popup JWindow",20);
         JTextField jtfMenuPopup=new JTextField("Edit for Popup JPopupMenu",20);
         JTextField jtfPopup=new JTextField("Edit for PopupFactory Popup",20);
         Window popupWindow=new JWindow();
         JPopupMenu popupMenu=new JPopupMenu();
         Popup popup;
         JPanel popupPane=new JPanel();
         public JTextFieldKindsOfPopup(){
              add(jtfWindowPopuup,"North");
              add(jtfMenuPopup,"South");
              add(jtfPopup,"Center");
              //popup window
              popupWindow.setPreferredSize(new Dimension(300,300));
              popupWindow.setBackground(Color.red);
              popupWindow.setBounds(20, 20, 100, 100);
              popupWindow.setAlwaysOnTop(true);
              popupWindow.addWindowListener(new WindowListener());
              jtfWindowPopuup.addKeyListener(new KeyAdapter(){
                   public void keyPressed(KeyEvent e){
                        popupWindow.setVisible(true);
                        //JWindow dosen't catch windowDeactivated event;
              //popup menu
              JMenuItem menuItem1=new JMenuItem("Item1");
              JMenuItem menuItem2=new JMenuItem("Item2");
              JMenuItem menuItem3=new JMenuItem("Item3");
              popupMenu.add(menuItem1);
              popupMenu.add(menuItem2);
              popupMenu.add(menuItem3);
              jtfMenuPopup.addKeyListener(new KeyAdapter(){
                   public void keyPressed(KeyEvent e){
                        popupMenu.show(jtfMenuPopup, 0, jtfMenuPopup.getHeight());
                        jtfMenuPopup.requestFocus();
                        //this way can resolve,input assistant
              //popup factory
              popupPane.setBackground(Color.blue);
              popupPane.setPreferredSize(new Dimension(100,100));
              jtfPopup.addKeyListener(new KeyAdapter(){
                   public void keyPressed(KeyEvent e){
                        popup=PopupFactory.getSharedInstance().getPopup(JTextFieldKindsOfPopup.this, popupPane, 100, 100);
                        popup.show();
                        //what event can i set the popup hide()?
                        //maybe popupFactory dosen't use for this ,it just use to Tooltip.
         class WindowListener extends WindowAdapter{
              @Override
              public void windowDeactivated(WindowEvent e) {
                   popupWindow.setVisible(false);
    }Here is my function code
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import java.text.Collator;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Locale;
    import java.util.Vector;
    import javax.swing.JCheckBox;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JSpinner;
    import javax.swing.JTextField;
    import javax.swing.SpinnerNumberModel;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    Author:tlw
    E-Mail:[email protected]
    Date:2008-10-23
    Description:
    public class MSearch1 extends JPanel {
         private static final long serialVersionUID = 1L;
         public static void main(String[] args) {
              final MSearch1 ms=new MSearch1();
              ms.setItems(new String[]{"aaa","aab","aac","W3.UNIT1.E0003","W3.UNIT1.E0004","W3.UNIT1.E0005"});
              final JCheckBox jckDropDownMode=new JCheckBox("isDropDownMode");
              jckDropDownMode.setSelected(ms.getIsDropDown());
              jckDropDownMode.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        ms.setIsDropDownModel(jckDropDownMode.isSelected());
              final JCheckBox jckFilterMode=new JCheckBox("isFilterMode");
              jckFilterMode.setSelected(ms.getIsFilterMode());
              jckFilterMode.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        ms.setIsFilter(jckFilterMode.isSelected());
              final SpinnerNumberModel jspinModel=new SpinnerNumberModel(8,3,15,1);
              final JSpinner jspinnerRows=new JSpinner(jspinModel);
              jspinnerRows.setToolTipText("drop down item count.");
              jspinnerRows.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent e) {
                        int rowCount=jspinModel.getNumber().intValue();
                        ms.setRows(rowCount);
              JPanel paneLeft=new JPanel();
              paneLeft.setLayout(new GridLayout(3,1));
              paneLeft.add(jckDropDownMode);
              paneLeft.add(jckFilterMode);
              paneLeft.add(jspinnerRows);
              JPanel pane=new JPanel();
              pane.setLayout(new BorderLayout());
              pane.add(ms,"Center");
              pane.add(paneLeft,"West");
              Shower.show(pane);
         /*---------user interface element-----------*/
         private JTextField jtfInput=new JTextField();
         private JList jlistReservior=new JList();
         private JScrollPane jscroll4List=new JScrollPane(jlistReservior);
         private JPopupMenu jpopup4List=new JPopupMenu();
         /*---------self property--------------*/
         private boolean isDropDownMode=true;
         private boolean isFilterMode=true;
         private int rows=8;
         private String[] items;
         /*---------constructor--------------*/
         public MSearch1(){
              initUI();
              initEvent();
         private void initUI(){
              jtfInput.setColumns(20);
              //Dimension listSize=new Dimension(20*16,rows*25);
              //jscroll4List.setPreferredSize(listSize);
              setLayout(new BorderLayout());
              add(jtfInput,"North");
              dropModelRefresh();
         private void initEvent(){
              jtfInput.getDocument().addDocumentListener(inputChange);
              jtfInput.addKeyListener(inputKeyListener);
              jtfInput.addComponentListener(resizeListener);
              jlistReservior.addMouseMotionListener(mouseOverShow);
              jlistReservior.addMouseListener(clickSelect);
         //filter items who start with user input;
         private void doFilter(){
              String txt=jtfInput.getText().toLowerCase();
              if(isFilterMode){
                   if(items==null){
                        throw new RuntimeException("please use setItems() to initialize items for select¡£");
                   List fileteredList=new Vector();//<String>
                   for(int i=0;i<items.length;i++){
                        if(items.toLowerCase().startsWith(txt)){
                             fileteredList.add(items[i]);
                   jlistReservior.setListData(fileteredList.toArray());
                   jlistReservior.setSelectedIndex(0);
              }else{
                   jlistReservior.setSelectedIndex(-1);
                   for(int i=0;i<items.length;i++){
                        if(items[i].toLowerCase().startsWith(txt)){
                             jlistReservior.setSelectedValue(items[i], true);
                             return;
         private void refreshPopup(){
              if(isDropDownMode){
                   if(jpopup4List==null){
                        jpopup4List=new JPopupMenu();
                        jpopup4List.add(jscroll4List);
                   jpopup4List.show(jtfInput, jtfInput.getX(), jtfInput.getY()+jtfInput.getHeight());
                   jtfInput.requestFocus();
         //listening user jtfInput change;
         private DocumentListener inputChange=new InputChange();
         class InputChange implements DocumentListener{
              public void changedUpdate(DocumentEvent e) {inputChanged();}
              public void insertUpdate(DocumentEvent e) {inputChanged();}
              public void removeUpdate(DocumentEvent e) {inputChanged();}
              private void inputChanged(){
                   doFilter();
                   refreshPopup();
         //listening user mouse double click jtfInput
         private DoubleClickDropDown clickDropDown=new DoubleClickDropDown();
         class DoubleClickDropDown extends MouseAdapter{
              public void mouseClicked(MouseEvent e){
                   if(e.getButton()==MouseEvent.BUTTON1
                             && e.getClickCount()==2){
                        refreshPopup();
         //listening user click drop down list menu ,select item;
         private ClickSelect clickSelect=new ClickSelect();
         class ClickSelect extends MouseAdapter{
              public void mouseClicked(MouseEvent e){
                   selectInDropDown();
         private void selectInDropDown(){
              jtfInput.setText(jlistReservior.getSelectedValue().toString());
              jpopup4List.setVisible(false);
         //listening user control key;
         private KeyListener inputKeyListener=new InputKeyListener();
         class InputKeyListener extends KeyAdapter{
              public void keyPressed(KeyEvent e){
                   int selected=jlistReservior.getSelectedIndex();
                   if(e.getKeyCode()==KeyEvent.VK_UP){
                        if(selected>0){
                             jlistReservior.setSelectedIndex(selected-1);
                   }else if(e.getKeyCode()==KeyEvent.VK_DOWN){
                        if(selected<(jlistReservior.getModel().getSize()-1)){
                             jlistReservior.setSelectedIndex(selected+1);
                   }else if(e.getKeyCode()==KeyEvent.VK_ENTER){
                        selectInDropDown();
         //listening list mouse over select
         private MouseMotionAdapter mouseOverShow=new MouseOverSelect();
         class MouseOverSelect extends MouseMotionAdapter{
              public void mouseMoved(MouseEvent e){
                   int selected=jlistReservior.getSelectedIndex();
                   int current=jlistReservior.locationToIndex(e.getPoint());
                   if(selected!=current)
                        jlistReservior.setSelectedIndex(current);
         //listening when jtfInput resize
         private ComponentListener resizeListener=new ResizeListener();
         class ResizeListener extends ComponentAdapter{
              public void componentResized(ComponentEvent e){
                   refreshSize();
         /*--------------weather drop down mode---------------------*/
         public boolean getIsDropDown(){
              return isDropDownMode;
         * É趨ÏÂÀģʽ£¬»ò¹Ì¶¨Ä£Ê½¡£É趨ºó×Ô¶¯Ë¢Ð½çÃæ¡£
         * @param dropDown true ±íʾÏÂÀģʽ£¬false ±íʾ¹Ì¶¨Ä£Ê½
         public void setIsDropDownModel(boolean dropDown){
              isDropDownMode=dropDown;
              dropModelRefresh();
              validate();
              repaint();
         private void dropModelRefresh(){
              if(isDropDownMode){
                   remove(jscroll4List);
                   jpopup4List.add(jscroll4List);
                   jtfInput.addMouseListener(clickDropDown);
              }else{
                   jpopup4List.remove(jscroll4List);
                   add(jscroll4List,"Center");
                   jtfInput.removeMouseListener(clickDropDown);
         /*--------------------drop down items-------------------------*/
         public void setItems(String[] strs){
              items=strs;
              refreshItems();
         public String[] getItems(){
              return items;
         private void refreshItems(){
              //if is filter mode ,items may be ordered;
              Comparator cmp = Collator.getInstance(Locale.getDefault());
              java.util.Arrays.sort(items, cmp);
              jlistReservior.setListData(items);
         /*---------------------weather filter mode------------------------*/
         public void setIsFilter(boolean isFilter){
              isFilterMode=isFilter;
              refreshItems();
         public boolean getIsFilterMode(){
              return isFilterMode;
         /*---------------------size property---------------------------------*/
         public int getRows(){
              return rows;
         public void setRows(int rowCount){
              rows=rowCount;
              refreshSize();
              validate();
              repaint();
         public int getColumns(){
              return jtfInput.getColumns();
         public void setColumns(int colCount){
              jtfInput.setColumns(colCount);
              validate();
              repaint();
         private void refreshSize(){
              Font font=jlistReservior.getFont();
              FontMetrics fm=jlistReservior.getFontMetrics(font);
              int height=fm.getHeight()*rows;
              //int height=jlistReservior.getFixedCellHeight()*rows;
              System.out.println(jlistReservior.getFixedCellHeight());
              Dimension size=new Dimension(jtfInput.getWidth(), height);
              jscroll4List.setPreferredSize(size);
         /*--------------------input text property-------------------*/
         public String getText(){
              return jtfInput.getText();
         public void setText(String text){
              jtfInput.setText(text);
    Edited by: tlw_ray on Oct 23, 2008 10:56 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          

  • Popup menu does not show in JTextField

    I have a JPanel with a popup menu that works perfectly, as long as the right mouse button is clicked on the JPanel. However the popup menu does not show if the right mouse button is clicked on a JTextField that is within the JPanel.
    What has to be done that the popup menu shows always?
    this.addMouseListener(new java.awt.event.MouseAdapter()
    public void mouseReleased(MouseEvent e)
    this_mouseReleased(e);
    protected void this_mouseReleased(MouseEvent e)
    if (e.isPopupTrigger())
    popPopup.show(this, e.getX(), e.getY());

    There are up to 20 JTextFields in the JPanels an the application has a lot of JPanels of course. Adding the listener to each and every JTextField means a lot of extra code. Is there really no generic solution to this problem???

  • JTextArea popups up when clicking JTextField

    The project I'm working on requires an input field, single line which can popup a JTextArea for multiple line input.
    So, when user selects ID in a combobox the component doesn't popup the textarea but has the normal JTextField behaviour. When the user selects address, the TextArea pops up to fill in the four lines and when the textarea is closed only the first line will be visible in the input field (JTextField).
    What I did is: I looked at the way the JComboBox works and I made a subclass of the JPopupMenu which holds the textarea, so when focussing the JTextField the focus is displaced to the textarea. But when the focus is Lost I get a nasty error when I want to close the JpopupMenu.
    My question: Are there other possibilities with Swing components to satisfy the requirement or is the way I'm working the best one
    Thnx

    Hi,
    this sounds bad to me - what about a JPanel with a
    Card-Layout in it - there you hold 2 JPanels in it,
    one with the JTextField and one with the JTextArea in
    it - by using Card-Layout you have the effort of
    choosing one of its "cards" to show while the others
    are in the background "under" this card.Well the reason is that the layout of all other GUI components may not change, I mean move down.
    They want to have it as a JTextField, but in rare occassion a TextArea must be visible.
    Isn't there a way that will show the textarea floating over the JTextField?
    I hope, this will give you an idea, how to do this
    greetings Marsian

  • Application wide popup menu for JTextComponent descendants

    Hi!
    I'm working on large project with reach Swing GUI and I got stuck with one small but wery annoing problem. I have to append simple popup menu to all text input fields (JTextComponent descendants) in whole application. I'm realy lazy to append mouse listener on each component, so I'm asking, is there any way to append "default" popup menu for all components. Please, don't answer about custom components instead of Swing plain JTextComponent descendants - it's worse to change classes for all fields then add mouse listener to them.
    As an example of what I want I could forward you to UIManager.put() method, which affects all properties of component behaviour thoughout application. I want to find same solution, maybe there any registry or smth. else in API.
    Than you in advice.

    You could always try extending something like MetalTextFieldUI so that it adds the listeners to the text field automatically. You'd then need to register that UI class with the UIManager at startup:
    public class MyTextFieldUI extends MetalTextFieldUI {
      protected void installListeners() {
        super.installListeners();
        // TODO - Install your listener here
      protected void uninstallListeners() {
        super.uninstallListeners();
        // TODO - Uninstall your listener here
    UIManager.put("TextFieldUI", MyTextFieldUI.class.getName());Personally, I think you're just being lazy... getting your components to extend a subclass of JTextField should be no trouble at all and will leave you with clearer code.
    Hope this helps.

  • JComboBox popup list remains open after losing keyboard focus

    Hi,
    I have noticed a strange JComboBox behavior. When you click on the drop down arrow to show the popup list, and then press the Tab key, the keyboard focus moves to the next focusable component, but the popup list remains visible.
    I have included a program that demonstrates the behavior. Run the program, click the drop down arrow, then press the Tab key. The cursor will move into the JTextField but the combo box's popup list is still visible.
    Does anyone know how I can change this???
    Thanks for any help or ideas.
    --Yeath
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class Test extends JFrame
       public Test()
          super( "Test Application" );
          this.getContentPane().setLayout( new BorderLayout() );
          Box box = Box.createHorizontalBox();
          this.getContentPane().add( box, BorderLayout.CENTER );
          Vector<String> vector = new Vector<String>();
          vector.add( "Item" );
          vector.add( "Another Item" );
          vector.add( "Yet Another Item" );
          JComboBox jcb = new JComboBox( vector );
          jcb.setEditable( true );
          JTextField jtf = new JTextField( 10 );
          box.add( jcb );
          box.add( jtf );
       public static void main( String[] args )
          Test test = new Test();
          test.pack();
          test.setVisible( true );
          test.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

    ran your code on 1.5.0_3, observed problem as stated.
    even though the cursor is merrily blinking in the textfield, you have to click into
    the textfield to dispose the dropdown
    ran your code on 1.4.2_08, no problems at all - tabbing into textfield immediately
    disposed the dropdown
    another example of 'usual' behaviour (involving focus) breaking between 1.4 and 1.5
    the problem is that any workaround now, may itself be broken in future versions

  • How do you set the number of visible items in the popup box of a JComboBox?

    Hi,
    Do you know how to set the number of items that shall be visible in the popup box of a JComboBox?
    I have produced an implementation of an autocomplete JComboBox such that following each character typed in the text field, the popup box is repopulated with items. Normally 8 items are visible when showing the popup box. Sometimes even though the list of items is > 8 the popup box shrinks in height so that 8 items are not visible.
    Thanks,
    Simon

    Below is my JComboBox autocomplete implementation.
    The problem seems to occur when the list of items is reduced in number, the button selected and then the list size increased, the popup box does not automatically increase in size. I have tried setMaximumRowCount � but does not resolve the problem.
    To see how it works:
    1)     click in text field.
    2)     Type 1 � the full list of items are shown.
    3)     Type 0 � the list has been narrowed down � the popup box is greyed out for remaining items.
    4)     Type Backspace � the full list of items is redisplayed.
    5)     Type 0 � to narrow down the list.
    6)     Select button � the popup box is invisible.
    7)     Select button � the popup box is displayed with 2 items.
    8)     Select Backspace � here is the problem � the combo box list contains all items but the popup box has been shrunk so that only 2 are visible.
    9)     Select button � popup box is invisible.
    10)     Select button � popup box is as expected.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.Enumeration;
    import java.util.Vector;
    import javax.swing.plaf.basic.*;
    class Test
    private JComboBox jCB = null;
    private JTextField jTF=null;
    private String typed="";
    private Vector vector=new Vector();
    public Test()
    JFrame fr=new JFrame("TEST ComboBox");
    JPanel p = new JPanel();
    p.setLayout( new BorderLayout() );
    ComboBoxEditor anEditor = new BasicComboBoxEditor();
    String[] s = new String[30];
    for (int i=0; i<30; i++) {
    s[i] = (new Integer(i+10)).toString();
    jTF=(JTextField)anEditor.getEditorComponent();
    jTF.addKeyListener(new KeyAdapter()
    public void keyReleased( KeyEvent ev )
    char key=ev.getKeyChar();
    if (! (Character.isLetterOrDigit(key)
    ||Character.isSpaceChar(key)
    || key == KeyEvent.VK_BACK_SPACE )) return;
    typed="";
    typed=jTF.getText();
    fillCB(vector);
    jCB.showPopup();
    jCB = new JComboBox();
    jCB.setEditor(anEditor);
    jCB.setEditable(true);
    boolean ins;
    for (int x=0; x<30; x++)
    ins = vector.add( new String(s[x]) );
    fillCB(vector);
    jCB.setSelectedIndex(-1);
    fr.getContentPane().add(p);
    p.add("South",jCB);
    p.add("Center",new JButton("test combo box"));
    fr.pack();
    fr.show();
    public void fillCB(Vector vector)
    typed = typed.trim();
    String typedUp = typed.toUpperCase();
    jCB.removeAllItems();
    jCB.addItem("Please select");
    for(Enumeration enu = vector.elements(); enu.hasMoreElements();) {
    String s = (String)enu.nextElement();
    if (s.toUpperCase().startsWith(typedUp)) {
    jCB.addItem(s);
    jTF.setText(typed);
    public static void main( String[] args )
    Test test=new Test();
    Many thanks,
    Simon

  • Popup JTree

    I created a subclass of JWindow which acts as a popup when the appropriate mousebutton is clicked. A JTree is shown in an etched border and when the user selects an item in the tree it updates the JTextField the popup is connected to. It is similar in concept to a JComboBox but rather then a list, it uses a tree. It is connected to two JTextFields in a subclass of JDialog. This works great when dialog box is run in the applet window under VAJ. However, when the dialog box is created (.show()) from within a JApplet in the browser it appears fine when the right mouse button is pressed in the appropriate JTextField but as soon as a mouse button is pressed within the popped up JTree, the popped up window (JWindow subclass) is forced behind the other window. If the roller on the microsoft mouse is used the jtree can be scrolled but if I try to manipulate the scrollbar the window disappears behind the parent window. How can I lock the window in place until I dispose of it??
    Thanks,
    Walt

    The problem is actually a problem in VAJ. The code generated by the VCE does not allow for creating the popup with a parent window. It is still unclear why when it was created on top of the 'parent' window and the scrollbar should have digested the mouse event, that the mouse event percolated through the popup to the underlying window, causing it to gain focus and be placed on top in the Z order. Anyone that can answer that one get the duke bucks too. What I did was modify the alternative constructors for the popup to initialize the window (set the listeners) which appears to be another bug in VAJ and then manually create the popup as invisible. Normally VAJ uses lazy construction to only construct the object upon first reference. Since that code is automatically regenerated by the VCE I couldn't modify it.
    Another question is why does the JWindow appear with the foolish "Java Applet Window" text in a status area. And why does a JWindow even have a status area? The drop down list of a JComboBox doesn't have one. And that was really all I wanted was a JComboBox with a tree instead of a list. So if anyone can address that, there are duke dollars available for it as well.
    So the questions are:
    1) why does the mouse action percolate through the popup window, which should have captured and digested it, even if only through the scrollbar logic?
    2) what does the JWindow based popup get stuck with the "Java Applet Window" text in an unwanted status area.
    3) how could this simply be like a JComboBox with a drop down JTree, as opposed to drop down list?
    Thanks,
    Walt

  • JTextField in a JPopupMenu

    I am trying to put a JTextField into a JPopupMenu. The JTextField is unable to gain focus even after calling grabFocus()/requestFocus(). From searching, it seems there is a glitch that each keep on trying to grab the focus from each other. However, I could not find any solution to the problem. Any advice would be helpful.

    I thought he was about the ones that popup anywhere on a component via a mouseevent/popup trigger, this was a quickie..
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TextFieldInMenu {
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable(){
                public void run() {
                    new TextFieldInMenu().go();
        void go() {
            JFrame f = new JFrame();
            JMenuBar mb = new JMenuBar();
            JMenu menu = new JMenu("test");
            menu.add(new JMenuItem("A popup menu item"));
            menu.add(textfield);
            menu.add(new JMenuItem("Another popup menu item"));
            menu.addMenuListener(new MenuListener(){
                public void menuCanceled(MenuEvent e) {}
                public void menuDeselected(MenuEvent e) {}
                public void menuSelected(MenuEvent e) {
                    EventQueue.invokeLater(new Runnable(){
                        public void run() {
                            textfield.grabFocus();
            mb.add(menu);
            popup.add( new JMenuItem("A popup menu item throught a jpopupmenu" ) );
            popup.add( textfield );
            JPanel panel = new JPanel();
            f.getContentPane().add( panel, BorderLayout.CENTER );
            panel.addMouseListener( new MouseHandler() );
            mb.addMouseListener( new MouseHandler() );
            f.setJMenuBar(mb);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize( 640, 480 );
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        JTextField textfield = new JTextField();
        JPopupMenu popup = new JPopupMenu();
        private class MouseHandler extends MouseAdapter
             public void mousePressed(MouseEvent e) {
                  System.out.println( "Mouse pressed" );
            maybeShowPopup(e);
        public void mouseReleased(MouseEvent e) {
            maybeShowPopup(e);
        private void maybeShowPopup(MouseEvent e) {
             System.out.println( "maybeShowPopup() called" );
            if (e.isPopupTrigger()) {
                popup.show(e.getComponent(),
                           e.getX(), e.getY());
                  textfield.grabFocus();
    }Sorry if it's kinda messy, but it's based off BigDaddy's code and it works for me (the textfield gets focus after calling grabFocus() on it in the maybeShowPopup() method in the MouseHandler implementation of MouseAdapter.

  • Strange behaviour whit custom JTextField and JToolTip

    Hello everyone. I hope I'm writing in the right section and sorry if I did not search for this issue but I really don't know which keywords I should use.
    I'm using NetBeans 6.1 on WinXP and JDK 1.6.0_07, I have a custom JTextField with regex validation: when you type something that don't mach regex it shows a JToolTip. This JToolTip should disappear when the text typed is finally correct, or when the textfield loses focus (see code below).
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Point;
    import javax.swing.JToolTip;
    import javax.swing.Popup;
    import javax.swing.PopupFactory;
    public class MyJTextField extends javax.swing.JTextField implements FormComponent
    private static Popup popUpToolTip;
    private static PopupFactory popUpFactory = PopupFactory.getSharedInstance();
    private boolean isValidated = false;
    private String regEx = "a regex";
    public MyJTextField()
    this.addKeyListener(new java.awt.event.KeyAdapter()
    public void keyReleased(java.awt.event.KeyEvent evt)
    if(evt.getKeyCode()!=java.awt.event.KeyEvent.VK_ENTER)
    validateComponent();
    else if(evt.getKeyCode()==java.awt.event.KeyEvent.VK_ENTER)
    if(isValidated)
    ((Component)evt.getSource()).transferFocus();
    this.addFocusListener(new java.awt.event.FocusAdapter()
    public void focusLost(java.awt.event.FocusEvent evt)
    if(popUpToolTip!=null){popUpToolTip.hide();}
    public void validateComponent()
    if(text.matches(regex))
    isValidated = true;
    if(popUpToolTip!=null){popUpToolTip.hide();}
    else
    isValidated = false;
    if(popUpToolTip!=null){popUpToolTip.hide();}
    String error = "C'&egrave; un errore nella validazione di questo campo";
    JToolTip toolTip = createToolTip();
    toolTip.setTipText(error);
    popUpToolTip = null;
    popUpToolTip = popUpFactory.getPopup(
    this,
    toolTip,
    getLocationOnScreen().x,
    getLocationOnScreen().y - this.getPreferredSize().height -1
    popUpToolTip.show();
    }(I've cut it a bit, here's only the lines that involve JToolTip use)
    I have many of them in a form, and when the first tooltip appears (on the first textfield I type in) it never disappears, while nex textfields work just fine.It seems the first tooltip appearing can't be overwritten or something similar. If I use this same component on any other NetBeans project, everithing works without issues.
    I have some other custom components working the same way (JComboBox, JXDatePicker), and they had this "not disappearing tooltip" issue since I changed this
    popUpToolTip = popUpFactory.getPopup(this, toolTip, getLocationOnScreen().x, getLocationOnScreen().y - this.getPreferredSize().height -1);
    whit this
    popUpToolTip = popUpFactory.getPopup(null, toolTip, getLocationOnScreen().x, getLocationOnScreen().y - this.getPreferredSize().height -1);
    but if I try it on the JTextField all textfield's tooltips stay stuck there, not only the first one appeared (while other components still works fine).
    This thing is really driving me crazy. Someone has an hint (or a link to another thread) which could explain this strange behaviour?
    Thanks in advance.

    BoBear2681 wrote:
    Note that an SSCCE wouldn't require you to post any proprietary code.Hmmm... well, I'll try again to reproduce the issue and post an SSCCE.
    BoBear2681 wrote:
    That probably indicates that the problem is somewhere other than where you're currently looking.Yes, I suppose so. Maybe it's some interference between all the custom components I created, or maybe something else that apparently doesn't conern at all. If I cannot reproduce it in an SSCCE and I'll figure out what's the cause of this mess I'll post it here for future knowledge.
    Many thanks for your advices. :)

  • Popups, focus, and J2SDK 1.4.2

    Hi,
    I have a program that draws a cartoon of a physical device in a JPanel and monitors mouse position, movement and left-clicks on the cartoon. When the user clicks a particular region of the cartoon, a popup containing a JTextField is displayed and given the focus, allowing the user to change the label for that part of the cartoon.
    All this works fine with every 1.4.1 SDK that I've tried. However, if I run the program under any 1.4.2 release, odd things happen. At first, things appear to work normally, but if the program displays a modal dialog like a JFileChooser or a JOptionPane, then dismisses the dialog, a JTextField in the popup that is brought up where the dialog appeared can no longer be given the focus. The problem appears to be associated with the region of the screen where the dialog appeared, not the window position since you can move the program window to a different location and the program will appear to work normally. Move it back to its original position and the "dead" area where the dialog was displayed still won't accept focus.
    I've simplified the original program substantially and can reproduce it with the program listed below.
    * FocusProblem.java
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    import javax.swing.event.MouseInputAdapter;
    import java.awt.*;
    import java.awt.event.*;
    * Illustrate problem with obtaining focus after overlaying panel with
    * a dialog.
    public final class FocusProblem extends JFrame {
        private boolean editing;    // is the editor displayed or not
        private int xPos;           // mouse positions from mouse events
        private int yPos;
        private final JTextField chpEd;
        private final JPanel buttonPanel;
        private final JPanel clickPanel;
        private final JButton theButton;
        private Popup popup;
        private final PopupFactory factory = PopupFactory.getSharedInstance();
        public FocusProblem() {
            editing = false;
            xPos = yPos = -1;
            addWindowListener(new WindowAdapter() {
                public void windowClosing(final WindowEvent evt) {
                    exitForm(evt);
            clickPanel = new JPanel();
            clickPanel.setPreferredSize(new Dimension(600, 400));
            getContentPane().add(clickPanel, BorderLayout.CENTER);
            theButton = new JButton("Show Dialog");
            theButton.addActionListener(new ActionListener() {
                public void actionPerformed(final ActionEvent evt) {
                    theButtonActionPerformed(evt);
            buttonPanel = new JPanel();
            buttonPanel.setBorder(new EtchedBorder());
            buttonPanel.add(theButton);
            getContentPane().add(buttonPanel, BorderLayout.EAST);
            pack();
            chpEd = new JTextField(10);
            // set up the mouse listeners
            final MyListener myListener = new MyListener();
            clickPanel.addMouseListener(myListener);
            clickPanel.addMouseMotionListener(myListener);
         * Handle a click on the button.
         * @param evt Not used.
        private void theButtonActionPerformed(final ActionEvent evt) {
            JOptionPane.showMessageDialog(this, "Just for testing", "A Modal Dialog",
                    JOptionPane.INFORMATION_MESSAGE);
         * Handle a click on the close decoration.
         * @param evt Not used.
        private static void exitForm(final WindowEvent evt) {
            System.exit(0);
        // Editor related methods.
         * Bring up the <code>JTextField</code> over the panel where clicked.
         * Highlight the contents of the test field.
        private void bringUpEditor() {
            editing = true;
            clickPanel.setToolTipText(null);
            chpEd.setText("X = " + xPos + ", Y = " + yPos);
            final Point p = new Point(xPos, yPos);
            // getPopup expects screen coordinates, so do the conversion
            SwingUtilities.convertPointToScreen(p, this);
            popup = factory.getPopup(clickPanel, chpEd, p.x, p.y);
            popup.show();
            chpEd.setVisible(true);
            if (chpEd.requestFocusInWindow() != true) {
                System.out.println("Failed to obtain focus");
    //        chpEd.requestFocus();
    //        chpEd.grabFocus();
            chpEd.getCaret().setDot(0);
            chpEd.getCaret().moveDot(chpEd.getText().length());
         * Hide the editor and set <code>editing</code>
         * to <code>false</code>.
        private void takeDownEditor() {
            popup.hide();
            popup = null;
            editing = false;
        // MouseInputAdapter methods
        final class MyListener extends MouseInputAdapter {
             * Watch mouse clicks on the panel. If the global variable
             * <code>editing</code> is <code>true</code>, the click occurred
             * outside of the editor, so any changes in the editor are
             * accepted and the editor is take down. If <code>editing</code>
             * is <code>false</code>, start editing at the position of the click.
             * @param e The <code>MouseEvent</code> to be responded to. Used
             * to retrieve the mouse position.
            public void mousePressed(final MouseEvent e) {
                if (editing) {
                    takeDownEditor();
                } else {
                    xPos = e.getX();
                    yPos = e.getY();
                    bringUpEditor();
             * Watch for mouse moves. If the global variable <code>editing</code>
             * is <code>false</code>, set the text of the panel's tooltip to the
             * mouse location.
             * @param e The <code>MouseEvent</code> to be responded to. Used to
             * retrieve the mouse position.
            public void mouseMoved(final MouseEvent e) {
                if (!editing) {
                    xPos = e.getX();
                    yPos = e.getY();
                    clickPanel.setToolTipText("X = " + xPos + ", Y = " + yPos);
         * A program entry point to run the test.
         * @param args Not used.
        public static void main(final String[] args) {
            new FocusProblem().show();
    }To observe the problem:
    1. Start the program and allow the mouse to hover near the center of the left panel. A tooltip should appear with the position of the mouse.
    2. Click and a popup with an editor should be brought up. The JTextField should have the focus. Click somewhere else to dismiss the editor.
    3. Click the button in the right pane to display a dialog. over a region of the left panel. Dismiss the dialog.
    4. Click in the area where the dialog was displayed. If running 1.4.1, the JTextField will be focused, just as in step 2. If running 1.4.2, the popup will appear with the JTextField but will not have foucs and will not accept focus by clicking (or any other method I've been able to find.)
    I've observed this problem with Linux (Redhat 9), Windows 98, Win2K, and WinXP on PIII and P4's. The problem occurs with J2SDK 1.4.1 and 1.4.2_01.
    I posted this as a bug right after 1.4.2 came out, but have only received the usual automated reply from Sun. Can't find it in the bug database. Am I missing something or is this really a bug? Any workarounds?
    Other Weirdness
    I've also noticed that if you run the program and let the mouse hover long enough for the tooltip to appear, then move the mouse down so that the tooltip appears to "touch" the bottom border, the tooltip will begin to flicker a lot when you move the mouse around higher in the window when running 1.4.2. Doesn't happen with any J2SDK 1.4.1 release that I've tried. Is this another manifestation of the problem described above?
    Thanks in advance for all the help.

    I'm wondering if you've been able to reconcile the problem. I have exactly the same situation. I've tried everything I could think of, but whenever I call popup.show() followed by a call to requestFocusInWindow,
    I get a false return - meaning of course the popup (or more precisely a JList in the popup) can NOT receive the focus. Same behavior as yours. I really liked the way it worked under 1.4.1 and hate to give it up. Surely hope you've figured it out and can share with me.

  • Cut,copy,paste in jtextfield

    Hi,
    I gotta JTextField. Now I want to get a popup menu when i right-click it to ask me if i wanna cut, copy or paste using the default os clipboard.
    can anyone suggest me any helpful url ?

    Clipboard operations such as copy, cut and paste are very easy to perform on a JTextField. Just use the JTextField's void cut(), copy() and paste() methods! That's all there is to it.
    In this demo I wrote, I've shown how to use these methods, and how to create a JPopupMenu menu that appears when the user right-clicks on the JTextField, showing the three clipboard functions.
    Enjoy!
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ClipboardDemo extends JFrame implements ActionListener {
         JPanel mainPane = new JPanel(new FlowLayout(FlowLayout.LEFT));
         JLabel descrLabel = new JLabel("Clipboard Demo by Ben James");
         JTextField theTextField = new JTextField(20);
         final JPopupMenu clipboardMenu = new JPopupMenu();
         JMenuItem cutMenuItem = new JMenuItem("Cut");
         JMenuItem copyMenuItem = new JMenuItem("Copy");
         JMenuItem pasteMenuItem = new JMenuItem("Paste");
         public ClipboardDemo() {
              super("Clipboard Demo");
              theTextField.setText("Highlight some text and right-click!");
              cutMenuItem.addActionListener(this);
              copyMenuItem.addActionListener(this);
              pasteMenuItem.addActionListener(this);
              clipboardMenu.add(cutMenuItem);
              clipboardMenu.add(copyMenuItem);
              clipboardMenu.add(pasteMenuItem);
              theTextField.addMouseListener(new MouseAdapter() {
                   public void mouseReleased(MouseEvent evt) {
                        if (evt.isPopupTrigger()) {
                             clipboardMenu.show(evt.getComponent(), evt.getX(), evt.getY());
              mainPane.add(descrLabel);
              mainPane.add(theTextField);
              mainPane.setPreferredSize(new Dimension(250,75));
              WindowListener wl = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              setContentPane(mainPane);
              addWindowListener(wl);
              pack();
              setResizable(false);
              setVisible(true);
         public void actionPerformed(ActionEvent evt) {
              Object source = evt.getSource();
              if (source == cutMenuItem) {
                   theTextField.cut();
              if (source == copyMenuItem) {
                   theTextField.copy();
              if (source == pasteMenuItem) {
                   theTextField.paste();
         public static void main(String[] args) {
              ClipboardDemo cd = new ClipboardDemo();
    }

  • Mouse Right-Click menu with JTextField and swing

    Hello,
    I created a small app for providing an organized gui to insert data and log it to a text file. I just recently converted it to swing to improve the functionality of it and try to get away from some of the bugs I found in using regular java.awt.
    So far so good, all of my complaints with regular awt are gone using swing, but I have one problem I see as a real pain.
    With a TextField in java.awt you can right click and get the standard mouse-menu. The mouse menu is nice for cut/copy/paste type operations and I do not want to lose this functionality.
    But with swing and JTextField I am not getting the menu. I right click in there and get nothing. My UIManager is loading the OS one (windows) and I cannot find a way to recover this feature.
    Does anyone know how I can get this working?
    Thanks,
    Lucas

    Well as I posted here to try and see if there was a way to recover what the OS already provides I have struggled through creating a popup menu.
    I have the cut, copy, paste and selectall complete but I am struggling with the undo option.

  • Popup not in specified Component, but in main JFrame

    Hi,
    how do I make a popup appear inside the Component "owner" that is
    given as parameter to the show method?
    I have a JFrame containing a JPanel component in a GridBagLayout.
    The JPanel has a MouseListener, causing "MousePressed" to show a
    popup with a small textfield at the mouse position inside JPanel.
    The popup is called as follows:
    show(e.getComponent(), JTextField, e.getX(), e.getY());
    I also tried giving explicit parameters: show(JPanel, JTextField, 10, 10);
    However, the popup is not positioned inside the JPanel, but in the JFrame that
    contains the JPanel.
    Thanks for any help!
    Regards,
    Elke

    Sorry, my fault: I confused the constructor with the method.
    Below is a test code I made.
    Thanks again,
    Elke
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import javax.swing.*;
    public class PopupTest extends JFrame {
    private JPanel jContentPane = null;
    private JTabbedPane jTabbedPane = null;
    private JPanel jpTab1 = null;
    private JPanel jPanel = null;
    private Popup mousePopup = null;
    public static void main(String[] args) {
    PopupTest myPopup = new PopupTest();
    myPopup.show();
    public PopupTest() {
    super();
    this.setContentPane(getJContentPane());
    this.setSize(300,300);
    private JPanel getJContentPane() {
    if(jContentPane == null) {
    jContentPane = new javax.swing.JPanel();
    jContentPane.setLayout(new BorderLayout());
    jContentPane.add(getJTabbedPane(), BorderLayout.CENTER);
    return jContentPane;
    private JTabbedPane getJTabbedPane() {
    if (jTabbedPane == null) {
    jTabbedPane = new JTabbedPane();
    jTabbedPane.addTab("Tab1", null, getJpTab1(), null);
    return jTabbedPane;
    private JPanel getJpTab1() {
    if (jpTab1 == null) {
    jpTab1 = new JPanel();
    jpTab1.setLayout(new GridBagLayout());
    jpTab1.setName("Tab1");
    GridBagConstraints grid1 = new GridBagConstraints();
    grid1.gridx = 0;
    grid1.gridy = 0;
    jpTab1.add(getJPanel(), grid1);
    return jpTab1;
    private JPanel getJPanel() {
    if (jPanel == null) {
    jPanel = new JPanel() {
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    for(int h = 0;h<100;h++)
    for(int w = 0;w<100;w++)
    g.setColor(Color.blue);
    g.drawRect(w, h, 1, 1);
    jPanel.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    if (e.isPopupTrigger()) {
    int x = e.getX();
    int y = e.getY();
    JLabel mouseData = new JLabel("["+x+","+y+"]");
    // create popup at mouse position inside the JPanel:
    mousePopup = PopupFactory.getSharedInstance().getPopup(e.getComponent(), mouseData, x, y);
    // problem: popup not at mouse position inside JPanel, but at position x,y in the JFrame.
    // Also tried the following, but that didn't work either:
    //mousePopup = PopupFactory.getSharedInstance().getPopup(jPanel, mouseData, x, y);
    // Why is the "owner" parameter in the popup constructor ignored?
    mousePopup.show();
    jPanel.setPreferredSize(new Dimension(100,100));
    return jPanel;
    }

  • Autocomplete popup list menu

    Hi,
    I am impressed by the autocomplete feature when I type in text editor of the netbeans. You know, when I type javax.swing. then I wait for seconds, or press Ctrl-Space, it will popup menu. The popup menu will offer me some word to complete the word "javax.swing.", maybe word like border, JTextField, JTable. So you just press arrow to choose the word. Very convenient. How do I make that kind of popup menu but this time I want to make in cell of the jtable. So if I type something in cell of the jtable, it will check the word I type and popup autocomplete list menu with scrollpane too according the word I type. If I type "wel" then it will offer word "come".
    Thank you.
    Regards,
    akbar

    Hello.
    I have something that might help you. Here is the story : I use IntelliJ IDEA at work and I like very much its auto-completion feature (much better than that of Visual Studio). I like it and use it so much that I often find myself hitting control+space in almost any type text editor.
    At one point, I said to myself : why not exporting the concept to a text editor and enable auto-completion for normal text (not just code). This is why I coded the following class (and later completely forgot about it until now).
    It requires a lexicon file containing the words subject to auto-completion. You can easily modify it and pass a String[].
    Hope it'll help you.import javax.swing.*;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.JTextComponent;
    import javax.swing.event.DocumentListener;
    import javax.swing.event.DocumentEvent;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.CompoundBorder;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import java.util.Set;
    import java.util.TreeSet;
    import java.util.Iterator;
    * <dl>
    * <dt><b>Creation date :</b></dt>
    * <dd> 8 oct. 2003 </dd>
    * </dl>
    * @author Pierre LE LANNIC
    public class PowerEditor extends JPanel {
         private Set theSet;
         private WordMenuWindow theWordMenu;
         private JTextComponent theTextComponent;
         private Window theOwner;
         private static final char[] WORD_SEPARATORS =
                   {' ', '\n', '\t', '.', ',', ';', '!', '?', '\'', '(', ')', '[', ']', '\"', '{', '}', '/', '\\', '<', '>'};
         private Word theCurrentWord;
         private class Word {
              private int theWordStart;
              private int theWordLength;
              public Word() {
                   theWordStart = -1;
                   theWordLength = 0;
              public void setBounds(int aStart, int aLength) {
                   theWordStart = Math.max(-1, aStart);
                   theWordLength = Math.max(0, aLength);
                   if (theWordStart == -1) theWordLength = 0;
                   if (theWordLength == 0) theWordStart = -1;
              public void increaseLength(int newCharLength) {
                   int max = theTextComponent.getText().length() - theWordStart;
                   theWordLength = Math.min(max, theWordLength + newCharLength);
                   if (theWordLength == 0) theWordStart = -1;
              public void decreaseLength(int removedCharLength) {
                   theWordLength = Math.max(0, theWordLength - removedCharLength);
                   if (theWordLength == 0) theWordStart = -1;
              public int getStart() {
                   return theWordStart;
              public int getLength() {
                   return theWordLength;
              public int getEnd() {
                   return theWordStart + theWordLength;
              public String toString() {
                   String toReturn = null;
                   try {
                        toReturn = theTextComponent.getText(theWordStart, theWordLength);
                   } catch (BadLocationException e) {
                   if (toReturn == null) toReturn = "";
                   return toReturn;
         private class WordMenuWindow extends JWindow {
              private JList theList;
              private DefaultListModel theModel;
              private Point theRelativePosition;
              private class WordMenuKeyListener extends KeyAdapter {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                             onSelected();
              private class WordMenuMouseListener extends MouseAdapter {
                   public void mouseClicked(MouseEvent e) {
                        if ((e.getButton() == MouseEvent.BUTTON1) && (e.getClickCount() == 2)) {
                             onSelected();
              public WordMenuWindow() {
                   super(theOwner);
                   theModel = new DefaultListModel();
                   theRelativePosition = new Point(0, 0);
                   loadUIElements();
                   setEventManagement();
              private void loadUIElements() {
                   theList = new JList(theModel) {
                        public int getVisibleRowCount() {
                             return Math.min(theModel.getSize(), 10);
                   theList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                   theList.setBackground(new Color(235, 244, 254));
                   JScrollPane scrollPane = new JScrollPane(theList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                   scrollPane.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
                   setContentPane(scrollPane);
              private void setEventManagement() {
                   theList.addKeyListener(new WordMenuKeyListener());
                   theList.addMouseListener(new WordMenuMouseListener());
              private void onSelected() {
                   String word = (String)theList.getSelectedValue();
                   setCurrentTypedWord(word);
              public void display(Point aPoint) {
                   theRelativePosition = aPoint;
                   Point p = theTextComponent.getLocationOnScreen();
                   setLocation(new Point(p.x + aPoint.x, p.y + aPoint.y));
                   setVisible(true);
              public void move() {
                   if (theRelativePosition != null) {
                        Point p = theTextComponent.getLocationOnScreen();
                        setLocation(new Point(p.x + theRelativePosition.x, p.y + theRelativePosition.y));
              public void setWords(String[] someWords) {
                   theModel.clear();
                   if ((someWords == null) || (someWords.length == 0)) {
                        setVisible(false);
                        return;
                   for (int i = 0; i < someWords.length; i++) {
                        theModel.addElement(someWords);
                   pack();
                   pack();
              public void moveDown() {
                   if (theModel.getSize() < 1) return;
                   int current = theList.getSelectedIndex();
                   int newIndex = Math.min(theModel.getSize() - 1, current + 1);
                   theList.setSelectionInterval(newIndex, newIndex);
                   theList.scrollRectToVisible(theList.getCellBounds(newIndex, newIndex));
              public void moveUp() {
                   if (theModel.getSize() < 1) return;
                   int current = theList.getSelectedIndex();
                   int newIndex = Math.max(0, current - 1);
                   theList.setSelectionInterval(newIndex, newIndex);
                   theList.scrollRectToVisible(theList.getCellBounds(newIndex, newIndex));
              public void moveStart() {
                   if (theModel.getSize() < 1) return;
                   theList.setSelectionInterval(0, 0);
                   theList.scrollRectToVisible(theList.getCellBounds(0, 0));
              public void moveEnd() {
                   if (theModel.getSize() < 1) return;
                   int endIndex = theModel.getSize() - 1;
                   theList.setSelectionInterval(endIndex, endIndex);
                   theList.scrollRectToVisible(theList.getCellBounds(endIndex, endIndex));
              public void movePageUp() {
                   if (theModel.getSize() < 1) return;
                   int current = theList.getSelectedIndex();
                   int newIndex = Math.max(0, current - Math.max(0, theList.getVisibleRowCount() - 1));
                   theList.setSelectionInterval(newIndex, newIndex);
                   theList.scrollRectToVisible(theList.getCellBounds(newIndex, newIndex));
              public void movePageDown() {
                   if (theModel.getSize() < 1) return;
                   int current = theList.getSelectedIndex();
                   int newIndex = Math.min(theModel.getSize() - 1, current + Math.max(0, theList.getVisibleRowCount() - 1));
                   theList.setSelectionInterval(newIndex, newIndex);
                   theList.scrollRectToVisible(theList.getCellBounds(newIndex, newIndex));
         public PowerEditor(Set aLexiconSet, JFrame anOwner, JTextComponent aTextComponent) {
              super(new BorderLayout());
              theOwner = anOwner;
              theTextComponent = aTextComponent;
              theWordMenu = new WordMenuWindow();
              theSet = aLexiconSet;
              theCurrentWord = new Word();
              loadUIElements();
              setEventManagement();
         public JTextComponent getTextComponent() {
              return theTextComponent;
         private void loadUIElements() {
              add(theTextComponent, BorderLayout.CENTER);
         private void setEventManagement() {
              theTextComponent.addFocusListener(new FocusAdapter() {
                   public void focusLost(FocusEvent e) {
                        theTextComponent.requestFocus();
              theTextComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, InputEvent.CTRL_MASK), "controlEspace");
              theTextComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, InputEvent.CTRL_MASK), "home");
              theTextComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_END, InputEvent.CTRL_MASK), "end");
              theTextComponent.getActionMap().put("controlEspace", new AbstractAction() {
                   public void actionPerformed(ActionEvent e) {
                        onControlSpace();
              theTextComponent.getActionMap().put("home", new AbstractAction() {
                   public void actionPerformed(ActionEvent e) {
                        theWordMenu.moveStart();
              theTextComponent.getActionMap().put("end", new AbstractAction() {
                   public void actionPerformed(ActionEvent e) {
                        theWordMenu.moveEnd();
              theTextComponent.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent e) {
                        super.mouseClicked(e);
                        if (theWordMenu.isVisible()) {
                             theWordMenu.setVisible(false);
              theTextComponent.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.isConsumed()) return;
                        if (theWordMenu.isVisible()) {
                             if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                                  theWordMenu.onSelected();
                                  e.consume();
                             } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                                  theWordMenu.moveDown();
                                  e.consume();
                             } else if (e.getKeyCode() == KeyEvent.VK_UP) {
                                  theWordMenu.moveUp();
                                  e.consume();
                             } else if (e.getKeyCode() == KeyEvent.VK_PAGE_DOWN) {
                                  theWordMenu.movePageDown();
                                  e.consume();
                             } else if (e.getKeyCode() == KeyEvent.VK_PAGE_UP) {
                                  theWordMenu.movePageUp();
                                  e.consume();
              theOwner.addComponentListener(new ComponentAdapter() {
                   public void componentHidden(ComponentEvent e) {
                        theWordMenu.setVisible(false);
                   public void componentMoved(ComponentEvent e) {
                        if (theWordMenu.isVisible()) {
                             theWordMenu.move();
              theTextComponent.getDocument().addDocumentListener(new DocumentListener() {
                   public void insertUpdate(DocumentEvent e) {
                        if (theWordMenu.isVisible()) {
                             int beginIndex = e.getOffset();
                             int endIndex = beginIndex + e.getLength();
                             String newCharacters = theTextComponent.getText().substring(beginIndex, endIndex);
                             for (int i = 0; i < WORD_SEPARATORS.length; i++) {
                                  if (newCharacters.indexOf(WORD_SEPARATORS[i]) != -1) {
                                       theCurrentWord.setBounds(-1, 0);
                                       theWordMenu.setWords(null);
                                       theWordMenu.setVisible(false);
                                       return;
                             theCurrentWord.increaseLength(e.getLength());
                             updateMenu();
                   public void removeUpdate(DocumentEvent e) {
                        if (theWordMenu.isVisible()) {
                             theCurrentWord.decreaseLength(e.getLength());
                             if (theCurrentWord.getLength() == 0) {
                                  theWordMenu.setWords(null);
                                  theWordMenu.setVisible(false);
                                  return;
                             updateMenu();
                   public void changedUpdate(DocumentEvent e) {
         private String[] getWords(String aWord) {
              aWord = aWord.trim().toLowerCase();
              Set returnSet = new TreeSet();
              for (Iterator iterator = theSet.iterator(); iterator.hasNext();) {
                   String string = (String)iterator.next();
                   if (string.startsWith(aWord)) {
                        returnSet.add(string);
              return (String[])returnSet.toArray(new String[0]);
         private static boolean isWordSeparator(char aChar) {
              for (int i = 0; i < WORD_SEPARATORS.length; i++) {
                   if (aChar == WORD_SEPARATORS[i]) return true;
              return false;
         private void onControlSpace() {
              theCurrentWord = getCurrentTypedWord();
              if (theCurrentWord.getLength() == 0) return;
              int index = theCurrentWord.getStart();
              Rectangle rect = null;
              try {
                   rect = theTextComponent.getUI().modelToView(theTextComponent, index);
              } catch (BadLocationException e) {
              if (rect == null) return;
              theWordMenu.display(new Point(rect.x, rect.y + rect.height));
              updateMenu();
              theTextComponent.requestFocus();
         private void updateMenu() {
              if (theCurrentWord.getLength() == 0) return;
              String[] words = getWords(theCurrentWord.toString());
              theWordMenu.setWords(words);
         private Word getCurrentTypedWord() {
              Word word = new Word();
              int position = theTextComponent.getCaretPosition();
              if (position == 0) return word;
              int index = position - 1;
              boolean found = false;
              while ((index > 0) && (!found)) {
                   char current = theTextComponent.getText().charAt(index);
                   if (isWordSeparator(current)) {
                        found = true;
                        index++;
                   } else {
                        index--;
              word.setBounds(index, position - index);
              return word;
         private void setCurrentTypedWord(String aWord) {
              theWordMenu.setVisible(false);
              if (aWord != null) {
                   if (aWord.length() > theCurrentWord.getLength()) {
                        String newLetters = aWord.substring(theCurrentWord.getLength());
                        try {
                             theTextComponent.getDocument().insertString(theCurrentWord.getEnd(), newLetters, null);
                        } catch (BadLocationException e) {
                        theCurrentWord.increaseLength(newLetters.length());
              theTextComponent.requestFocus();
              theTextComponent.setCaretPosition(theCurrentWord.getEnd());
              theCurrentWord.setBounds(-1, 0);
         private static Set loadLexiconFromFile(File aFile) throws IOException {
              Set returnSet = new TreeSet();
              BufferedReader reader = new BufferedReader(new FileReader(aFile));
              String line = reader.readLine();
              while (line != null) {
                   returnSet.add(line);
                   line = reader.readLine();
              reader.close();
              return returnSet;
         public static void main(String[] args) {
              try {
                   File lexiconFile = new File("./lexicon.txt");
                   Set lexicon = loadLexiconFromFile(lexiconFile);
                   final JFrame frame = new JFrame("Test");
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   JTextPane textArea = new JTextPane();
                   PowerEditor powerEditor = new PowerEditor(lexicon, frame, textArea);
                   JScrollPane scrollpane = new JScrollPane(powerEditor);
                   scrollpane.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10),
                                                                     BorderFactory.createBevelBorder(BevelBorder.LOWERED)));
                   frame.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent e) {
                             System.exit(0);
                   frame.setContentPane(scrollpane);
                   SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                             frame.setSize(500, 500);
                             frame.setVisible(true);
              } catch (IOException e) {
                   e.printStackTrace();

Maybe you are looking for