Vertically Centering Text in HTML Table Cell in Java Jlabel

Vertically centering text in HTML table cell in Java JLabel

Support for HTML in Swing Components is limited to 3.2, but valign="middle" should work.

Can't vertical center align text inside a JLabel

You can give an alignment suggestion to the layout manager by using:

label.setAlignmentY(JLabel.CENTER_ALIGNMENT);

If this doesn't help then post a proper SSCCE that demonstrates the problem.

HTML text in JLabel ignores alignment with text-align: center

Because support for HTML in Swing Components is limited, specify JLabel.CENTER for botlabel.

image

JLabel botlabel = new JLabel("", JLabel.CENTER);
botlabel.setText(
"<html>"
+ "<br clear=all />"
+ "<h3 style='color: #0033CC'>"
+ "Press Ok to continue or Cancel to exit.</h3>"
+ "</html>"
);

How to align text with image (img) in a table cell (td) in HTML 3.2

First. there's no style attribute in HTML 3.2. Your only hope is to nest tables, like this:

  <table border="1" >
<tr>
<td>
<table>
<tr>
<td>
<img src="https://www.w3schools.com/images/stickman.gif" align='middle' width="24" height="24">
</td>
<td>
sometext
</td>
</tr>
</table>
</td>
<td>something</td>
</tr>
</table>

Modify text alignment in a JTable cell

Use DefaultTableCellRenderer for that purposes, it has setHorizontalAlignment() method :

DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(){
@Override
public Component getTableCellRendererComponent(JTable arg0,Object arg1, boolean arg2, boolean arg3, int arg4, int arg5) {
Component tableCellRendererComponent = super.getTableCellRendererComponent(arg0, arg1, arg2, arg3, arg4, arg5);
int align = DefaultTableCellRenderer.CENTER;
if(condition){
align = DefaultTableCellRenderer.LEFT;
}
((DefaultTableCellRenderer)tableCellRendererComponent).setHorizontalAlignment(align);
return tableCellRendererComponent;
}
};
t.getColumnModel().getColumn(COLUMN).setCellRenderer(renderer);

COLUMN is target column, condition is condition for switching.

Center text in JTable

You must explicitly specify the column type in TableModel. If you are using DefaultTableModel, the default type returned by thegetColumnClass method is type Object, and because the DefaultTableCellRenderer class uses a JLabel to render the cells, the default alignment is left for this type.

You can set the type of each column or let java identify the type by changing the getColumnClass method:

@Override
public Class<?> getColumnClass(int column) {
System.out.println(getValueAt(0, column).getClass());
return getValueAt(0, column).getClass();
}

But if you want to define for more than one column with different types, the setDefaultRenderer method will not work because it defines only for the type passed by parameter and applies to the whole table. The ideal is to identify the column and define the alignment separately for it:

//change 0 for your column index
table.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);

See this applied on a example:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.time.LocalDate;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class JTableCreatingDemo extends JFrame {

public void createAndShowGUI() {

Object columnNames[] = { "String-Column", "Number-Column", "Date-Column", "Boolean-Column" };

Object rowData[][] = { { "some text", 89, LocalDate.now(), new Boolean(true) },
{ "other text", 546, LocalDate.now(), new Boolean(false) } };

JTable table = new JTable(rowData, columnNames) {

@Override
public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};

DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);

table.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
table.getColumnModel().getColumn(1).setCellRenderer(centerRenderer);

JScrollPane scrollPane = new JScrollPane(table);
this.add(scrollPane, BorderLayout.CENTER);
this.setSize(350, 150);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}

public static void main(String args[]) throws IllegalAccessException {

EventQueue.invokeLater(() -> new JTableCreatingDemo().createAndShowGUI());
}
}

See works:

Sample Image

How to align JLabel-JTextField pairs vertically

Is there any way to align the JLabels vertically to their right, so that the starts of JTextFields that follow would be aligned?

1.6+, GroupLayout. E.G. from the JavaDocs:

Sample Image

Use the label alignment that pushes the text to the RHS.


See also this answer for an MCVE.

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.

Vertical and Horizontal Allignment in JTextPane

You can just use plain HTML and the default TableCellRenderer, which is based on a JLabel to achieve this basic principles.

The following example uses a html table, which further aligns the text (broken of lines) to the center of the label. It uses the horizontalAlignment and verticalAlignment properties of the JLabel to get the contents aligned within the label.

It also does a little trickery with the row height ;)

Table with html

import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

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

String text
= "<html><div align=center>"
+ "And Caesar's spirit, raging for revenge,<br>"
+ "With Ate by his side come hot from hell,<br>"
+ "Shall in these confines with a monarch's voice<br>"
+ "Cry \"Havoc!\" and let slip the dogs of war,<br>"
+ "That this foul deed shall smell above the earth<br>"
+ "With carrion men, groaning for burial.";

DefaultTableModel model = new DefaultTableModel(0, 1);
model.addRow(new String[]{text});

JTable table = new JTable(model) {
@Override
public int getRowHeight(int row) {
Component comp = prepareRenderer(getCellRenderer(row, 0), row, 0);
return comp.getPreferredSize().height;
}
};
((JLabel)table.getDefaultRenderer(Object.class)).setHorizontalAlignment(JLabel.CENTER);
((JLabel)table.getDefaultRenderer(Object.class)).setVerticalAlignment(JLabel.CENTER);
table.setRowHeight(100);

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

}

Now, I pre-wrapped my text and applied it to the model. You could create a custom TableCellRenderer (using a DefaultTableCellRenderer) and post-wrap the text, depending on your needs



Related Topics



Leave a reply



Submit