在 Swing 中右键单击焦点 [英] Right click focus in Swing

查看:28
本文介绍了在 Swing 中右键单击焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天在我的 Swing 应用程序中,当我左键单击时,文本区域会聚焦.当我右键单击任何其他文本字段时,会出现弹出菜单,但该文本区域未聚焦.焦点仍然在之前左键单击的字段上.如何从上一个字段中移除焦点并使其出现在右键单击的字段上?

Today in my Swing app when I left click, the text area gets focused. When I do a right click on any other text field,the popup menu appears but that text area is not focused. The focus remains on the field left clicked on before. How do I remove the focus from the previous field and make it appear on the field that is right clicked upon ?

if (e.isPopupTrigger()) {
        ContextMenu menu = new ContextMenu();
        menu.show(tree, e.getX(), e.getY());
    }

在 mouseRelease 上执行此操作.

Doing this on mouseRelease.

推荐答案

假设您的意思是焦点"而不是突出显示":

Assuming you meant 'focus' instead of 'highlight':

创建一个 JTextField 的子类,添加一个鼠标侦听器,并在按下、释放或单击鼠标按钮时强制文本字段请求焦点(三个版本以确保它在每个平台上都能正常工作).

Create a subclass of JTextField, add a mouse listener and force the text field to request focus whenever the mouse button is pressed, released or clicked (three versions to make sure it works on every platform).

import javax.swing.JTextField;

public class TextFieldRClick extends JTextField {

    public TextFieldRClick() {
        super();
        createMouseListener();
    }

    public TextFieldRClick(int cols) {
        super(cols);
        createMouseListener();
    }

    private void createMouseListener() {
        this.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mousePressed(java.awt.event.MouseEvent evt) {
                requestFocusInWindow();
            }

            @Override
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                requestFocusInWindow();
            }

            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                requestFocusInWindow();
            }
        });
    }
}

然后,您可以直接将文本字段创建为new TextFieldRClick()",使它们能够在用户右键单击它们时获得焦点.

You can then create text fields as directly 'new TextFieldRClick()' giving them the ability to get the focus when the user right-clicks them.

我遇到了同样的问题,这为我解决了.

I had the same problem, this solved it for me.

将 requestFocus() 更改为 requestFocusInWindow().requestFocus() 据说是平台相关的,不应再使用.

Changed requestFocus() to requestFocusInWindow(). requestFocus() is said to be platform dependent and should no longer be used.

这篇关于在 Swing 中右键单击焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆