Texto de múltiplas linhas em JLabel
Pergunta
Como posso fazer o texto de um JLabel estender para outra linha?
Solução
Você pode fazê-lo, colocando HTML no código, assim:
JFrame frame = new JFrame();
frame.setLayout(new GridLayout());
JLabel label = new JLabel("<html>First line<br>Second line</html>");
frame.add(label);
frame.pack();
frame.setVisible(true);
Outras dicas
Se você quer que seu texto JLabel para redimensionar automaticamente, por exemplo, em um GridBagLayout elástica é o suficiente apenas para colocar seu texto em HTML tags como assim:
JLabel label = new JLabel("<html>First line and maybe second line</html>");
Digite o conteúdo (ou seja, o "texto" campo de propriedade) dentro de uma tag <html></html>
. Assim você pode usar <br>
or<P>
para inserir uma nova linha.
Por exemplo:
String labelContent = "<html>Twinkle, twinkle, little star,<BR>How I wonder what you are.<BR>Up above the world so high,<BR>Like a diamond in the sky.</html>";
Ele irá exibir o seguinte:
Brilha, brilha, estrelinha,
Como eu quero saber o que você é.
-Se acima do mundo tão alto,
Como um diamante no céu.
Você também pode usar um JXLabel de < a href = "https://swingx.java.net/" rel = "nofollow"> a biblioteca SwingX .
JXLabel multiline = new JXLabel("this is a \nMultiline Text");
multiline.setLineWrap(true);
Eu tenho usado JTextArea para várias linhas JLabels.
JTextArea textarea = new JTextArea ("1\n2\n3\n"+"4\n");
http://docs.oracle.com/ JavaSE / 7 / docs / api / javax / Swing / JTextArea.html
No meu caso foi o suficiente para dividir o texto em cada \n
e, em seguida, criar um JLabel
para cada linha:
JPanel panel = new JPanel(new GridLayout(0,1));
String[] lines = message.split("\n");
for (String line : lines) {
JLabel label = new JLabel(line);
panel.add(label);
}
Eu usei acima em um JOptionPane.showMessageDialog
String labelText ="<html>Name :"+name+"<br>Surname :"+surname+"<br>Gender :"+gender+"</html>";
JLabel label=new JLabel(labelText);
label.setVisible(true);
label.setBounds(10, 10,300, 100);
dialog.add(label);
por que você está dando coisas complexas ... você pode apenas fazê-lo, colocando "\ n" em vez de html tag