JEditorPane vertical aligment

2019-08-05 21:43发布

I try to apply center vertical aligment to text in JEditorPane. But text still is aligned to the top. Where did I mistake?

    JEditorPane editor = new JEditorPane();
    editor.setText("..large text block..");
    editor.setAlignmentY(JEditorPane.CENTER_ALIGNMENT); // DOESN'T WORK

    JFrame frame = new JFrame();
    frame.setSize(600, 400);
    frame.setVisible(true);
    frame.add(editor);

1条回答
We Are One
2楼-- · 2019-08-05 22:18

I find it is always best to do any special alignment by placing your components in a JPanel and then smartly choosing the correct layout manager for the panel.

JEditorPane editor = new JEditorPane();
editor.setBorder(BorderFactory.createLineBorder(Color.RED, 1));
editor.setText("..large text block..");
JScrollPane scrollPane = new JScrollPane(editor);

JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(layout);
panel.add(Box.createVerticalGlue());
panel.add(scrollPane);
panel.add(Box.createVerticalGlue());


JFrame frame = new JFrame();
frame.setSize(600, 400);
frame.add(panel);

frame.setVisible(true);

This really just centers the editor vertically, not the text within the editor which I think is what you are trying for. For more on BoxLayout see http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html

查看更多
登录 后发表回答