12

So say I have a really long line that I want to display in a JLabel. How can I do it?

Currently, longer lines come up as this:

enter image description here

I have to resize the window to see the complete text.

How can I make it so that there's linebreaks when the text almost reaches the width of my JFrame?

I'm not sure if any code is required here for you to answer this, but still:

my frame properties:

frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(450, 400));
frame.setLocation(new Point(400, 300));
frame.setLayout(new BorderLayout());

The label I want to modify:

question = new JLabel("Question:");
question.setFont(new Font("Serif", Font.BOLD, 15));
question.setHorizontalAlignment(JLabel.CENTER);

EDIT: More details:

I am reading lines from a file and then displaying them. The size of lines is not fixed, and so I do not know where to put <br> at.

EDIT 2:

I ended up using JTextArea.

private JTextArea textAreaProperties(JTextArea textArea) {
    textArea.setEditable(false);  
    textArea.setCursor(null);  
    textArea.setOpaque(false);  
    textArea.setFocusable(false);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    return textArea;
}
user2027425
  • 389
  • 3
  • 5
  • 14
  • You may find the second example of this [answer](http://stackoverflow.com/questions/14705684/placing-a-marker-within-the-image/14705893#14705893) helpful. It uses HTML to provide extended layout to a tool tip, but the concept is the same – MadProgrammer Feb 06 '13 at 20:13

4 Answers4

27

Just another example, showing that, with the right layout manager, text wrapped in HTML tags will automatically wrap to the available space...

enter image description here

public class TestHTMLLabel {

    public static void main(String[] args) {
        new TestHTMLLabel();
    }

    public TestHTMLLabel() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                StringBuilder sb = new StringBuilder(64);
                sb.append("<html>I have something to say, it's beter to burn out then to fade away.").
                                append("  This is a very long String to see if you can wrap with in").
                                append("the available space</html>");

                JLabel label = new JLabel(sb.toString());

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(label);
                frame.setSize(100, 100);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }    
        });
    }        
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • That's way too much work for what I need. I ended up using `JTextArea`. See my edit in OP. – user2027425 Feb 06 '13 at 23:03
  • 2
    Adding "" to the start and "" to the end of `String` is to much work?? Wow, you're going to be disappointed :P – MadProgrammer Feb 06 '13 at 23:05
  • The problem I see with this kind of solution is that when dynamically fetched text which already contains html tags, for example for markup, will not display at all (no text will show up) as the and tags are both added twice. It really is a pity that a JLabel doesn't support multiline out of the box. – Timmos Sep 05 '14 at 07:56
  • @Timmos In that case, you wouldn't need to set it up yourself. If you think that you "might" get a html ladden `String` you could also check for it (`String#startsWith`)... – MadProgrammer Sep 05 '14 at 07:57
  • @MadProgrammer You would need to do that check everywhere you need a (multiline)label... For such basic functionality, I prefer reusable code, thus an out-of-the-box component that does it for me. But you are right of course, I just don't consider this a very elegant solution. – Timmos Sep 05 '14 at 11:28
  • @Timmos Okay, so make a factory method, create a custom label..."out-of-the-box" functionality got us the `JSpinner` and `JFormattedFields`, which are great at the jobs they do but so inflexible as to be more frustrating then they are worth (IMHO) – MadProgrammer Sep 05 '14 at 12:42
11

Use HTML to display the text within the Label.

JLabel fancyLabel = new JLabel("<html>Punch Taskmaster</html>");

(Taskmaster-suggested example added in)

arcy
  • 12,845
  • 12
  • 58
  • 103
5

Format with HTML. Works great.

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

public class Test {

    public static void main(String[] args) {
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(new Dimension(450, 400));
        frame.setLocation(new Point(400, 300));
        frame.setLayout(new BorderLayout());

        final JLabel question = new JLabel("<html>Question:<br>What is love?<br>Baby don't hurt me<br>Don't hurt me<br>No more</html>");
        question.setFont(new Font("Serif", Font.BOLD, 15));
        question.setHorizontalAlignment(JLabel.CENTER);

        frame.add(question);

        frame.setVisible(true);
    }


}
  • First thing that comes to mind when someone says the word 'Question' lol –  Feb 06 '13 at 20:18
4

Something like this. The answer give by rcook is very correct. Its just example to show how it can be done.

 b1 = new JLabel("<html>Default Lable I have to resize the
                 <br/> window to see the complete text.</html>");
Matt Clark
  • 27,671
  • 19
  • 68
  • 123
Smit
  • 4,685
  • 1
  • 24
  • 28