Showing posts with label keyboard. Show all posts
Showing posts with label keyboard. Show all posts

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
**********************************************************************

How to make a program that can press keyboard for you ???


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


import java.awt.Robot;
import java.awt.event.KeyEvent;

public class PressKeyboard
{
public static void main(String[]args)
{
try
{

Robot a=new Robot();

while(true)
{
//THIS PROGRAM WILL PRESS A FOR YOU
a.keyPress(KeyEvent.VK_A);

//THIS PROGRAM WILL SLEEP FOR 5 second
a.delay(5000);
}
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


*******************************************************
JUST COMPILE AND EXECUTE IT
*******************************************************

RELAXING NATURE VIDEO