java 如何向 JTextField 添加弹出菜单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1912758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 18:29:09  来源:igfitidea点击:

How to add a popup menu to a JTextField

java

提问by artaxerxe

Can anybody explain me how to add a popup menu at a JtextField? I managed to add a JPopupMenu:

有人能解释一下如何在 JtextField 中添加弹出菜单吗?我设法添加了一个 JPopupMenu:

JPopupMenu popup = new JPopupMenu();
    popup.add("m");
popup.add("n"); 

JTextField textField = new JTextField();
textField.add(popup);

.....

.....

But when i roll the mouse over "popup", nothing is happening (i need to select an item from popup).

但是当我将鼠标滚动到“弹出窗口”上时,什么也没有发生(我需要从弹出窗口中选择一个项目)。

回答by austen

From your comment, it sounds like you are trying to display a sub-menu in the popup that appears over your JTextField.

从您的评论来看,您似乎正在尝试在 JTextField 上方出现的弹出窗口中显示子菜单。

// 1. Let's add the initial popup to the text field.
JTextField textField = new JTextField();
JPopupMenu popup = new JPopupMenu();
textField.add(popup);
textField.setComponentPopupMenu(popup);

// 2. Let's create a sub-menu that "expands"
JMenu subMenu = new JMenu("m");
subMenu.add("m1");
subMenu.add("m2");

// 3. Finally, add the sub-menu and item to the popup
popup.add(subMenu);
popup.add("n");

Hopefully I answered the question you are trying to ask. If not could you explain a bit more on what you are trying to accomplish?

希望我回答了您要问的问题。如果不是,你能解释一下你想要完成的事情吗?

回答by Varun

I don't think its as straightforward as the code in question looks. You may want to have a look at this example

我认为它不像有问题的代码看起来那么简单。你可能想看看这个例子

回答by Boris Pavlovi?

Maybe editable combo boxcould suit you better.

也许可编辑的组合框更适合您。

回答by camickr

Read the JComponent APIfor the setComponentPopupMenu()method.

阅读该方法的 JComponent APIsetComponentPopupMenu()