当我按下退出键时,为什么框架不关闭?

时间:2011-12-10 09:53:59

标签: java swing events jframe actionlistener

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键时,为什么帧不关闭?

4 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:7)

使用dispose()方法。

addKeyListener(new KeyAdapter() {
 public void keyPressed(KeyEvent ke) {  // handler
    if(ke.getKeyCode() == ke.VK_ESCAPE) {
      System.out.println("escaped ?");
      displayFullScreen.this.dispose();
      } 
     else {
      System.out.println("not escaped");
      }
     } 
});

答案 2 :(得分:5)

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;

public abstract class EscapableFrame extends JFrame
{
    public EscapableFrame()
    {
        // on ESC key close frame
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
        KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel"); //$NON-NLS-1$
        getRootPane().getActionMap().put("Cancel", new AbstractAction()
        { 

            public void actionPerformed(ActionEvent e)
            {
                System.exit(0);
                //framename.setVisible(false);
            }
       });

   }

}

答案 3 :(得分:3)

您没有在esc键上关闭相框。您只需设置其默认关闭操作,因此您必须编写

System.exit(0);

dispose();

而不是

setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

如果您不想退出该应用程序,请使用setVisible(false)


提示:

VK_ESCAPEKeyEvent类的静态字段,因此您可以ke.VK_ESCAPE代替KeyEvent.VK_ESCAPE