问题
I have a JTable with 9 columns, and I know I can create custom cell renderers for each column, at the expense of about 8 lines of code per renderer.
But all I really need is to display text placed in all cells as right-justified. Is there any way to set this alignment for the whole table?
Thanks in advance for any suggestions.
John Doner
回答1:
Try this:
for (int i = 0; i < myTable.getModel().getRowCount(); i++) {
for (int j = 0; j < myTable.getModel().getColumnCount(); j++) {
DefaultTableCellRenderer renderer =
(DefaultTableCellRenderer)myTable.getCellRenderer(i, j);
renderer.setHorizontalAlignment(JTextField.RIGHT);
} // End for(j)
} // End for(i)
Since each cell already has a renderer, this grabs each cell's existing TableCellRenderer
from the TableModel
and uses the built-in method setHorizontalAlignment(int)
inherited from JLabel
.
Hope that's what you're looking for!
来源:https://stackoverflow.com/questions/4631985/java-jtable-any-default-cell-alignment-technique