gpt4 book ai didi

java - 为 JLabel 中包含的超链接添加事件

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

我有一个 jlabel 显示内容,然后我添加一个包含内容的超链接。使用标签 .我有一个问题,用户如何单击此超链接,鼠标单击监听器工作。这是我的代码:

String languages="<html> Deutsch, English (All), English (United Kingdom), Bahasa Indonesia, Italiano <a href=\"\">  edit</a> </html>";
GUIConstants.ELM_ALIGN_RIGHT), 240, 0));*/
JLabel lblLanguage= new JLabel();
lblLanguage.setFont((new Font("Arial", Font.PLAIN, 12)));
lblLanguage.setText(languages);

我希望如果用户单击编辑链接,则会显示弹出窗口。否则,单击内容上的文本将不起作用。谢谢

最佳答案

我认为这符合您想要实现的目标:

import java.awt.BorderLayout;   
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

public class HtmlMsg {

public static void main(String[] args) {

JFrame frame = new JFrame("Message with HTML link");

String languages="<html> Deutsch, English (All), English (United Kingdom), "
+ "Bahasa Indonesia, Italiano <a href=\"\"> edit</a> </html>";

frame.getContentPane().add( panelWithHtmlListener(languages));
frame.pack();
frame.setVisible(true);
}

/**
*
* @param msg
* to be displayed. Should contain HTML or html tag.
*
* @return
* Returns a panel with an HTML listener, displaying msg.
*/
private static JPanel panelWithHtmlListener(String msg){

JEditorPane jEditorPane = new JEditorPane("text/html", msg);
jEditorPane.setEditable(false);
jEditorPane.setOpaque(false);

HyperlinkListener listener = new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent hyperLink) {

if (HyperlinkEvent.EventType.ACTIVATED.
equals(hyperLink.getEventType())) {
try {
//respond to html link clicked
JOptionPane.showMessageDialog(null, "HTML has been clicked !!" );
}
catch (Exception ex) { ex.printStackTrace();}
}
}

};

jEditorPane.addHyperlinkListener(listener);

JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout(5, 5));
jPanel.add(jEditorPane, BorderLayout.CENTER);

return jPanel;
}
}

关于java - 为 JLabel 中包含的超链接添加事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31806207/

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