Search code examples
javaswingkeylistenerjwindow

Add Keylistener to full-screen JWindow


I've made a full-screen JWindow, and I want to add a simple KeyListener that in case of pressing Arrow keys do somethings
But I don't know why it's not working. I've added keylistener to all of Components. But yet it's not working
who knows what's the problem?


Solution

  • By default a JWindow doesn't receive key events unless you specify a JFrame as the owner when you create the window. The following code demonstrates this:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class WindowTest
    {
        public static void main(String[] args)
        {
    
            JFrame frame = new JFrame();
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //      frame.setLocation(-200, 0); // uncomment this line to hide the dummy frame
            frame.setVisible( true );
    
            JWindow window = new JWindow(); // this doesn't work
    //      JWindow window = new JWindow(frame); // this works
    
            window.getContentPane().add( new JTextField(10), BorderLayout.NORTH );
            window.getContentPane().add( new JButton("Button") );
            String[] items = { "Select Item", "Color", "Shape", "Fruit" };
            JComboBox mainComboBox = new JComboBox( items );
            window.getContentPane().add( mainComboBox, BorderLayout.SOUTH );
    
            window.setBounds(50, 50, 200, 200);
            window.setVisible(true);
            window.getRootPane().setBorder(new javax.swing.border.MatteBorder(4, 4, 4, 4, Color.BLUE));
         }
    }
    

    An easier solution is to use an undecorated JFrame:

    JFrame frame = new JFrame();
    frame.setUndecorated(true);
    

    and I want to add a simple KeyListener that in case of pressing Arrow keys do somethings

    Also, you should NOT be using a KeyListener for this. You SHOULD be using Key Bindings.