javaswingkeylistenerjinternalframejdesktoppane

How to close JInternalFrame by pressing escape key?


I created one JFrame with JDesktopPane, in which I am calling JInternalFrame. Now I want to close that internal frame by pressing escape key.

I tried 2-3 ways, but no output.

  1. I did that by using code given below:

    public static void closeWindow(JInternalFrame ji){
        ActionListener close=New ActionListener(){
    
        public void actionPerformed(ActionEvent e){
            ji.dispose();
        }
    };
    

    When I called above method from my intern frame class constructor by supplying its object , I was able to close it. But when there I write some other lines of code to the constructor. The above method call doesn't work. Please help me. I unable to find the problem in the code.

  2. Also I tried to add KeyListener to internal frame, so I able to work with key strokes,but it also doesn't work.
  3. Again I tried to setMnemonic to button as escape as below:

    jButton1.setMnemonic(KeyEvent.VK_ESCAPE);
    

    But also gives no output.


Solution

  • You need to implement the KeyListener interface, or add one that is Anonymous. In this example, I just implemented it.

    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    
    import javax.swing.JFrame;
    
    public class JInternalFrame extends JFrame implements KeyListener {
    
        public JInternalFrame() 
        {
            super();
    
    
            // other stuff to add to frame
            this.setSize(400, 400);
            this.setVisible(true);
    
            this.addKeyListener( this );
        }
    
        @Override
        public void keyTyped(KeyEvent e) {
            // Don't need to implement this
    
    
        }
    
        @Override
        public void keyPressed(KeyEvent e) {
            if( e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
                System.exit(0); //Change this to dispose or whatever you want to do with the frame
            }
    
        }
    
        @Override
        public void keyReleased(KeyEvent e) {
            //Dont need to implement anything here
    
        }
    
        public static void main(String[] args)
        {
            JInternalFrame frame = new JInternalFrame();
        }
    
    }
    

    Now if this is an internal jframe as mentioned, it is probably better to implement the keylistener in the JDesktopPane and call the dispose method on the JInternalFrame after pressing escape instead of implementing keylistener in this frame. It all depends on which GUI component has focus of input.