Alignment date parts in a JTable column formatted in a propositional font

I need the date parts (dd, MMMM, yyyy) to be vertically aligned. I asked a question in Fixed month and day length in date format? to insert uppercase letters, but I found that this does not help in the case of a proportional font (the width of the letters is different). For example, with the font Lucida Fax:

enter image description here
Creating different labels for different date details is considered, but this is too much guidance. It is difficult to make the text wrapped if the column width is small ....
thanks

+1
source share
3 answers

Thank you for your responses. I found a solution for myself that uses JTextPane as a TableCellRenderer, then determines the values โ€‹โ€‹of tabstop and uses tabs in the format date. This is normal for my requirement, and also has other functions of a regular text field, such as word wrap ...

0
source

Note that for all Renderers (with the exception of the prepared Renderer) you must / be sure that you need to call this after changing any column / row in JTable

 TableColumnModel m = myTable.getColumnModel(); m.getColumn(5).setCellRenderer(new SubstDateRenderer()); 

here you can set BackGround, ForeGround for TableCell

 import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.table.DefaultTableCellRenderer; public class SubstDateRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 1L; private Date dateValue; private SimpleDateFormat sdfNewValue = new SimpleDateFormat("dd.MMMM.yyyy"); private String sdfNewValueString = ""; public SubstDateRenderer() {// formating TableCell super(); setHorizontalAlignment(javax.swing.SwingConstants.CENTER); } @Override public void setValue(Object value) { if ((value != null) && (value instanceof Date)) { dateValue = (Date) value; sdfNewValueString = sdfNewValue.format(dateValue); value = sdfNewValueString; } super.setValue(value); } } 
+6
source

As @mKorbel suggested, a suitable TableCellRenderer is the right choice, but you might have to override paintComponent() and render the text using the FontMetrics graphics context as shown.

If numerical months are acceptable, most proportionally spaced fonts give numeric icons of the same constant progression.

+1
source

All Articles