0

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

所以我有类似的东西:

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

2 回答 2

3

阅读有关如何使用键绑定的信息。简单地说,您将键绑定到特定操作。以您为例:

 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);
于 2013-11-11T19:46:29.940 回答
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 键绑定方法结合使用。

于 2013-11-11T20:12:19.953 回答