why the key pressed does not trigger any event?

醉酒当歌 提交于 2019-12-24 20:17:00

问题


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 ?


回答1:


Maybe you want a window but you have two problems:

  1. You should extend JWindow, not Window when using a Swing application
  2. Even extending JWindow won't work because a JWindow won't receive KeyEvent unless it is parent JFrame is visible.

So you should be using a JFrame. If you don't want the title bar and borders, then you can use an undecorated 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.




回答2:


Extend JFrame instead and get rid of the super call.



来源:https://stackoverflow.com/questions/8454043/why-the-key-pressed-does-not-trigger-any-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!