How to center in JTable cell a value?
You need to customize the renderer. To center the first column you can do:
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.getColumnModel().getColumn(0).setCellRenderer( centerRenderer );
To center all columns with String data you can do:
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.setDefaultRenderer(String.class, centerRenderer);
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:
How to center cells in JTable
I've pared your example down to the essentials:
Your custom renderer,
r
, should condition the alignment, as well as size and color.Override model methods in the model, not in the view.
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
Use
deriveFont()
as required.See also this tutorial section on how renderers are selected.
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.*;
import java.awt.Color;
import javax.swing.JLabel;
class ver_his_sign extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ver_his_sign();
}
});
}
ver_his_sign() {
DefaultTableModel model = new DefaultTableModel(get_data(), get_header()) {
@Override
public boolean isCellEditable(int row, int col) {
switch (col) {
case 0:
return false;
case 1:
return false;
case 2:
return true;
default:
return false;
}
}
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Boolean.class;
default:
return Boolean.class;
}
}
};
DefaultTableCellRenderer r = new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object
value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
setForeground(Color.blue);
setHorizontalAlignment(JLabel.CENTER);
setFont(getFont().deriveFont(50f));
return this;
}
};
JTable table = new JTable(model);
table.setRowHeight(table.getRowHeight() + 50);
table.getColumnModel().getColumn(1).setCellRenderer(r);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.add(new JScrollPane(table));
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
Object[][] get_data() {
Object data[][] = new Object[][]{
{"Uno, 1", "\u4e00", true},
{"Uno, 1", "\u4e01", true},
{"Uno, 1", "\u4e02", true},
{"Uno, 1", "\u4e03", true},
{"Uno, 1", "\u4e04", true}
};
return data;
}
String[] get_header() {
String header[] = new String[]{"SIGNIFICADO", "KANJI", "Agregar"};
return header;
}
}
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.
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.
Align the values of the cells in JTable?
There is no need to create a custom class for this, just use the default renderer:
DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
table.getColumnModel().getColumn(???).setCellRenderer(rightRenderer);
Or a better approach is to actually store Double values in the table and then a proper numeric renderer will be used and number renderers are automatically right aligned. You can then customize the formatting of the number using a Table Format Renderer.
Related Topics
Why Can Array Constants Only Be Used in Initializers
Getting the Array Length of a 2D Array in Java
Can't Make Jackson and Lombok Work Together
Gson and Deserializing an Array of Objects with Arrays in It
List All Files in the Folder and Also Sub Folders
Possible to Use Two Java Classes with Same Name and Same Package
Should Methods in a Java Interface Be Declared with or Without a Public Access Modifier
Java: String Concat VS Stringbuilder - Optimised, So What Should I Do
How to Update Maven Repository in Eclipse
Reverse Java Graphics2D Scaled and Rotated Coordinates
Difference Between Paint() and Paintcomponent()
Why Does Java's Arrays.Sort Method Use Two Different Sorting Algorithms for Different Types
The Easiest Way to Transform Collection to Array
Preparedstatement Syntax Error