Alignment date parts in JTable column formatted in propotional font

前端 未结 3 1344
我寻月下人不归
我寻月下人不归 2020-12-22 02:29

I need to make the date parts (dd, MMMM, yyyy) to be vertically aligned. I asked a question at Fixed length of month and day in date format? to insert padding letters, but I

相关标签:
3条回答
  • 2020-12-22 03:01

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

    If numeric months are acceptable, most proportionally-spaced fonts give digit glyphs the same constant advance.

    0 讨论(0)
  • 2020-12-22 03:01

    Thanks for your answers. I found for myself a solution that uses JTextPane as a TableCellRenderer, then define the tabstop values, and use tabs in formatting date. It seems ok for my requirement and also have other features of normal text field such as word wrapping...

    0 讨论(0)
  • 2020-12-22 03:27

    note as for all Renderers (excluding preparedRenderer)you have to/be sure that you have to call that after any column/row changes 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题