Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright 2002-2016 Jalal Kiswani.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;

import javax.swing.ActionMap;

import javax.swing.InputMap;

import javax.swing.JComponent;

import javax.swing.KeyStroke;

public class Main {
    /**
     * Sets the hot key for focus.
     *
     * @param comp
     *            the comp
     * @param keyStroke
     *            the key stroke
     * @param actionName
     *            the action name
     */
    public static void setHotKeyForFocus(final JComponent comp, final String keyStroke, final String actionName) {
        // get the button's Action map
        final ActionMap amap = comp.getActionMap();
        // add an action to the button's action map
        // and give it a name(it can be any object not just String)
        amap.put(actionName, new AbstractAction() {
            /**
             *
             */
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(final ActionEvent e) {
                // call your a method that contains your action code
                comp.requestFocus();
            }
        });
        // get the input map for the button
        final InputMap imap = comp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        // add a key stroke associated with an action in the action map(action
        // name).
        // imap.put(KeyStroke.getKeyStroke("F1"),"ActionName");
        // you can do the same for more than one key.
        imap.put(KeyStroke.getKeyStroke(keyStroke), actionName);
    }
}