Pages

Close JFrame using keyboard

Source code below will show you how to close JFrame using keyboard press. In this source code we will use "Esc" key. So when someone press "Esc" key, and at the same time JFrame focused, the JFrame will close and this program will exit.

**********************************************************************
COMPLETE SOURCE CODE FOR : CloseJFrameUsingKeyboard.java
**********************************************************************


import javax.swing.JFrame;

import java.awt.event.KeyListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class CloseJFrameUsingKeyboard
{
public static void main(String[]args)
{
//Create a KeyListener that can listen when someone press Esc key on keyboard
//You can change for what key that you want, by change value at:
//VK_ESCAPE
KeyListener kl=new KeyAdapter()
{
public void keyPressed(KeyEvent evt)
{
//If someone click Esc key, this program will exit
if(evt.getKeyCode()==KeyEvent.VK_ESCAPE)
{
System.exit(0);
}
}
};

//Create a JFrame with title ( CLOSE JFRAME USING KEYBOARD )
JFrame frame=new JFrame("CLOSE JFRAME USING KEYBOARD");

//add Key Listener to JFrame
frame.addKeyListener(kl);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size to :
//Width : 400 pixels
//Height : 400 pixels
frame.setSize(400,400);

//Make JFrame visible. So we can see it.
frame.setVisible(true);
}
}


**********************************************************************
JUST COMPILE AND EXECUTE IT
**********************************************************************
Related Posts Plugin for WordPress, Blogger...