[英]How to know which top container is currently “focused” according to the focused controls?
我有一个显示一个JFrame的应用程序,其中有几个JPanels(A)。 每个JPanel A中都有一些控件,还有一些包含额外控件的复杂组件。 现在,我的应用程序需要知道正在使用JPanel A包含的一组控件中的哪一个,以便可以突出显示该JPanelA。
以下是一些示例代码:
public class MyApp extends JFrame
{
private JPanel A1 = new JPanel();
private JPanel A2 = new JPanel();
private JPanel A3 = new JPanel();
public MyApp()
{
// Add components to the layout, initialize things, etc
...
// Lets suppose each JPanel has 2 components
JComponent C1 = new JComponent();
JComponent C2 = new JComponent();
A1.add(C1);
A1.add(C2);
JComponent C3 = new JComponent();
JComponent C4 = new JComponent();
A2.add(C3);
A2.add(C4);
JComponent C5 = new JComponent();
JComponent C6 = new JComponent();
A3.add(C5);
A4.add(C6);
}
}
因此,我想知道的是哪个JPanel(A1,A2或A3)当前根据使用的是哪个JComponent而被“聚焦”。 重要的一件事是我无法直接从主机访问所有控件,因为那些JComponent在我的应用程序中的其他地方定义为类。 我可以修改它们,但不能说“如果C1内是textfield1,那么A1”。
我一直在阅读,到目前为止,我认为我要做的是实现PropertyChangeListener(如Focus Subsystem的文档中“将焦点更改为多个组件中的跟踪 ”部分所示),以跟踪每个面板和然后将该信息发送到我的应用。
有没有更好的方法可以做到这一点,我不知道呢? 非常感谢。
首先查看KeyboardFocusManager#getFocusOwner
以获得对焦点组件的引用,然后遍历每个父引用,直到它等于您的面板之一或父为null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.