为什么按键不会触发任何事件? [英] why the key pressed does not trigger any event?

查看:166
本文介绍了为什么按键不会触发任何事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一个程序,显示带有邮件的报警黑屏:

Following is a program that displays a black screen with a messgage ALARM ! :

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


public class displayFullScreen extends Window {
    private JLabel alarmMessage = new JLabel("Alarm !");

    public displayFullScreen() {
        super(new JFrame());
        setLayout(new FlowLayout(FlowLayout.CENTER));
        alarmMessage.setFont(new Font("Cambria",Font.BOLD,100));
        alarmMessage.setForeground(Color.CYAN);
        add(alarmMessage);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setBounds(0,0,screenSize.width,screenSize.height);
        setBackground(Color.black);

        addKeyListener(new KeyAdapter() {
           @Override
           public void keyPressed(KeyEvent ke) {
                escapeHandler(ke);
           } 
        });
    }

    public void escapeHandler(KeyEvent ke) {
        if(ke.getKeyCode() == ke.VK_ESCAPE) {
            System.out.println("escaped !");
        } else {
            System.out.println("Not escaped !");
        }
    }

    public static void main(String args[]) {
        new displayFullScreen().setVisible(true);
    }
}

我在这个程序中设置了一个关键处理程序。当焦点在窗口上时,处理器捕获按下的按键。
当退出键被按下时,转义!应该被显示,否则!转义
但是当我按一个键时,没有任何显示。问题是什么 ?

I have set a key handler in this program . The handler catches the keys pressed when the focus is on window. When the escape key will be pressed escaped ! should be displayed otherwise !escaped. But nothing gets displayed,when i press a key. What is the problem ?

推荐答案

也许你想要一个窗口,但你有两个问题:

Maybe you want a window but you have two problems:


  1. 在使用Swing应用程序时,您应该扩展JWindow而不是窗口

  2. 即使扩展JWindow也不起作用,因为JWindow将不会收到KeyEvent,除非它是父JFrame可见。

所以你应该使用JFrame。如果你不想要标题栏和边框,那么你可以使用未装饰的JFrame。

So you should be using a JFrame. If you don't want the title bar and borders, then you can use an undecorated JFrame.

此外,你不应该使用KeyListener,因为即使在JFrame键事件只发送到关注的组件。相反,您应该使用密钥绑定。在这种情况下,您似乎应该将绑定添加到框架的根窗格。

Also, you should NOT be using a KeyListener because even on a JFrame key events are only dispatched to the focused component. Instead you should be using Key Bindings. In this case it seems you should be adding the binding to the root pane of the frame.

这篇关于为什么按键不会触发任何事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆