为什么按退出键时框架不关闭?

why doesn#39;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);
    }

}

我已经为按键设置了一个监听器.当我按下 ESC 键时,为什么框架不关闭?

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

推荐答案

调用setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);不会关闭框架,它会定义窗口装饰时的行为[X] 关闭按钮被按下(您已禁用全屏).您可以将其替换为 setVisible(false); 或退出您的程序.

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.

这篇关于为什么按退出键时框架不关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么按退出键时框架不关闭?

基础教程推荐