无法从JLable复制/粘贴

时间:2016-01-13 23:18:56

标签: java jframe jlabel

我正在使用下面的代码来显示消息对话框:

  public static double smaller(double x, double y)
  {
    if (x >= y)
        return y;

        return x;
  } //end of larger

但是用户无法复制和粘贴链接,

1 个答案:

答案 0 :(得分:2)

所以,有点“黑客”(不是真的,但也不好)......

使用JEditorPane ...

enter image description here

public class TestPane extends JPanel {

    public TestPane() {
        JEditorPane field = new JEditorPane();
        field.setContentType("text/html");
        field.setText("<html><a href='https://google.com'>Google it</a></html>");
        field.setEditable(false);
        field.setBorder(null);
        field.setOpaque(false);
        setLayout(new GridBagLayout());
        add(field);
    }

}

您还可以使用类似Hyperlink in JEditorPane的内容来实际关注链接

另一种方法可能是为JPopupMenu

提供JLabel

Copy link

public class TestPane extends JPanel {

    public TestPane() {
        JLabel field = new JLabel("<html><a href='https://google.com'>Google it</a></html>");
        field.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        add(field, gbc);
        add(new JTextField(20), gbc);

        JPopupMenu menu = new JPopupMenu();
        menu.add(new CopyAction("https://google.com"));
        menu.add(new OpenAction("https://google.com"));
        field.setComponentPopupMenu(menu);
    }

    public class CopyAction extends AbstractAction {

        private String url;

        public CopyAction(String url) {
            super("Copy");
            this.url = url;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Toolkit tk = Toolkit.getDefaultToolkit();
            Clipboard cb = tk.getSystemClipboard();
            cb.setContents(new StringSelection(url), null);
        }

    }

    public class OpenAction extends AbstractAction {

        private String url;

        public OpenAction(String url) {
            super("Follow");
            this.url = url;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Desktop desktop = Desktop.getDesktop();
            if (desktop.isSupported(Action.BROWSE)) {
                try {
                    desktop.browse(new URL(url).toURI());
                } catch (IOException | URISyntaxException ex) {
                    ex.printStackTrace();
                }
            }
        }

    }

}

我非常想在MouseListener添加JLabel并点击鼠标左键,只需点击链接即可,但那就是我

相关问题