2) 独自で実装する
* paintComponent() をオーバーライドして計算して折り返しを実装する
サンプル
http://ateraimemo.com/Swing/GlyphVector.htmlを参考に実装(ただし、気になる点あり)
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.font.FontRenderContext; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextAttribute; import java.awt.font.TextLayout; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import javax.swing.Box; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.LineBorder; public class WrappedLabel extends JLabel { private static final long serialVersionUID = 1L; public static void main(String[] args) { JFrame frame = new JFrame("WrappedLabel Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Box box = Box.createVerticalBox(); String text = "あいう。1234567890123456789012345678901234567890"; JLabel jLabel = new JLabel(text); jLabel.setBorder(new LineBorder(Color.BLACK, 2)); jLabel.setPreferredSize(new Dimension(50, 100)); box.add(jLabel); box.add(Box.createVerticalGlue()); String text2 = "あいう。1234567890123456789012345678901234567890"; WrappedLabel wrappedLabel = new WrappedLabel(text2); wrappedLabel.setBorder(new LineBorder(Color.BLACK, 2)); wrappedLabel.setPreferredSize(new Dimension(50, 100)); box.add(wrappedLabel); frame.add(box); frame.setBounds(100, 200, 400, 400); frame.setVisible(true); } public WrappedLabel(String text) { super(text); } @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g.create(); g2.setPaint(this.getForeground()); Insets insets = this.getInsets(); float x = insets.left; float y = insets.top; int width = this.getWidth() - insets.left - insets.right; AttributedString attributedString = new AttributedString(this.getText()); attributedString.addAttribute(TextAttribute.FONT, this.getFont()); AttributedCharacterIterator attributedCharacterIterator = attributedString.getIterator(); FontRenderContext fontRenderContext = g2.getFontRenderContext(); LineBreakMeasurer lineBreakMeasurer = new LineBreakMeasurer(attributedCharacterIterator, fontRenderContext); while (lineBreakMeasurer.getPosition() < attributedCharacterIterator.getEndIndex()) { TextLayout textLayout = lineBreakMeasurer.nextLayout(width); textLayout.draw(g2, x, y + textLayout.getAscent()); y += textLayout.getDescent() + textLayout.getLeading() + textLayout.getAscent(); } g2.dispose(); } }
サンプルで気になる点
「あいう。」の後に自動的に改行されてしまう以下の関連記事で解決をはかる
https://blogs.yahoo.co.jp/dk521123/36833885.html