简体   繁体   中英

How do i append a new text at JLabel?

I read, some StackOverflow questions that I need to use HTML stuffs. But what would be the easiest it without any of HTML stuff.

Here's the code

label.setText(label.getText() + (String)boxTimes.getSelectedItem() + input);

This code will produce this

在此处输入图片说明

What I want is:

在此处输入图片说明

You must know a bit of basic String format:

  • \\n line break
  • \\t tab

So your code will be like:

String myLabel = 
      // 4
      label.getText() + "\n\n" + 
      // 7:00
      (String)boxTimes.getSelectedItem() + "\t" +
      // - Going out....
      "- " + input;

label.setText(myLabel);

But as long as JLabel does not accept \\n as Abishek Manoharan pointed, you must use <br> .

String  myLabel = 
    "<html>" + 
        label.getText() + 
        "<br/><br/>" +
        (String)boxTimes.getSelectedItem() + " - " + input + 
    "</html>;

label.setText(myLabel);

I was faced with the same problem too and couldn't find a viable solution.
So I went ahead and used a JTextArea instead of JLabel .

JTextArea label = new JTextArea();
label.setEditable(false);
label.setBackground(null);
  1. It gives the same look and feel of a JLabel
  2. You can use '\\n' and '\\t' as you like,
  3. and what more, the text is selectable which is not possible in JLabel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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