帧退出操作Java

时间:2013-11-11 19:35:25

标签: java swing

如何做到:如果用户按下键盘上的“escape”按钮,然后在用户按下框架的退出按钮时执行代码?

所以我有类似的东西:

if(e.getKeyCode() == 27) {
    if (true) {
        /..
    } else {
    // Program behaves so, like the exit button in 
        // the frame was pushed
    }
}

2 个答案:

答案 0 :(得分:3)

了解How to use keybindings。简单来说,您可以将键绑定到特定操作。例如:

 String key = "ESCAPE";
 KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(key);
 Action escapeAction = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
            frame.dispose();
         }
    };
 frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, key);
 frame.getRootPane().getActionMap().put(key, escapeAction);

答案 1 :(得分:1)

通常会让用户选择,会发生什么:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class CloseVetoFrame extends JFrame {

    public static void main(String[] args) {
        CloseVetoFrame frame = new CloseVetoFrame();
        frame.setSize(300, 200);
        frame.setVisible(true);
    }

    public CloseVetoFrame() {
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                requestExit();
            }

            @Override
            public void windowClosed(WindowEvent e) {
                shutdown();
            }
        });
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == 27) {
                    requestExit();
                }
            }
        });
    }

    protected void requestExit() {
        System.out.println("Window close requested.");
        if (JOptionPane.showConfirmDialog(this, "Exit?") == JOptionPane.YES_OPTION) {
            dispose();
        }
    }

    protected void shutdown() {
        System.out.println("Window closed.");
    }
}

你应该将它与nachokks键绑定方法结合起来。