user6725738 user6725738 - 1 month ago 10x
Java Question

How to close JInternalFrame by pressing escape key?

I created one

, in which I am calling
. 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){

    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
    to internal frame, so I able to work with key strokes,but it also doesn't work.

  3. Again I tried to
    to button as escape as below:


    But also gives no output.


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() 

        // other stuff to add to frame
        this.setSize(400, 400);

        this.addKeyListener( this );

    public void keyTyped(KeyEvent e) {
        // Don't need to implement this


    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


    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.