gpt4 book ai didi

java - 带有可点击链接的 JOptionPane

转载 作者:行者123 更新时间:2023-12-02 04:42:06 25 4
gpt4 key购买 nike

我正在尝试为我的 JoptionPane 消息框添加一个可点击的链接。我从这个链接开始:clickable links in JOptionPane但它似乎不起作用,并且该链接不可点击。我怎样才能做到这一点?

最佳答案

@camickr 在您共享的链接中给出的解决方案有效......需要更多的挖掘

这就是我所做的

我必须将 JEditorPane 的 EditorKit 设置为能够处理“text/html”,然后将 JEditorPane 设置为不可编辑,然后我必须通过实现 HyperlinkListener 来处理超链接,它成功了!

这是我的代码:

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

关于java - 带有可点击链接的 JOptionPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30074161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com