This question already has an answer here:
Lets say I have a string and JLabel, the JLabel displayed on a JFrame:
public String content="Hello fellow stack-overflowers, I want to format this output";
public JLabel jL = new JLabel();
Once do the following:
jL.setText(content);
I get this output:
Hello fellow stack-overflowers, I want to for..
But what I really want is the text not to keep going right past the length of the label or textfield, but to make a newline every like 4 words or so, something like:
Hello fellow stack-overflowers, I want
to format this output
Ask if more info is needed.
A possible solution is to wrap the label text in HTML
tags and allow the underlying layout manager the ability to resize it, for example...

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test100 {
public static void main(String[] args) {
new Test100();
}
public Test100() {
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 {
private JLabel label;
private JTextField textField;
public TestPane() {
label = new JLabel("<html>Hello fellow stack-overflowers, I want to format this output</html>");
textField = new JTextField(10);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
add(label);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
add(textField, gbc);
}
}
}
This example goes out of it's way to pressure the label to split, you might need to play around with the values a little...
来源:https://stackoverflow.com/questions/26747610/how-to-format-jlabel-jtextfield-so-text-wraps