我正在尝试让 JTextPane 自动换行。我已经搜索过这个站点和整个 Internet,似乎 JTextPane 应该默认自动换行 - 人们遇到的大多数麻烦是禁用换行或让换行在 JScrollPane 中工作。我尝试了 TextPanes、ScrollPanes 和 JPanel 的各种组合,但都无济于事。下面是经过测试但仍然存在问题的最简单的可能代码(没有换行)。
public class Looseleaf extends JFrame{
public Looseleaf(){
this.setSize(200,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextPane txtPane = new JTextPane();
this.add(txtPane);
this.setVisible(true);
}
}
最佳答案
根据您的布局,JTextPane
可能会或可能不会被包裹,这取决于它感知到的可用大小。
相反,将 JTextPane
添加到 JScrollPane
中......
public class Looseleaf extends JFrame{
public Looseleaf(){
this.setSize(200,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextPane txtPane = new JTextPane();
this.add(new JScrollPane(txtPane)); // <-- Add the text pane to a scroll pane....
this.setVisible(true);
}
}
更新了额外的例子
试试这个。这对我有用。
public class TestTextPaneWrap {
public static void main(String[] args) {
new TestTextPaneWrap();
}
public TestTextPaneWrap() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
JTextPane editor = new JTextPane();
editor.setMinimumSize(new Dimension(0, 0));
add(new JScrollPane(editor));
}
}
}
关于java - JTextPane 不会换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14636186/