Which swing containers can be set focusable?

2019-08-15 02:37发布

问题:

I’m using a JPanel to add JComponents on and I tried to set the JPanel focusable so when the user clicks on the JPanel, it will unselect any JComponent and call that JComponent’s listener. I've read pretty much every Q&A asked about this and I can't find anything that works. So then I thought: is there another container that I can use?

回答1:

Did you try panel.requestFocus();? Since JPanel is a sub class of Component it could also call this method. This will take focus from whatever has it at the particular moment.

EDIT:

Here goes a code sample showing it working.

import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class PanelOnClickGrabFocus {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                final JPanel p = new JPanel();
                p.setPreferredSize(new Dimension(400, 400));
                JTextField tf = new JTextField(34);
                p.add(tf);
                f.setContentPane(p);
                f.pack();
                f.setVisible(true);
                p.addMouseListener(new MouseAdapter() {    
                    @Override
                    public void mousePressed(MouseEvent e) {
                        p.requestFocus();
                    }
                });
            }
        });
    }
}


回答2:

I suppose you can use any container that implements the FocusListener interface. Create your own or use on the know implemented interfaced described in the documentation. http://docs.oracle.com/javase/6/docs/api/java/awt/event/FocusListener.html