Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't the frame close when i press the escape key?

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


public class displayFullScreen extends JFrame {
        private JLabel alarmMessage = new JLabel("Alarm !");
        private JPanel panel = new JPanel();
        public displayFullScreen() {
            setUndecorated(true);
            panel.setLayout(new FlowLayout(FlowLayout.CENTER));
            alarmMessage.setText("Alarm !");
            alarmMessage.setFont(new Font("Cambria",Font.BOLD,100));
            alarmMessage.setForeground(Color.CYAN);
            panel.add(alarmMessage);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds(0,0,screenSize.width,screenSize.height);
            panel.setBackground(Color.black);
            add(panel);

            addKeyListener(new KeyAdapter() {
               public void keyPressed(KeyEvent ke) {  // handler
        if(ke.getKeyCode() == ke.VK_ESCAPE) {
                       System.out.println("escaped ?");
                       setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // trying to close
                    } else {
                       System.out.println("not escaped");
                     }
              } 
           });
        }          

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

}

I have set a listener for the keys .When ever i press ESC key why doesn't the frame close ?

like image 395
Suhail Gupta Avatar asked Dec 10 '11 09:12

Suhail Gupta


People also ask

How do you exit a frame?

You can close the frame programmatically by sending it the WINDOW_CLOSING event, like this: WindowEvent closingEvent = new WindowEvent(targetFrame, WindowEvent.


1 Answers

The invocation of setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); does not close the frame, it will define the behaviour when the windows decoration [X] close button is pressed (Which you have disabled for full screen). You could replace this with setVisible(false); or exit your programm.

like image 181
stacker Avatar answered Oct 26 '22 19:10

stacker