要包装这些行,JTextArea我们需要调用setLineWrap(boolean wrap)方法并传递一个true布尔值作为参数。setWrapStyleWord(boolean word)当我们将其设置为时,该方法会在单词边界处换行true。
package org.nhooo.example.swing; import javax.swing.*; import java.awt.*; public class TextAreaWrapDemo extends JPanel { public TextAreaWrapDemo() { initializeUI(); } private void initializeUI() { this.setLayout(new BorderLayout()); this.setPreferredSize(new Dimension(500, 200)); JTextArea textArea = new JTextArea(5, 40); String text = "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog. " + "The quick brown fox jumps over the lazy dog."; textArea.setText(text); textArea.setFont(new Font("Arial", Font.BOLD, 18)); // 如果JTextArea不合适,请换行 // 当前分配的JTextArea。 textArea.setLineWrap(true); textArea.setWrapStyleWord(true); JScrollPane scrollPane = new JScrollPane(textArea); this.add(scrollPane, BorderLayout.CENTER); } public static void showFrame() { JPanel panel = new TextAreaWrapDemo(); panel.setOpaque(true); JFrame frame = new JFrame("JTextArea Demo"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { TextAreaWrapDemo.showFrame(); } }); } }
上面的代码片段的输出是: