Java JDialog Escape Key decorate(final JDialog d, boolean closeOnEscape)

Here you can find the source of decorate(final JDialog d, boolean closeOnEscape)

Description

decorate

License

Open Source License

Declaration

public static void decorate(final JDialog d, boolean closeOnEscape) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.KeyStroke;

public class Main {
    private final static List<Image> ICONS = new ArrayList<Image>();

    public static void decorate(final Window w) {
        center(w);//w w w . j  a  v  a 2  s .c  o m
        setIcon(w);
    }

    public static void decorate(final JDialog d, boolean closeOnEscape) {
        center(d);
        setIcon(d);
        if (closeOnEscape) {
            addEscapeListener(d);
        }
    }

    private static void center(Window w) {
        Dimension windowSize = w.getSize();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (screenSize.width - windowSize.width) / 2;
        int y = (screenSize.height - windowSize.height) / 2;
        w.setLocation(x, y);
    }

    private static void setIcon(Window w) {
        w.setIconImages(ICONS);
    }

    public static void addEscapeListener(final JDialog d) {
        ActionListener al = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                d.setVisible(false);
            }
        };
        d.getRootPane().registerKeyboardAction(al, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);
    }
}

Related

  1. addEscKeyAction(javax.swing.JDialog dialog, javax.swing.Action action)
  2. closeOnEsc(final JDialog dlg)
  3. closeOnEsc(JDialog dialog)
  4. closeOnEscape(final JDialog dialog)
  5. closeOnEscapePressed(final JDialog dialog)
  6. enableCloseByEscape(final JDialog dialog)
  7. installEscapeCloseOperation(final JDialog dialog)
  8. installEscapeCloseOperation(final JDialog dialog)
  9. installEscapeCloseOperation(final JDialog dialog)