How to show a jPopupMenu just below a jTextfield?

Asked

Viewed 424 times

2

My intention is to create a search field where you type and appear the data of a query in the BD as a popup menu. I got this, 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 the Google search autocomplete! The way I’m doing the menu is over the TF and still exceeds in width and still has more: I don’t 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);
        }

Screenshot of my current menu:

Menu atual

As I would like to: (don’t worry about making the text fit, that I already got :))

Menu ideal

  • the part "System.out.println(nmItemMenu);" I was just supposed to test if I was searching right! You can ignore it!

1 answer

1

I suggest instead of taking the position of Caret (that goes forward as you type the text...) you pick up the position (getLocation or getLocationOnScreen, I can’t remember which is correct) and the 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: the setPopupSize sets the preferred size, not necessarily the actual size. It may also be necessary to assign the minimum and maximum sizes so that the popup does not grow beyond the established width.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.