Daniel
Daniel

Reputation: 4549

Platform specific cut paste mnemonics swing.

I'm developing my own text-like JComponent. It isn't a subclass of JTextComponent, because it isn't using a Document as the model. I'd still like to support the standard mnemonics of cut/copy/paste, but I know that the keystrokes depend on the platform.

Ultimately, I'll let the user edit the keybindings themselves, but for now, I'd like to at least default to something that is sensible.

Is it possible to get it from the LookAndFeel somehow? Or do I need to detect the platform myself and just have a mapping per platform?

I'm using Java 8 if that makes a difference.

Upvotes: 0

Views: 73

Answers (2)

Daniel
Daniel

Reputation: 4549

So, the closest I found to do what I want is the OS X Integration for Java page from Apple. There is a method on the Toolkit class getMenuShortcutKeyMask(), which will help support what I want.

For example, the following will get the right keystroke for "meta-v" on mac, and "ctrl-v" on windows/linux.

KeyStroke.getKeyStroke(KeyEvent.VK_V, 
    Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())

Upvotes: 1

camickr
camickr

Reputation: 324108

There is no LAF property that I'm aware of for this purpose.

However you might be able to use the information from the InputMap of the LAF. The following works for Windows 8:

import java.awt.*;
import javax.swing.*;

public class PlatformMnemonics
{
    public static void main(String[] args)
    {
        KeyStroke copyKeyStroke = null;
        KeyStroke cutKeyStroke = null;
        KeyStroke pasteKeyStroke = null;

        InputMap im = (InputMap) UIManager.get("TextField.focusInputMap");

        for (KeyStroke keyStroke: im.keys())
        {
            boolean upperCase = Character.isUpperCase( keyStroke.getKeyCode() );

            if ( upperCase )
            {
                String actionMapKey = im.get( keyStroke ).toString();

                if ("copy-to-clipboard".equals(actionMapKey))
                    copyKeyStroke = keyStroke;
                else if ("cut-to-clipboard".equals(actionMapKey))
                    cutKeyStroke = keyStroke;
                else if ("paste-from-clipboard".equals(actionMapKey))
                    pasteKeyStroke = keyStroke;

            }
        }

        System.out.println("Copy  KeyStroke: " + copyKeyStroke);
        System.out.println("Cut   KeyStroke: " + cutKeyStroke);
        System.out.println("Paste KeyStroke: " + pasteKeyStroke);
    }
}

Note there are actually 3 bindings on Windows for each Action as you can see in the Key Bindings programs that displays all the key bindings for every Swing component. I just displayed the binding I think you are interested in.

Upvotes: 1

Related Questions