Domanda

Snippet

Hi, I'm building a simple tagging tool using Java Swing. There are two JLists in the component, and whenever I click the tagging button, I want to add a tag to the given text. If my cursor focus is on the left JList, I want to modify the text on the left JList, and if it's on the right one, modify the right one. What I mean by cursor focus is the place where I can navigate the list items using keyboard arrows.

So the button listener should tell whether the current cursor focus is on the left Jlist or the right one. How should I do this? I've already tried using "getFocusOwner", but it returns the button I just clicked.

È stato utile?

Soluzione

While not the most elegant way, you can add a FocusListener to your Jlists

public class CheckFocus extends JFrame {

    JList<String> focusedList = null;
    JList<String> list1 = new JList<>(new String[]{"A", "B"});
    JList<String> list2 = new JList<>(new String[]{"1", "2"});

    CheckFocus() {

        JButton btn = new JButton("Who has focus?");

        btn.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {    

                if (focusedList.equals(list1))
                    System.out.println("list1");
                else if (focusedList.equals(list2))
                    System.out.println("list2");
                else
                    System.out.println("none");
            }
        });

        MyFocusListener mfl = new MyFocusListener();
        list1.addFocusListener(mfl);
        list2.addFocusListener(mfl);

        getContentPane().add(list1, BorderLayout.LINE_START);
        getContentPane().add(list2, BorderLayout.LINE_END);
        getContentPane().add(btn, BorderLayout.CENTER);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {

        new CheckFocus();
    }


    class MyFocusListener extends FocusAdapter {

        @Override
        public void focusGained(FocusEvent e) {

            super.focusGained(e);
            focusedList = (JList<String>) e.getSource();
        }
    }
}

If you select a cell on each list and then press a button, the JVM treats the lists the same - they both do not have focus at the moment. What you want is to know which had focus just before you pressed the button, but the JVM does not store this kind of information so you have to store it yourself.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top