Java Swing 和 JComboBox 事件

发布于 2024-10-22 19:35:02 字数 196 浏览 7 评论 0原文

我有一个 JComboBox ,其中包含多个值。我需要能够检测用户何时单击 JComboBox 但不更改当前选定的项目。

发生这种情况时,itemStateChangedactionPerformed 都不会触发。

我应该使用什么事件?

I have a JComboBox with multiple values in it. I need to be able to detect when the user clicks the JComboBox but does not change the currently selected item.

Neither itemStateChanged nor actionPerformed fire when this happens.

What event should I be using?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

时光暖心i 2024-10-29 19:35:02

按下鼠标按钮时记录组合框的状态,并将其与释放鼠标按钮时组合框的值进行比较怎么样?

此时,这是一个简单的相等检查。

How about recording the combo box's state when the mouse button is pressed, and comparing it to the value the box has when the mouse button is released?

At this point, it's a simple equality check.

夜光 2024-10-29 19:35:02

使用 addMouseListener 方法将 MouseListener 添加到 JComboBox 中。您将需要扩展 MouseAdapter 并仅重写 mouseClicked 方法。

Add a MouseListener to the JComboBox using its addMouseListener method. You will want to extend MouseAdapter and override only the mouseClicked method.

咆哮 2024-10-29 19:35:02

如果用户使用键盘打开弹出窗口,然后使用退出键关闭弹出窗口怎么办?

我会使用 PopupMenuListener。这应该处理鼠标和键盘操作。这个概念与其他建议相同。当显示弹出窗口时,您可以保存选定的索引。当关闭时,您可以比较所选索引以查看它是否已更改。

What if the user users the keyboard to open the popup and then uses the escape key to close the popup?

I would use a PopupMenuListener. This should handle both mouse and keyboard actions. The concept would be the same as other suggestions. When the popup is displayed you save the selected index. When is closes you compare the selected index to see it it has changed.

送舟行 2024-10-29 19:35:02

我专门研究了鼠标右键单击项目,所以这是一个略有不同的问题。
但对我来说,解决方案是

  1. 子类 JComboBox 用子类 DefaultListCellRenderer 替换 getCellRenderer()。

  2. 在单元格渲染器中拦截getListCellRendererComponent(),它具有boolean isSelectedboolean cellHasFocus参数,可用于监视鼠标事件和do list.setToolTipText().

我确信非最终选择更改将到达那里,在那里它可以被拦截。

I was looking specifically at right mouse click on items, so it's a slightly different problem.
But the solution for me was to

  1. Subclass JComboBox substituting getCellRenderer() with a subclassed DefaultListCellRenderer.

  2. In the cell renderer intercept getListCellRendererComponent() which has boolean isSelected, boolean cellHasFocus parameters and can be used to watch for mouse events and do list.setToolTipText().

I'm sure the non-final selection change will get there, where it can be intercepted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文