Centering Text in a Jtextarea or Jtextpane - Horizontal Text Alignment

Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment

You need to use a JTextPane and use attributes. The following should center all the text:

StyledDocument doc = textPane.getStyledDocument();
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes(0, doc.getLength(), center, false);

Edit:

Vertical centering is not supported as far as I know. Here is some code you might find useful: Vertical Alignment of JTextPane

How to center align text in JTextArea?

To center text you should use a JTextPane not a JTextArea. Centering text is a big issue.

It is better to solve the background problem with the JTextPane.

When using the Nimbus LAF it looks like you need to provide a custom Painter to just paint the background as a solid color. Check out this answer by @mKorbel. You would need to change the property tag. Also in the FillPainter I changed:

g.setColor(color);
g.setColor(object.getBackground());

Center alignment of a word in JTextPane

You could use html for aligiment and colors and bold:

First you need to set the datatype to html like:

textarea.setContentType("tekst/html");

After that you can use html formatting to customize the look:

For example a big font and centered and bold you would do like this:

textarea.setText("<html><center><b><font size=30 color=rgb(1,1,1)>  Text   </font></b></center></html>");

This is what the different parts do:

  1. <html> and </html> : These allow you to use all other html tags
  2. <center> and </center> : These center the tekst
  3. <b> and </b> or <strong> and </strong> : These make the text bold
  4. <font size=xx color=rbg(r,g,b)> and </font> : These do the size and color for the color you can also use preset colors like: color=black

Also more HTML tag can be found here:
http://www.w3schools.com/html/default.asp

I hope this helps and good luck with your code :).

EDIT:

For multiple format apply multiple tag a tag is only active till it's colsed .
So I you do this:

<html><font color=red>HI</font><font color=green>HI</font></html>.

Now the first HI is red and the second one is green. So you can mix around tags as you like. So only everything between <center> and </center> is centered.

Smiliar here:

<html><b>HI</b>HI</html>

Only the first HI is bold the second one is normal.

I hope this expains it a bit more.

Java - Align JTextArea to the Right

Try with JEditorPane or JTextPane instead of JTextArea.

Please have a look at my another post JEditorPane vertical aligment for complete sample code.

For more info have a look at this thread Vertical Alignment of Text in JEditorPane

Sample code:

JTextPane output = new JTextPane();

SimpleAttributeSet attribs = new SimpleAttributeSet();
StyleConstants.setAlignment(attribs, StyleConstants.ALIGN_RIGHT);
output.setParagraphAttributes(attribs, true);


EDIT

You can try

JTextArea jTextArea = new JTextArea();
jTextArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

Read more about How to set the orientation of JTextArea from right to left

How to set different JTextArea text alignment per line?

Not with a JTextArea.

You need to use a JTextPane which supports different text and paragraph attributes. An example to CENTER the text:

JTextPane textPane = new JTextPane();
textPane.setText("Line1");
StyledDocument doc = textPane.getStyledDocument();

// Define the attribute you want for the line of text

SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);

// Add some text to the end of the Document

try
{
int length = doc.getLength();
doc.insertString(doc.getLength(), "\ntest", null);
doc.setParagraphAttributes(length+1, 1, center, false);
}
catch(Exception e) { System.out.println(e);}

Center text in TextArea

There is no alignment property for a TextArea. The alignment is determined by which LayoutManager you are using.

How to center text and a JComponent in a JTextPane vertically?

You can use this http://java-sl.com/tip_center_vertically.html

It should work with JComponents as well.

You can also override LabelView's getPreferredSpan() adding some space to the bottom.

Alternatively you can try to override RowView inner class in ParagraphView

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/javax/swing/text/ParagraphView.java#ParagraphView.Row

That points to inner class Row extends BoxView

You should replace it with own one. Try to override

public float getAlignment(int axis) 

to return CENTER (0.5). If this does not help override layoutMinorAxis(0 to return proper offsets (shifted).

Java JTextPane Vertical Alignment

Amazing what you can find with some googling.

So, the following example is based on Centering text vertically in JEditorPane. The example does leave a "blank" line at the bottom of the view, which I'm sure with a little effort, you can figure out how to remove it, but this will give you a jumping off point to start with.

Aligned to the bottom

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.BoxView;
import javax.swing.text.ComponentView;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.IconView;
import javax.swing.text.LabelView;
import javax.swing.text.ParagraphView;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private int lineCount = 0;

public TestPane() {
setLayout(new BorderLayout());
JTextPane tp = new JTextPane();
tp.setEditorKit(new MyEditorKit());
add(new JScrollPane(tp));

JButton btn = new JButton("Add");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Document doc = tp.getDocument();
int end = doc.getLength();
doc.insertString(end, (++lineCount) + " some more text\n", null);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
});

add(btn, BorderLayout.SOUTH);
}

}

class MyEditorKit extends StyledEditorKit {

public ViewFactory getViewFactory() {
return new StyledViewFactory();
}

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;
for (int i = 0; i < offsets.length; i++) {
offsets[i] += offset;
}

}
}
}

The magic happens in the layoutMajorAxis method

Center text alignment in JTable cell with TextAreaRenderer

You need to have a renderer that uses a JTextPane, not a JTextArea, and then set the Document's style attributes.

i.e.,

static class TextAreaRenderer extends JTextPane implements TableCellRenderer {

private final DefaultTableCellRenderer adaptee = new DefaultTableCellRenderer();
/** map from table to map of rows to map of column heights */
private final Map cellSizes = new HashMap();

public TextAreaRenderer() {
// !! setLineWrap(true);
// setWrapStyleWord(true);

StyledDocument doc = getStyledDocument();
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes(0, doc.getLength(), center, false);
}

For more, see (and up-vote) camickr's answer here.



Related Topics



Leave a reply



Submit