问题
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