自动滚动JEditorPane

时间:2008-11-07 12:10:51

标签: java text-editor jeditorpane

我使用JEditorPane作为编辑器在我的应用程序中编写注释。内容类型设置为“text / plain”。当我在其中写入文本并且文本填充可用空间并继续键入时,文本不会向上移动以显示光标。所以我不知道我在哪里打字以及我正在输入什么,因为它可见。

你能告诉我如何通过向上移动上面的文字来显示插入符吗?

相反,如果我可以在输入时自动调整编辑器的大小,那可能会更好。 JEdi​​torPane在JPanel中,所以我也必须调整它。任何想法?

2 个答案:

答案 0 :(得分:4)

您需要将编辑器放在JScrollPane中。 ScrollPane将自动添加滚动条,无需调整编辑器的大小。

答案 1 :(得分:1)

编辑添加完整解决方案

您必须先添加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作为编辑器的容器。