【问题标题】:Cannot copy/paste from JLable无法从 JLable 复制/粘贴
【发布时间】:2016-01-14 07:59:31
【问题描述】:

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

String msg = "<html>You need to download it from here: <br><b> ttp://chromedriver.storage.googleapis.com/index.html?path=2.20/ </b <br></html>";
JLabel label = new JLabel(msg);
label.setFont(new java.awt.Font("serif", java.awt.Font.PLAIN, 14));
JOptionPane.showMessageDialog(null, label);

但用户不能复制粘贴链接,

【问题讨论】:

  • 您是否考虑过使用底涂层JTextField?还有一些超链接组件实现漂浮在网络上
  • @MadProgrammer 是的,但我不喜欢它的样子
  • @Reimeus 请解释一下?
  • 忘记了 JTextField 不呈现 HTML :P

标签: java jframe jlabel


【解决方案1】:

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

使用JEditorPane...

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 的内容来实际点击链接

另一种方法可能是为JLabel 提供JPopupMenu

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 并单击鼠标左键,只需点击链接即可,但这就是我

【讨论】: