Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have Command-W close a window on Mac OS in Java or Clojure

I'd like to have + W close a window/JFrame in a program I am writing in Clojure. How might this be accomplished? Pure Java solutions are also welcome.

like image 358
Jeremy Avatar asked Nov 17 '10 22:11

Jeremy


People also ask

How do you close a window with the keyboard on a Mac?

Command-W: Close the front window. To close all windows of the app, press Option-Command-W.

How do you close all windows on a Mac?

Close one or all windows for an app On your Mac, do any of the following: Close a single window: In a window, click the red Close button in the top-left corner of the window, or press Command-W. Close all open windows for an app: Press Option-Command-W.

How do I keep a window on top Mac?

Other Ways to Keep Your Application Window “Always On Top” First, though, head to the System Preferences screen and choose Mission Control. Here, check that “Displays have separate Spaces” is active, then open some apps. With the toolbar of one app, hover over the green window button.


1 Answers

Here's one way:

 Action closeWindow = new AbstractAction("Close Window") {
   @Override public void actionPerformed(ActionEvent e) {
     // window closing code here
   }
 };
 closeWindow.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(
     KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

Put that Action in a menu on your menubar. The accelerator will be Ctrl + W on Windows.

Probably better would be to use the Keybinding API to have the main panel in each JFrame (assuming there are multiple) bind the same KeyStroke as above in its (WHEN_FOCUSED) input map to an action in its action map that closes the frame.

public class ClosableWindow extends JFrame {
  public void setUp() {
    JPanel mainPanel = createMainPanel();

    int mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
    KeyStroke closeKey = KeyStroke.getKeyStroke(KeyEvent.VK_W, mask);

    mainPanel.getInputMap().put(closeKey, "closeWindow");        

    mainPanel.getActionMap().put("closeWindow", 
        new AbstractAction("Close Window") {
          @Override public void actionPerformed(ActionEvent e) {
            setVisible(false);
            dispose();
          }
        });

    getContentPane().add(mainPanel);      
  }
}
like image 138
ColinD Avatar answered Sep 28 '22 01:09

ColinD