Code
class CalendarTableRenderer extends DefaultTableCellRenderer {
private final JPanel p = new JPanel();
@Override public Component getTableCellRendererComponent(
JTable table, Object value, boolean selected, boolean focused,
int row, int column) {
JLabel c = (JLabel) super.getTableCellRendererComponent(
table, value, selected, focused, row, column);
if (value instanceof LocalDate) {
LocalDate d = (LocalDate) value;
c.setText(Objects.toString(d.getDayOfMonth()));
c.setVerticalAlignment(SwingConstants.TOP);
c.setHorizontalAlignment(SwingConstants.LEFT);
updateCellWeekColor(d, c, c);
LocalDate nextWeekDay = d.plusDays(7);
boolean isLastRow = row == table.getModel().getRowCount() - 1;
if (isLastRow &&
YearMonth.from(nextWeekDay).equals(YearMonth.from(getCurrentLocalDate()))) {
JLabel sub = new JLabel(Objects.toString(nextWeekDay.getDayOfMonth()));
sub.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
sub.setOpaque(false);
sub.setVerticalAlignment(SwingConstants.BOTTOM);
sub.setHorizontalAlignment(SwingConstants.RIGHT);
p.removeAll();
p.setLayout(new BorderLayout());
p.add(sub, BorderLayout.SOUTH);
p.add(c, BorderLayout.NORTH);
p.setBorder(c.getBorder());
c.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
updateCellWeekColor(d, sub, p);
return new JLayer>>(p, new DiagonallySplitCellLayerUI());
}
}
return c;
}
// ...
}
class DiagonallySplitCellLayerUI extends LayerUI>JPanel> {
@Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (c instanceof JLayer) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(UIManager.getColor("Table.gridColor"));
g2.drawLine(c.getWidth(), 0, 0, c.getHeight());
g2.dispose();
}
}
}
Explanation
The sixth week of the month calendar is shown in diagonally split cells for the same day of the previous fifth week.
DefaultTableModel#getRowCount()
overrides to always return 5, causing the month calendar to display only 5 weeks- If this month is the seventh day after the target date in the cell renderer displaying the fifth week(row==4), add a
JLabel
for the target date in theJPanel
withBorderLayout
set asBorderLayout.NORTH
and anotherJLabel
withBorderLayout.SOUTH
to display the seventh day after the target date - Create a
JLayer
to display diagonal lines in thisJPanel
and use it as a cell renderer
No comments:
Post a Comment