1

我有一个长字符串,不适合我放置的 JPanel。文本比 JPanel 宽度记录器。我不能将“\n”放到字符串中来破坏字符串,事实上我无法控制字符串的长度和内容。它是用户输入的字符串。我想要做的是当我将文本放在 JPanel 上时,我希望任何不适合 JPanel 的文本流入下一行。

这有点难以解释。如果您需要更多详细信息,请告诉我。

谢谢

4

3 回答 3

2

从快速的谷歌搜索中,我读到,从逻辑上讲,所有操作系统都有不同的换行符,并且由于 Java 与平台无关,您需要首先使用以下方法找到相对分隔符:

lineSeparator = (String) java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));

然后将您的字符串与lineSeparator

例如:

JLabel label = new JLabel("Hello"+lineSeparator+"world");

这种方法未经我尝试和测试,只是我的研究结果。

至于处理溢出文本,我个人的经验是在超出框架之前找到字符的最大长度,然后添加lineSeparator

于 2012-06-09T19:44:38.517 回答
2

将您的文本放在<html></html>标签中就可以了。长行将自动换行。

JLabel label = new JLabel("<html>"+ reallyLongString + "</html>");  
label.setPreferredSize(new Dimension(1, 1); 
于 2012-06-09T20:04:12.110 回答
1

尝试改用 JTextPane,它会为您处理自动换行。

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;

public class Wordwrap extends JFrame {

    public Wordwrap() {
        String s = "I have a long string which doesn't fit to the JPanel i am putting it. text is logger than the JPanel width. I can not put \n to the string to break the string, in fact i don't have the control over the length and content of the string. It user inputted string. What i want to do is when i am putting the text on JPanel i want any text that doesn't fit in to the JPanel to flow in to the next Line.";

        JTextPane textPanel = new JTextPane();
        textPanel.setText(s);
        textPanel.setPreferredSize(new Dimension(500, 100));

        JPanel p = new JPanel();
        p.add(textPanel);
        getContentPane().add(p);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);
        pack();
    }

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                new Wordwrap();
            }
        });
    }
}
于 2012-06-09T20:19:49.023 回答