简体   繁体   中英

How to know which top container is currently “focused” according to the focused controls?

I have an app which displays a JFrame which has several JPanels (A) in it. Each JPanel A has some controls in it and also some complex components holding extra controls. Now, my app needs to know which one of the set of controls contained by a JPanel A is being used, so it can highlight that JPanel A.

Here's some code as an example:

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);
    }
}

So what I'd like to know is which JPanel (A1, A2 or A3) is currently "focused" according to which JComponent is being used. One important thing is I can't have direct access to all the controls from the main frame, because those JComponent are defined as a class somewhere else in my app. I can modify those, but I can't say something like "if it is textfield1 inside C1, then is A1".

I've been reading and so far I think what I got to do is to implement a PropertyChangeListener (as shown in the section Tracking Focus Changes to Multiple Components , from the Focus Subsystem's documentation) to track the focus from the controls inside each panel and then send that information to my app.

Is there any better way to do this and I am not aware of it? Thanks a lot.

首先查看KeyboardFocusManager#getFocusOwner以获得对焦点组件的引用,然后遍历每个父引用,直到它等于您的面板之一或父为null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM