5

I cant believe fastest solution for a multilined JLabel is the following one (text comes from a var, and so I dont want to put HTML code manually every x chars, its so ugly):

public class JMultilineLabel extends JTextArea{
    private static final long serialVersionUID = 1L;
    public JMultilineLabel(String text){
        super(text);
        setEditable(false);  
        setCursor(null);  
        setOpaque(false);  
        setFocusable(false);  
        setFont(UIManager.getFont("Label.font"));      
        setWrapStyleWord(true);  
        setLineWrap(true);
    }
} 

... sure it isnt a better way to handle this????

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Whimusical
  • 6,401
  • 11
  • 62
  • 105
  • Why would you set the `JTextArea` to non-editable, this way you would get something more equivalent to `JLabel` rather than `JTextField` which whole point is to be editable :) or maybe you are actually after a multiline `JLabel`? – Boro Jun 14 '12 at 13:21
  • Wow sorry, I wanted to say JLabel sorrrryy I changed, what was I thinking? – Whimusical Jun 14 '12 at 13:25
  • But know I should look again if theres any answer for this,, so maybe its duplicated since the suggested results did not fit (obviously) my doubts – Whimusical Jun 14 '12 at 13:25
  • Yea it is a duplicate, some of the links in **BTW** section of my answer. I forgot to check it out since you mentioned `JTextField` first I started to think about it. – Boro Jun 14 '12 at 13:34
  • Yeah but I mantain my question, because I need to make linewrapping automatically, and not having to parse the incoming string and put a
    every x chars
    – Whimusical Jun 14 '12 at 13:43
  • Thanks for showing me, how to make `JTextArea` font look acceptable (`UIManager` stuff). – Jarekczek Dec 03 '16 at 14:39

2 Answers2

3

If you want a multilne label then you simply use HTML in its text, as they support its use. Therefore, use line brake tag </br> to break lines or put separate lines in <p></p> paragraph tags.

Do not forget to mark that you want to use HTML for a JLabel by starting its text with the <html> tag.

More available here.

BTW I forgot to check if there were other related questions about JLabel use and there were at least a few, check this or this. :)


EDIT:

For a working sample, showing a different approach, without setting a style and with use of paragraph and label taking available space, please see below:

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;

public class LabelHTMLAutoResize {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JPanel p = new JPanel(new BorderLayout());
                JLabel l = new JLabel("<html><p> Some verrrry long text  Some verrrry long  Some verrrry long text dsa ads oiosi o</p>");
                l.setVerticalAlignment(SwingConstants.TOP);
                l.setOpaque(true);
                l.setBackground(Color.green);
                p.add(l);
                f.setContentPane(p);
                /* good practice is to use f.pack(); and let the size be automatically calculated but we want to show line wrapping thus frame size is set */
                f.setSize(200, 200);
                f.setVisible(true);
            }
        });
    }
}
Community
  • 1
  • 1
Boro
  • 7,913
  • 4
  • 43
  • 85
3

I need to make linewrapping automatically, and not having to parse the incoming string and put a <BR> every x chars

Set the body width (of the HTML). Swing HTML support includes basic styles.

I had some examples of using CSS to limit the width of a JLabel lying around SO somewhere..


Aah yes, there it is:

import javax.swing.*;

class FixedWidthLabel {

    public static void main(String[] srgs) {
        String s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu nulla urna. Donec sit amet risus nisl, a porta enim. Quisque luctus, ligula eu scelerisque gravida, tellus quam vestibulum urna, ut aliquet sapien purus sed erat. Pellentesque consequat vehicula magna, eu aliquam magna interdum porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed sollicitudin sapien non leo tempus lobortis. Morbi semper auctor ipsum, a semper quam elementum a. Aliquam eget sem metus.";
        String html1 = "<html><body style='width: ";
        String html2 = "px'>";

        JOptionPane.showMessageDialog(null, new JLabel(html1+"200"+html2+s));
        JOptionPane.showMessageDialog(null, new JLabel(html1+"300"+html2+s));
    }
}

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • +1 nice one I was wondering how to limit the text size. After a while I chose a different approach (presented in my **EDIT**). – Boro Jun 14 '12 at 14:15
  • @Boro *"After a while I chose a different approach"* Have you tested that approach in a tool-tip? – Andrew Thompson Jun 14 '12 at 14:21
  • I am guessing, that by asking me the above question you meant, that in a tool-tip it will not wrap, right? I agree, since the width was never set thus tool-tip will take all that is available before it will wrap, thus, in this case yours solution is the one. – Boro Jun 14 '12 at 14:38
  • *"in a tool-tip it will not wrap, right?"* Got it in one. Mind you, I have not tested it, but I noted your example set a limit to the size of the external container - and there is no opportunity to do that with a tool-tip (AFAIK). – Andrew Thompson Jun 14 '12 at 14:46
  • Yea. I wanted a solution that would make the label size dependent from its parent. Thus, I have control over it via layout manager rather than controlling its size directly plus if you are building such a solution, i.e. a component that can have many lines you should always put it into a `JSCrollPane` as you do not want to end up with a gigantic component which you will not be able to read because some lines will not be visible. – Boro Jun 14 '12 at 14:55