-1

Jframe is closing to any input from keyboard just need it to close when user input escape key. Unable to find similar examples if known issue exist please provide link.

package jframe_no_decoration;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.WindowConstants;


public class Jframe_no_decoration {

    public static void main(String args[]) {

        int FrameWidth = 400;
        int FrameHeight = 350;


        JFrame frame = new JFrame ();

        frame.setResizable(false);
        frame.setBounds(0, 0, FrameWidth, FrameHeight);
        frame.setLocationRelativeTo(null);
        frame.setUndecorated(true);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frame.setVisible(true);
        frame.getContentPane().setBackground(Color.black);

        frame.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {

                if( e.getKeyCode() == KeyEvent.VK_ESCAPE);
                System.exit(0);
            }

        });

    }



}

Jframe is closing to any input from keyboard just need it to close when user input escape key. Unable to find similar examples if known issue exist please provide link.

Nathan Morales
  • 71
  • 1
  • 1
  • 6
  • 3
    Get rid of the semi-colon -> `KeyEvent.VK_ESCAPE);`. Also you should prefer to use [Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) over KeyListener – Paul Samsotha Aug 26 '14 at 16:49
  • it worked thank you. can you show me example where I would place the key binding would it be in the if statement at KeyEvent? – Nathan Morales Aug 26 '14 at 17:06

5 Answers5

1

Remove the ; after your if-statement, because it ends the statement.

if( e.getKeyCode() == KeyEvent.VK_ESCAPE); //if the key code is VK_ESCAPE, do nothing
System.exit(0); //in any case, exit the application
J4v4
  • 780
  • 4
  • 9
1

"can you show me example where I would place the key binding would it be with KeyEvent?"

Others have spotted the obvious problem, but have not addressed the other problem you will eventually face down the line. That problem being issues with focus. This is one of the main reasons key bindings are preferred over KeyListener. You get get more information by reading How to Use Key Bindings

Here's is the simplest example based on your program (notice it looks nothing like using a KeyListener - so you need to go over the tutorial to understand what everything means).

import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class SimpleKeyBindDemo {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                JFrame frame = new JFrame("Demo");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(new JLabel("Type Esc to exit"));

                // get the contentPane of the frame
                JPanel panel = (JPanel)frame.getContentPane();
                // bind the Escape key to the contentPane
                addKeyBindToComponent(panel, "ESCAPE", "random");

                frame.setSize(400,  400);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    private static void addKeyBindToComponent(
            JComponent component, String key, String identifier) {

        InputMap imap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        imap.put(KeyStroke.getKeyStroke(key), identifier);
        ActionMap amap = component.getActionMap();
        amap.put(identifier, new AbstractAction(){
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
    }
}

Also notice the SwingUtilities.invokeLater. That is how you should initialize your swing apps, on the Event Dispatch Thread. See more at Initial Threads

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • 1
    After reading [KeyEvent](http://docs.oracle.com/javase/8/docs/api/java/awt/event/KeyEvent.html#VK_ESCAPE) I can see why Key Binding would be better. I believe I originally got the example of using KeyEvent from [lwjgl](http://lwjgl.org/wiki/index.php?title=LWJGL_Basics_2_(Input)) or coderanch. – Nathan Morales Aug 26 '14 at 17:56
0

You are doing (note the semicolon after ...ESCAPE):

if( e.getKeyCode() == KeyEvent.VK_ESCAPE);
System.exit(0);

That is the same that if you do:

if( e.getKeyCode() == KeyEvent.VK_ESCAPE) {
   // nothing happen
}
System.exit(0);

The correct is:

if( e.getKeyCode() == KeyEvent.VK_ESCAPE) {
    System.exit(0);
}

Regards

angel_navarro
  • 1,757
  • 10
  • 11
0

You've written the System.exit(0); AFTER the if-statement was complemted with an ";". Just delete the ";" behind the closing bracket of the if statement and it is fine. Would be like this then:

if (e.getKeyCode() == KeyEvent.VK_Escape) System.exit(0);
cozmic
  • 178
  • 2
  • 7
0

Wanted to post for the future viewer this information.

    package jframe_no_decoration;

    import java.awt.event.ActionEvent;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.*;
    import javax.swing.*;


    public class Jframe_no_decoration {

        public static void main(String[] args) {


            //looking into swingutilities and canvas to make sure both methods work together.
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {

            JFrame frame = new JFrame ();
            JPanel panel = (JPanel)frame.getContentPane();

            addKeyBindToComponent(panel, "ESCAPE", "random");


            int FrameWidth = 400;
            int FrameHeight = 350;
// setBounds() allowed me to set frame in the center of the screen and decided not to use .setSize()
            frame.setBounds(0,0, FrameWidth, FrameHeight);


            // frame.setLayout(new GridBagLayout()); optional will be using Canvas
            // frame.add(new JLabel("Type Esc to exit")); Timer, FadingLabel,   Fader.FadeMode(jmonkeyengine).


            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setResizable(false);

            // setLocationRelativeTo() gets x y coordinate from setBounds() to center frame on screen.
            frame.setLocationRelativeTo(null);

            frame.setUndecorated(true);
            frame.setVisible(true);
            frame.getContentPane().setBackground(Color.black);




            }   
        });

    }   

        // keyBinding information listed in the comments.   
        private static void addKeyBindToComponent( JComponent component, String key, String identifier) {

                InputMap keyboardmap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
                keyboardmap.put(KeyStroke.getKeyStroke(key), identifier);

                ActionMap framemap = component.getActionMap();
                framemap.put(identifier, new AbstractAction(){

                public void actionPerformed(ActionEvent e) {

                    System.exit(0);
                }

            });

        }



    }
Nathan Morales
  • 71
  • 1
  • 1
  • 6
  • Informational linke for: [keyEvent](http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html) [keyListener](http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyListener.html) [keyBinding](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) [Example benefits of keyBinding](https://bugs.mojang.com/browse/MC-30704) [MadProgrammer Java keyListener vs keyBinding](http://stackoverflow.com/questions/23486827/java-keylistener-vs-keybinding) – Nathan Morales Aug 27 '14 at 03:16
  • [Andrew Thompso](http://stackoverflow.com/questions/15290035/key-bindings-vs-key-listeners-in-java)KeyListener vs keyBinding [Per-Erik Bergman](http://stackoverflow.com/questions/21253405/how-to-put-properly-a-libgdx-application-inside-swing-application)canvas and swingutilities inital thread. [Jframe jar on Github](https://github.com/natstarone/jframe) – Nathan Morales Aug 27 '14 at 03:17