Charles Chung
Charles Chung

Reputation: 103

Java KeyListener never works (After setFocusable + requestFocusInWindow)

After adding setFocusable(true) and requestFocusInWindow() my KeyListener inside a JComponent object still doesn't work. Can anyone find the problem?

public class Canvas extends JComponent{
    public Canvas(String str) {
        this.str = str;
        this.setPreferredSize(new Dimension(700, 300));
        setFocusable(true);
        requestFocusInWindow();
        addKeyListener(new KeyAdapter(){
            public void keyTyped(KeyEvent e) {
                out.println("in");
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            public void keyPressed(KeyEvent e) {
                out.println("in");
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            public void keyReleased(KeyEvent e) {
                out.println("in");
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        });
    }

I expect when any key is pressed, "in" would be displayed in the console. Thanks!

Upvotes: 0

Views: 240

Answers (1)

camickr
camickr

Reputation: 324207

After adding setFocusable(true) and requestFocusInWindow() my KeyListener inside a JComponent object still doesn't work.

You can't request focus on a component until the component has been added to a frame has been packed or made visible. So requesting focus in the constructor doesn't do anything.

The basic logic will need to be:

CustomComponent component = new CustomComponent(...);
frame.add( component );
frame.pack();
frame.setVisible( true );
component.requestFocusInWindow();

Note I called the component CustomCompnent because there is already an AWT class called "Canvas", which can be confusing. Use a more descriptive name when creating classes.

Another option is to override the addNotify() method of your class to invoke the requestFocusInWindow() method.

@Override
public void addNotify()
{
    super.addNotify();
    requestFocusInWindow();
}

Upvotes: 1

Related Questions