JTextPane and empty filler space

試著忘記壹切 提交于 2019-12-11 19:29:02

问题


I have a JTextPane in a JScrollPane, and I want to add an empty "filler space" at the top of the JTextPane, so that the first actual text row in the JTextPane appears at the bottom of the JViewport. I have a vague idea of having perhaps an empty paragraph in the beginning of the JTextPane and modify it's height everytime the JViewport is resized.. Anyone have ideas how to implement such a thing? Perhaps there is an easier way?


回答1:


You can use setMargin() to set margin space between component's border and its text. For example:

textPane.setMargin(new Insets(20, 0, 0, 0));

EDIT:

Consider the following very simple example the demonstrates use of setMargin():

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

public class MarginDemo {
    private static void createAndShowUI() {
        final JTextPane textPane = new JTextPane();
        final JScrollPane scrollPane = new JScrollPane(textPane);

        String text = "Lorem ipsum dolor sit amet, "
                + "consectetur adipiscing elit."
                + "Fusce nec sapien id diam consequat adipiscing.";
        textPane.setText(text);

        JFrame frame = new JFrame("MarginDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(scrollPane);

        frame.setSize(new Dimension(200, 200));
        frame.setVisible(true);

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                FontMetrics metrics = textPane.getFontMetrics(textPane
                        .getFont());
                textPane.setMargin(new Insets(scrollPane.getViewport()
                        .getHeight() - metrics.getHeight(), 0, 0, 0));
            }
        });
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

Here is the result:




回答2:


You can use the example http://java-sl.com/tip_center_vertically.html of custom vertical alignment in JEditorPane. To provide bottom alignment vertically you should change the line in the end to offset = (targetSpan - textBlockHeight);



来源:https://stackoverflow.com/questions/12575031/jtextpane-and-empty-filler-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!