JLabel new line doesn't work

て烟熏妆下的殇ゞ 提交于 2019-12-20 05:45:29

问题


I've encountered some unexpected problem with my String in the setText() method of JLabel.

No matter what I do, it just can't get it to set a new line when asserting variables.

what i've tried so far

Jabel l = new JLabel();
String string = new String();
string = var1+"\n"+var2;
string = var1+"\r\n"+var2;
string = var1+"<html><br/></html>"+var2;

l.setText(string);

回答1:


You can use HTML within the JLabel as described in the online tutorial, and you almost got it right; the text you want to wrap has to be enclosed within the HTML tags like:

string = "<html>" + var1 + "<br/>" + var2 + "</html>";

although it might be better to use StringBuilder to actually build the string.




回答2:


Seems to work just fine for me...

var1+"<html><br/></html>"+var2; doesn't make any sense, in order for the JLabel to know what it should render the String should start with <html> and the rest of the content should follow using standard HTML mark up...

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;

public class Test1 {

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

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

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            String someText = "";
            StringBuilder sb = new StringBuilder(128);
            sb.append("<html><br>").
                    append(someText).append("<br>").
                    append(someText).append("</html>");

            JLabel label = new JLabel();
            label.setBorder(new LineBorder(Color.RED));
            label.setText(sb.toString());
            setLayout(new GridBagLayout());
            add(label);
        }

    }

}


来源:https://stackoverflow.com/questions/27812936/jlabel-new-line-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!