Reputation: 157
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);
Upvotes: 1
Views: 5018
Reputation: 347184
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);
}
}
}
Upvotes: 1
Reputation: 44871
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.
Upvotes: 4