Making a JEditorPane with html put correctly formatted text in clipboard

后端 未结 3 1928
一向
一向 2020-12-31 06:59

I have this code to demonstrate the problem:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new JEd         


        
3条回答
  •  梦谈多话
    2020-12-31 07:23

    Note: this is not an answer to the question, just a comment with code to the answer by @Thorn, related to security restrictions

    In webstartables with default permissions (that is, none ;-) you can ask the SecurityManager at runtime for a ClipboardService: it will popup a dialog asking the user once to allow (or disallow) the copy. With that, you can replace the default copy action in the textComponent. In SwingX demo we support pasting the code from the source area by:

    /**
     * Replaces the editor's default copy action in security restricted
     * environments with one messaging the ClipboardService. Does nothing 
     * if not restricted.
     * 
     * @param editor the editor to replace 
     */
    public static void replaceCopyAction(final JEditorPane editor) {
        if (!isRestricted()) return;
        Action safeCopy = new AbstractAction() {
    
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    ClipboardService cs = (ClipboardService)ServiceManager.lookup
                        ("javax.jnlp.ClipboardService");
                    StringSelection transferable = new StringSelection(editor.getSelectedText());
                    cs.setContents(transferable);
                } catch (Exception e1) {
                    // do nothing
                }
            }
        };
        editor.getActionMap().put(DefaultEditorKit.copyAction, safeCopy);
    }
    
    private static boolean isRestricted() {
        SecurityManager manager = System.getSecurityManager();
        if (manager == null) return false;
        try {
            manager.checkSystemClipboardAccess();
            return false;
        } catch (SecurityException e) {
            // nothing to do - not allowed to access
        }
        return true;
    }
    

提交回复
热议问题