How to show a jPopupMenu just below a jTextfield?

2

My intention is to create a search field where you go typing and displaying the data of a query in the DB as a popup menu. I already got it, it's working. I created the menu and I can show it on the screen with the data, but the position is the problem: I want something like autocomplete of Google search! The way I'm doing the menu is above the TF and still exceeds in width and there's more: I do not even know if the way I'm positioning the menu is the most appropriate.

My code (the part where the menu is created):

public void mostrarPopUp(DocumentEvent e) {
            tfTexto.setEditable(false);
            pumAutoComp.removeAll();
            List lista = buscar(tfTexto.getText());
            for (int i = 0; i< lista.size(); i++)
            {
                String nmItemMenu;
                nmItemMenu = lista.get(i).toString();
                System.out.println(nmItemMenu);
                JMenuItem item = new JMenuItem(nmItemMenu);
                pumAutoComp.add(item);
                tfTexto.add(pumAutoComp);
                tfTexto.setComponentPopupMenu(pumAutoComp);   
            }
             try {
                  int dotPosition = tfTexto.getCaretPosition();
                  Rectangle popupLocation = tfTexto.modelToView(dotPosition);
                  pumAutoComp.show(tfTexto, popupLocation.x, popupLocation.y);
            } catch (BadLocationException badLocationException) {
                  System.out.println("Oops");
            }
            tfTexto.setEditable(true);
        }

Picture of my current menu:

AsIwouldliketo:(donotworryaboutmakingthetextfit,thisIhavealreadymanaged:))

    
asked by anonymous 29.04.2015 / 20:15

1 answer

1

I suggest instead of picking up the caret position (which will move forward as you type the text ...) you pick up the position ( getLocation or getLocationOnScreen , I can not remember which one is correct) and dimensions ( getSize ) of the text field, and specify the size of the popup in relation to these values. For example:

int margem = 4; // Pro menu não ficar "agarrado" à caixa de texto

Point locTexto = tfTexto.getLocation(); // ou getLocationOnScreen
Dimension tamTexto = tfTexto.getSize();
pumAutoComp.setPopupSize(tamTexto.width, 300); // A altura é de sua escolha
pumAutoComp.show(tfTexto, locTexto.x, locTexto.y + tamTexto.height + margem);

Note: setPopupSize sets the preferred size, not necessarily the actual size. You may also need to assign the minimum and maximum sizes so that the popup does not grow beyond the established width.

    
29.04.2015 / 20:48