简体   繁体   English

显示Java组件中的链接

[英]Displaying links in Java components

I want to display a list of links in a java component, doesn't matter what component it is. 我想在java组件中显示链接列表,无论它是什么组件都无关紧要。 By links I mean URLs of some sites. 通过链接我的意思是一些网站的URL。 Those links can be clicked and doing so opens chosen URL in the default web browser for example google chrome / firefox ( I don't want to display web pages in java, only links ). 可以点击这些链接,这样做可以在默认的Web浏览器中打开所选的URL,例如google chrome / firefox(我不想在java中显示网页,只显示链接)。

I already know how to display single link, but I am having problems with display a list of links. 我已经知道如何显示单个链接,但是我在显示链接列表时遇到问题。 I tried to do it like this : 我试着这样做:

 public void appendTextToJEditorPane(String text) {

    try {
        Document doc = jEditorPane1.getDocument();
        String newLine = "\n";

        String url = "<html><a href=" + text + ">" + text + "<//a><//html>.";

        doc.insertString(doc.getLength(), url, null);
        doc.insertString(doc.getLength(), newLine, null);

    } catch (BadLocationException exc) {
        exc.printStackTrace();
    }


}

    appendTextToJEditorPane("http://google.pl");
    appendTextToJEditorPane("http://wp.pl");
    appendTextToJEditorPane("http://onet.pl");

but it doesn't work due to problems with "/" in the html closing tag. 但由于html结束标记中的“/”问题,它无效。 And I get plain text in JEditorPane. 我在JEditorPane中得到了纯文本。 How to append links properly? 如何正确附加链接?

If you can make an HTML of links and open this page in JEditorPane, will help you to code less and achieve your requirement. 如果您可以制作链接的HTML并在JEditorPane中打开此页面,将帮助您减少代码并实现您的要求。

I hope this works for you. 我希望这适合你。

You can use html in JLabel component. 您可以在JLabel组件中使用html。 That means you can use links via a-href also. 这意味着您也可以通过a-href使用链接。

label.setText("<html><a href="your-link">link</a></html>.")

In Swing, it is possible to put HTML formatted text on a component. 在Swing中,可以将HTML格式的文本放在组件上。 So making your text <html><a href="...">...</a></html> should be enough. 所以制作你的文字<html> <a href="..."> ...... </a> </ html>就足够了。
Otherwise, you'll have to implement an ActionListener that opens the browser. 否则,您将必须实现一个打开浏览器的ActionListener。 You can do this with the Desktop.browse(URI) method. 您可以使用Desktop.browse(URI)方法执行此操作。

If you make your component clickable you can open the browser from within your program with the URL. 如果您使组件可单击,则可以使用URL在程序中打开浏览器。 See java.lang.Desktop, the browse method specifically. 具体请参见java.lang.Desktop,即浏览方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM