How to write text in JLabel?

How can I wrap text similar to "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" that is larger than the width of JLabel? I tried to include text in html tags but no luck. Please give your suggestions.

+5
source share
1 answer

The usual approach is to not use JLabel and instead use JTextArea with word wrap and wrapper enabled. Then you can decorate JTextArea so that it looks like JLabel (border, background color, etc.). [Edited to include line ending for completeness on DSquare comment]

Another approach is to use HTML in your shortcut, like here. . Fears there

  • You may need to take care of some characters that HTML can interpret / convert from plain text.

  • The call to myLabel.getText() will now contain HTML (possibly escaped and / or converted characters due to # 1

EDIT: Here is an example JTextArea approach:

enter image description here

 import javax.swing.*; public class JLabelLongTextDemo implements Runnable { public static void main(String args[]) { SwingUtilities.invokeLater(new JLabelLongTextDemo()); } public void run() { JLabel label = new JLabel("Hello"); String text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // String text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " + // "quick brown fox jumped over the lazy dog."; JTextArea textArea = new JTextArea(2, 20); textArea.setText(text); textArea.setWrapStyleWord(true); textArea.setLineWrap(true); textArea.setOpaque(false); textArea.setEditable(false); textArea.setFocusable(false); textArea.setBackground(UIManager.getColor("Label.background")); textArea.setFont(UIManager.getFont("Label.font")); textArea.setBorder(UIManager.getBorder("Label.border")); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(label, BorderLayout.NORTH); frame.getContentPane().add(textArea, BorderLayout.CENTER); frame.setSize(100,200); frame.setLocationRelativeTo(null); frame.setVisible(true); } } 
+6
source

Source: https://habr.com/ru/post/1204901/


All Articles