1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class CenterTextEdit {
public CenterTextEdit() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
JTextPane edit = new JTextPane();
frame.getContentPane().add(edit, BorderLayout.CENTER);
try {
edit.setEditorKit(new CenterEditorKit());
SimpleAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.setAlignment(attrs, StyleConstants.ALIGN_CENTER);
StyledDocument doc = (StyledDocument) edit.getDocument();
doc.insertString(0, "Tapez\nvotre\ntexte\nici", attrs);
doc.setParagraphAttributes(0, doc.getLength() - 1, attrs, false);
edit.setSelectionStart(0);
edit.setSelectionEnd(edit.getText().length() - 1);
} catch (Exception ex) {
ex.printStackTrace();
}
frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
frame.setLocation(0, 0);
frame.setVisible(true);
}
public static void main(String[] args) throws Exception {
new CenterTextEdit();
}
private static class CenterEditorKit extends StyledEditorKit {
private static final long serialVersionUID = 1L;
public ViewFactory getViewFactory() {
return new StyledViewFactory();
}
}
private static class StyledViewFactory implements ViewFactory {
public View create(Element elem) {
String kind = elem.getName();
if (kind != null) {
if (kind.equals(AbstractDocument.ContentElementName)) {
return new LabelView(elem);
} else if (kind.equals(AbstractDocument.ParagraphElementName)) {
return new ParagraphView(elem);
} else if (kind.equals(AbstractDocument.SectionElementName)) {
return new CenteredBoxView(elem, View.Y_AXIS);
} else if (kind.equals(StyleConstants.ComponentElementName)) {
return new ComponentView(elem);
} else if (kind.equals(StyleConstants.IconElementName)) {
return new IconView(elem);
}
}
return new LabelView(elem);
}
}
private static class CenteredBoxView extends BoxView {
public CenteredBoxView(Element elem, int axis) {
super(elem, axis);
}
protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets,
int[] spans) {
super.layoutMajorAxis(targetSpan, axis, offsets, spans);
int textBlockHeight = 0;
for (int i = 0; i < spans.length; i++) {
textBlockHeight += spans[i];
}
int offset = (targetSpan - textBlockHeight) / 2;
for (int i = 0; i < offsets.length; i++) {
offsets[i] += offset;
}
}
}
} |
Partager