В JTextArea так сделать нельзя, но можно использовать JTextPane с аттрибутами
public static void main(String[] args) throws BadLocationException{
SimpleAttributeSet attrs;
StyledDocument doc;
JFrame infoWindow = new JFrame("Окно");
infoWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
infoWindow.setSize(200, 200);
JPanel grid = new JPanel();
GridLayout layout = new GridLayout(2, 2, 10, 10);
grid.setLayout(layout);
JTextPane area1 = new JTextPane();
area1.setEditorKit(new MyEditorKit());
attrs = new SimpleAttributeSet();
StyleConstants.setAlignment(attrs,StyleConstants.ALIGN_CENTER);
doc = (StyledDocument)area1.getDocument();
doc.insertString(0,"Текст первой ячейки",attrs);
doc.setParagraphAttributes(0,doc.getLength()-1,attrs,false);
grid.add(area1);
/* ... */
JTextPane area4 = new JTextPane();
area4.setEditorKit(new MyEditorKit());
attrs = new SimpleAttributeSet();
StyleConstants.setAlignment(attrs,StyleConstants.ALIGN_CENTER);
doc = (StyledDocument)area4.getDocument();
doc.insertString(0,"Текст четвёртой ячейки",attrs);
doc.setParagraphAttributes(0,doc.getLength()-1,attrs,false);
grid.add(area4);
infoWindow.setContentPane(grid);
infoWindow.setVisible(true);
}
class MyEditorKit extends StyledEditorKit {
public ViewFactory getViewFactory() {
return new StyledViewFactory();
}
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);
}
}
}
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;
int offset = 0;
for (int i = 0; i < spans.length; i++) {
textBlockHeight = spans[i];
}
offset = (targetSpan - textBlockHeight) / 2;
for (int i = 0; i < offsets.length; i++) {
offsets[i] += offset;
}
}
}
Ответ был взят с англоязычного StackOverflow