I have  to tell that this is the easiest trick I found so far to dealing with multiple JFrames with Keyboard inputs.(Eg:- Closing a JFrame using ESC button )
Scenario: closing the JFrame "Invoice" by pressing ESC and go to another JFrame "Main_menue".
1) First of all you have to import few things as follows
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
 2) Then Implement your JFrame class to KeyEventDispatcher(used class name is "Invoice")
public class Invoice extends javax.swing.JFrame 
implements KeyEventDispatcher {
3) (Step  3 & 4 make sure to do in JFrame class u want to close) Then you have to Override the method "public boolean dispatchKeyEvent(KeyEvent e) " of  KeyEventDispatcher, as follows.
        @Override
        public boolean dispatchKeyEvent(KeyEvent e)
{
        
            if (e.getID()== KeyEvent.KEY_PRESSED)
        {
                System.out.println("Pressed key From Invoice: "+e.getKeyCode());
              if(e.getKeyCode()==KeyEvent.VK_ESCAPE)
             {
                int y= JOptionPane.showConfirmDialog(rootPane,
                 "Do You want to Exit from Invoice? ","Message", JOptionPane.YES_NO_OPTION);
                
                 if (y==JOptionPane.YES_OPTION)
                      {
                        removemanager(); //remove KeyEventDispatcher
                        new Main_menue().setVisible(true);
                       dispose();
                      }
             }
         }
else if (e.getID() == KeyEvent.KEY_RELEASED) {
           System.out.println("2test2");  //not important(Situational)
            } else if (e.getID() == KeyEvent.KEY_TYPED) {
              System.out.println("3test3"); //not important(Situational)
            }
            return false;
        }
4) Then create two methods to add & remove the KeyEventDispatcher from KeyBoardFocusManager
public void addmanager()
{
KeyboardFocusManager manager1 = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager1.addKeyEventDispatcher(this);
}
     public void removemanager()
 {
KeyboardFocusManager manager2 = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager2.removeKeyEventDispatcher(this);
  }
5) In the Constructor of JFrame call the addmanager()
 Invoice()
 {
        initComponents();
         setExtendedState(MAXIMIZED_BOTH);
    //add the KeyEventDispatcher to KeyBoardFocusManager as follows
          addmanager();
 }
IMPORTANT:  Make sure to call removemanager() when u closing a JFrame, if didn't there will be two KeyeventDispatcher's currently running . which will cause you some troubles.
(Make sure to contact me if have any trouble regarding this post,GOOD LUCK)
 
great ! keep it up
ReplyDeleteThanks Dude
ReplyDeleteHope its easy to understand :)
Nice ,keep up
ReplyDelete