带有可点击链接的JOptionPane

时间:2015-05-06 10:29:13

标签: java swing joptionpane

我正在尝试使用我的JoptionPane消息框提供可点击链接。我开始使用此链接:ARM D.8(30)但它似乎不起作用且链接不可点击。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

@camickr在您分享的链接中提供的解决方案......还有一点挖掘

这就是我做的事情

我必须设置JEditorPane的EditorKit才能处理“text / html”然后我使JEditorPane不可编辑,然后我必须通过实现HyperlinkListener处理Hyperlink并且它有效!

这是我的代码:

public class HtmlInSwing {

    private static JFrame frame;
    private static JPanel panel;
    private static JOptionPane optionPane;
    private static JEditorPane editorPane;

    public static void main(String[] args) {
        frame = new JFrame("Demo frame...");
        panel = new JPanel();
        panel.setBackground(Color.CYAN);
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);

        optionPane = new JOptionPane();
        optionPane.setSize(400, 300);
        editorPane = new JEditorPane();
        panel.add(optionPane, BorderLayout.CENTER);
        optionPane.add(editorPane, BorderLayout.CENTER);
        editorPane.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
        editorPane.setEditable(false);

        HyperlinkListener hyperlinkListener = new     ActivatedHyperlinkListener(frame, editorPane);
        editorPane.addHyperlinkListener(hyperlinkListener);

        editorPane.setText("<a href='http://www.stackoverflow.com'>Go to the     stack</a>");

        editorPane.setToolTipText("if you click on <b>that link you go to     the stack");

        frame.setVisible(true);

    }
}

这是一个说明性的图像:

jeditorpane with html inside

现在这里是HyperlinkListener的实现。

class ActivatedHyperlinkListener implements HyperlinkListener {

    Frame frame;

    JEditorPane editorPane;

    public ActivatedHyperlinkListener(Frame frame, JEditorPane editorPane) {
        this.frame = frame;
        this.editorPane = editorPane;
    }

    public void hyperlinkUpdate(HyperlinkEvent hyperlinkEvent) {
        HyperlinkEvent.EventType type = hyperlinkEvent.getEventType();
        final URL url = hyperlinkEvent.getURL();
        if (type == HyperlinkEvent.EventType.ENTERED) {
            System.out.println("URL: " + url);
        } else if (type == HyperlinkEvent.EventType.ACTIVATED) {
            System.out.println("Activated");
            Runnable runner = new Runnable() {
            public void run() {

            Document doc = editorPane.getDocument();
            try {
                editorPane.setPage(url);
            } catch (IOException ioException) {
                JOptionPane.showMessageDialog(frame,
                    "Error following link", "Invalid link",
                    JOptionPane.ERROR_MESSAGE);
                editorPane.setDocument(doc);
            }
        }
      };
      SwingUtilities.invokeLater(runner);
    }
  }
}

以下是结果的快照(我将保留由您修复的装饰细节,因为我只是说明它有效!)

enter image description here