0

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 ?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

2 Answers2

4

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • An alternative would be to add the listener to each component, the solution given to this similar question: http://stackoverflow.com/questions/286727/java-keylistener-for-jframe-is-being-unresponsive – Chip McCormick Dec 10 '11 at 04:06
  • 1
    @ChipMcCormick, no that is not a good solution. As I already stated a KeyListener should NOT be used. Swing was designed to be used with Key Bindings. – camickr Dec 10 '11 at 04:14
1

Extend JFrame instead and get rid of the super call.

Chip McCormick
  • 744
  • 4
  • 17