1

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);

Aleks Ya
  • 859
  • 5
  • 15
  • 27
  • 1
    Please edit your question to include an [mcve](http://stackoverflow.com/help/mcve) that shows your approach in context. – trashgod May 12 '14 at 16:00
  • Are you looking for centering vertical aligment to text in `JEditorPane`? or you want to place the widget in the center only? – Braj May 13 '14 at 06:46
  • Braj, the solution to place the widget in the center is simpler. Your answer is works, but one is too complex. Thanks for spend time to answer! – Aleks Ya May 13 '14 at 06:56
  • Find it here [Centering text vertically in JEditorPane.](http://java-sl.com/tip_center_vertically.html). For more info have a look at this thread [Vertical Alignment of Text in JEditorPane](https://community.oracle.com/thread/1352946?start=0&tstart=0) – Braj Apr 18 '16 at 19:09

1 Answers1

2

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

cyber-monk
  • 5,470
  • 6
  • 33
  • 42