Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.awt.Component;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;

public class Main {
    /**
     * Attaches a key event listener to given component, disposing of the given window
     * upon pressing escape within the context.
     * 
     * @param context
     * @param button
     */
    public static void simulateExitOnEscape(Component context, JFrame window) {
        context.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    for (WindowListener wl : window.getWindowListeners()) {
                        wl.windowClosing(new WindowEvent(window, WindowEvent.WINDOW_CLOSING));
                    }

                    if (window != null)
                        window.dispose();
                }
            }
        });
    }
}