gpt4 book ai didi

java - JOptionPane 中的可点击链接

转载 作者:IT老高 更新时间:2023-10-28 20:29:08 25 4
gpt4 key购买 nike

我正在使用 JOptionPane 来显示一些产品信息,需要添加一些网页链接。

我发现您可以使用包含 html 的 JLabel,因此我包含了 <a href>关联。该链接在对话框中显示为蓝色并带有下划线,但不可点击。

例如,这也应该有效:

public static void main(String[] args) throws Throwable
{
JOptionPane.showMessageDialog(null, "<html><a href=\"http://google.com/\">a link</a></html>");
}

如何在 JOptionPane 中获得可点击的链接?

谢谢,保罗。

编辑 - 例如解决方案

public static void main(String[] args) throws Throwable
{
// for copying style
JLabel label = new JLabel();
Font font = label.getFont();

// create some css from the label's font
StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";");
style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";");
style.append("font-size:" + font.getSize() + "pt;");

// html content
JEditorPane ep = new JEditorPane("text/html", "<html><body style=\"" + style + "\">" //
+ "some text, and <a href=\"http://google.com/\">a link</a>" //
+ "</body></html>");

// handle link events
ep.addHyperlinkListener(new HyperlinkListener()
{
@Override
public void hyperlinkUpdate(HyperlinkEvent e)
{
if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED))
Desktop.getDesktop().browse(e.getURL().toString()); // roll your own link launcher or use Desktop if J6+
}
});
ep.setEditable(false);
ep.setBackground(label.getBackground());

// show
JOptionPane.showMessageDialog(null, ep);
}

最佳答案

您可以将任何组件添加到 JOptionPane。

所以添加一个 JEditorPane 来显示您的 HTML 并支持 HyperlinkListener。

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

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