我使用JEditorPane作为编辑器在我的应用程序中编写注释。内容类型设置为"text/plain“。当我在其中写入文本时,当文本填满可用空间并继续键入时,文本不会向上移动以显示光标。所以我不知道我在哪里输入,我正在输入什么,因为它是可见的。
你能告诉我如何总是通过向上移动上面的文本来显示插入符号吗?
相反,如果我可以在输入时自动调整编辑器的大小,那会更好。JEditorPane在JPanel中,所以我也必须调整它的大小。有什么想法吗?
发布于 2008-11-07 14:14:27
您需要将编辑器放在JScrollPane中。ScrollPane将自动添加滚动条,并且不需要调整编辑器的大小。
发布于 2011-04-30 05:36:38
编辑以添加完整解决方案
您必须先添加一个JScrollPane。然后,如果您不希望滚动条可见,但希望文本区域自动滚动,请设置
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);在滚动窗格上。这将隐藏滚动条,但为您提供自动滚动。
这是如何实现滚动窗格的自动滚动,并自动调整到给定的最大大小。
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class SPTest extends JFrame {
private static final long serialVersionUID = 1L;
private JEditorPane editor;
private JScrollPane scrollPane;
private JPanel topPanel;
private JLabel labelTop;
public SPTest() {
super("Editor test");
initComponents();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void initComponents() {
editor = new JEditorPane("text/plain", null);
scrollPane = new JScrollPane(editor);
topPanel = new JPanel();
labelTop = new JLabel("main contents here");
topPanel.add(labelTop);
setSize(600, 400);
editor.setMinimumSize(new Dimension(100, 30));
editor.setPreferredSize(new Dimension(100, 60));
scrollPane.setPreferredSize(new Dimension(600, 60));
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
scrollPane.setMinimumSize(new Dimension(100, 30));
final int MAX_HEIGHT_RSZ = 120;
editor.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent e) {
int height = Math.min(editor.getPreferredSize().height, MAX_HEIGHT_RSZ);
Dimension preferredSize = scrollPane.getPreferredSize();
preferredSize.height = height;
scrollPane.setPreferredSize(preferredSize);
SPTest.this.validate();
}
});
setLayout(new BorderLayout());
add(topPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.SOUTH);
}
public static void main(String[] args) {
new SPTest();
}
}您可以调整大小,您可以使用此JScrollPane代替JPanel作为编辑器的容器。
https://stackoverflow.com/questions/271881
复制相似问题