Note that there are some explanatory texts on larger screens.

plurals
  1. POText-wrapping JLabels with no preferred/max/min size
    text
    copied!<p>I'm using JLabels as hyperlinks. I want them to look and function exactly like a link in a browser, so using text panes/editor panes etc is not desirable. The problem is that many of the containers these links will be placed in do not have a size specified: they rely on the size of their parents (or even grand-parents). I am using Boxes for layouts, and if the link text spans more than about two-thirds the width of the box, the box contents begin to stretch outside the actual bounds of the box (so that, if that box were surrounded by a JScrollPane, a horizontal scrollbar would appear).</p> <p>Is there any way to enforce wrapping on a JLabel? Many posts I have read say that puttng the text in HTML tags will cause it to wrap automatically when necessary - but no matter what I do I cannot get this to work. I can't use <br /> tags because I do not know exactly where they would go (unless this could be automated - i.e.</p> <pre><code>if(text.length() &gt; wrapLength) { //break the text into substrings and insert a &lt;br /&gt; at wrapLength //the difficulty is in figuring out the value of wrapLength } </code></pre> <p>)</p> <p>Any ideas would be greatly appreciated. Code for the hyperlink class is below.</p> <pre><code>import java.awt.Color; import java.awt.Desktop; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.swing.JLabel; public class Hyperlink extends JLabel { private URI uri; private String baseText; public Hyperlink(String text, String uri, Font font, Color textColor) { super(text); baseText = text; setFont(font); setForeground(textColor); setOpaque(false); if(Desktop.isDesktopSupported()) { try { setToolTipText(uri); this.uri = new URI(uri); addMouseListener(new LinkMouseListener()); } catch(URISyntaxException ex) { } } } private class LinkMouseListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { Desktop desktop = Desktop.getDesktop(); try { desktop.browse(uri); } catch(IOException ioe) { System.out.println("Something went wrong..."); //DELETE } } @Override public void mouseEntered(MouseEvent e) { setText("&lt;html&gt;&lt;u&gt;" + baseText + "&lt;/u&gt;&lt;/html&gt;"); } @Override public void mouseExited(MouseEvent e) { setText(baseText); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload