简体   繁体   English

Java Jframe将关闭所有键盘输入

[英]Java Jframe is closing with all keyboard inputs

Jframe is closing to any input from keyboard just need it to close when user input escape key. Jframe正在关闭来自键盘的任何输入,只需要在用户输入转义键时关闭它即可。 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. Jframe正在关闭来自键盘的任何输入,只需要在用户输入转义键时关闭它即可。 Unable to find similar examples if known issue exist please provide link. 如果存在已知问题,则找不到相似的示例,请提供链接。

Remove the ; 去除 ; after your if-statement, because it ends the statement. 在if语句之后,因为它结束了该语句。

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

"can you show me example where I would place the key binding would it be with KeyEvent?" “您能举例说明我将键绑定与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. 这是键绑定优于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). 这是基于您的程序的最简单示例(请注意,它看起来与使用KeyListener完全不同,因此您需要仔细阅读本教程以了解所有内容)。

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 . 还要注意SwingUtilities.invokeLater That is how you should initialize your swing apps, on the Event Dispatch Thread. 这就是您应该在事件调度线程上初始化swing应用的方法。 See more at Initial Threads 初始线程中查看更多

You are doing (note the semicolon after ...ESCAPE): 您正在做(请注意... 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 问候

You've written the System.exit(0); 您已经编写了System.exit(0); AFTER the if-statement was complemted with an ";". 在if语句后加上“;”。 Just delete the ";" 只需删除“;” behind the closing bracket of the if statement and it is fine. 在if语句的右括号后面,就可以了。 Would be like this then: 然后将是这样的:

if (e.getKeyCode() == KeyEvent.VK_Escape) System.exit(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);
                }

            });

        }



    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM