【问题标题】:How to make a new line in JTextPane dynamically?如何在 JTextPane 中动态创建新行?
【发布时间】:2015-12-02 08:22:30
【问题描述】:

当用户输入内容并到达屏幕/框架的末尾时,如何让 JTextPane 创建一个新行?这是我所拥有的:

JFrame frame = new JFrame("Frame");

JTextPane pane= new JTextPane ();
JPanel panel = new JPanel(new BorderLayout());
panel.add(pane);
JScrollPane scrollBar = new JScrollPane(panel);
        scrollBar.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

frame.add(scrollBar, BorderLayout.CENTER);

请注意,这不适用于 JTextPane 中的某些固定字符串,这意味着窗格默认为空白,文本由用户输入添加。当用户正在输入内容并且单词已到达屏幕末尾时,文本应在新行上继续,而不是在同一行继续...

【问题讨论】:

  • 您可以使用JTextArea 并致电setWrapStyleWord(true);
  • 我必须使用 JTextPane
  • 如果我记得,您可以使用BorderLayoutJTextPane 添加到JPanel,然后将JPanel 添加到JScrollPane
  • 看看这个解决方案:how-to-make-jtextpane-line-break
  • @MadProgrammer 感谢您的回复,我不确定我是否了解在哪里添加 JTextPane。我是否将它添加到 JPanel 或 BorderLayout?我已经更新了上面的代码

标签: java swing newline jtextpane


【解决方案1】:

我不明白为什么人们一直在问这个问题。 JTextPane 通常会换行:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame mainFrame = new JFrame("test");
            mainFrame.setSize(100, 100);
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            Container pane = mainFrame.getContentPane();
            JTextPane jtp = new JTextPane();
            JScrollPane scroll = new JScrollPane(jtp);
            pane.add(scroll);

            mainFrame.setVisible(true);
        }
    });
}

【讨论】:

    猜你喜欢
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多