When writing interfaces in javaSwing, I wanted to implement automatic line wrapping of text content in JLabel. I checked it online and found that most of them were just simpler adding line wrapping. So I wrote a function myself and now posted it for everyone to learn.
The renderings are as follows:
The code is as follows:
package com.zht;import java.awt.BorderLayout;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.FontMetrics;import java.util.concurrent.TimeUnit;import javax.swing.JFrame;import javax.swing.JLabel;public class JLabelDemo extends JFrame {public static void main(String[] args) throws InterruptedException {System.out.println("hello");JLabelDemo jLabelDemo = new JLabelDemo();}public JLabelDemo() throws InterruptedException {String text = "This space contains technical articles," + " blogs and discussion forums with questions and answers." + "As a Java programmer, more and more people feel that Java develops programs from the forums," + "I can't help but feel relieved. hello";JLabel label = new JLabel();label.setSize(200, 0);//Note that JLabel must set width// System.out.println(label.getWidth());JlabelSetText(label, text);setLayout(new FlowLayout());add(label);pack();// setSize(300, 200);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);setVisible(true);}void JlabelSetText(JLabel jLabel, String longString) throws InterruptedException {StringBuilder builder = new StringBuilder("<html>");char[] chars = longString.toCharArray();FontMetrics fontMetrics = jLabel.getFontMetrics(jLabel.getFont());int start = 0;int len = 0;while (start + len < longString.length()) {while (true) {len++;if (start + len > longString.length()) break;if (fontMetrics.charsWidth(chars, start, len) > jLabel.getWidth()) {break;}}builder.append(chars, start, len-1).append("<br/>");start = start + len - 1;len = 0;}builder.append(chars, start, longString.length()-start);builder.append("</html>");jLabel.setText(builder.toString());}}Summarize
The above is all the content of this article about Jlabel's simple example of automatically wrapping content. I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
" Detailed explanation and usage examples of Java programming swing component JLabel "
" Java Programming Implements Swing Circular Button Example Code "
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!