【问题标题】:copy jTextPane text to clipboard将 jTextPane 文本复制到剪贴板
【发布时间】:2013-04-24 10:07:49
【问题描述】:

我有一个包含jTextPanejButton 的表单,我已将jTextPane Accessible Description 设置为text/html,现在我想要点击jButton 复制内容jTextPane 到我的剪贴板,我尝试了这段代码:

 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        StringSelection stringSelection = new StringSelection (jTextPane1.getText());
        Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard ();
        clpbrd.setContents (stringSelection, null);
    } 

但是当我过去时,它会以 HTML 格式的文本过去。

我该如何解决这个问题?

【问题讨论】:

    标签: java swing jtextpane


    【解决方案1】:

    首先,Java 中有 2 个剪贴板(您正在使用的一个本地剪贴板和一个系统剪贴板)。 Here 是一个使用系统剪贴板的示例。看看并尝试这个 getClipboardContents 方法:

    public String getClipboardContents(Clipboard clipboard) {
        String result = "";
        if (clipbloard != null){            
            //odd: the Object param of getContents is not currently used
            Transferable contents = clipboard.getContents(null);
            boolean hasTransferableText =
              (contents != null) &&
              contents.isDataFlavorSupported(DataFlavor.stringFlavor);
            if ( hasTransferableText ) {
              try {
                result = (String)contents.getTransferData(DataFlavor.stringFlavor);
              }
              catch (UnsupportedFlavorException ex){
                //highly unlikely since we are using a standard DataFlavor
                System.out.println(ex);
                ex.printStackTrace();
              }
              catch (IOException ex) {
                System.out.println(ex);
                ex.printStackTrace();
              }
            }
        }
        return result;
    }
    

    【讨论】:

    • 在我看来,问题在于设置或获取内容,它的蚂蚁将文本从 JTextpane 转换为纯文本(剥离 HTML 标签)
    【解决方案2】:

    当我使用 Ctrl+C 时,我将文本复制到没有 HTML 的剪贴板。您可以通过以下代码使用默认操作:

    Action copy = new ActionMapAction("Copy", textPane, "copy-to-clipboard");
    JButton copyButton = new JButton(copy);
    

    有关其工作原理的更多信息,请参阅Action Map Action

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多