我正在制作一个GUI简单的日历程序。我正在使用DefaultTableModel和DefaultTableCellRenderer显示日历的月视图。我的日历设置为突出显示今天的日期。我希望它也能突出显示用户点击其他颜色的日期。我已经将鼠标监听器连接到每个单元格,并且能够检索那些单元格的日期,但我不知道如何更新tblCalendarRenderer(至少不正确)。我得到它开始突出显示点击相同颜色的一些日期,但它只像其他每次点击一样,并突出显示我点击的上一个日期,而不是当前日期。它也会开始突出显示多个,然后在某个时刻刷新。有人可以告诉我如何正确地完成它吗?
以下是一些代码:
public static void monthView(final int month, int year){
//print month calendar
int nod, som; //Number Of Days, Start Of Month
//Clear table
for (int i = 0; i < 6; i++){
for (int j = 0; j < 7; j++){
MyCalendarTester.mtblCalendar.setValueAt(null, i, j);
}
}
if(initial){ // to make sure that the mouse listeners are only created once.
initial = false;
MyCalendarTester.tblCalendar.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent event) {
// TODO Auto-generated method stub
int rowEvent = MyCalendarTester.tblCalendar.getSelectedRow();
int colEvent = MyCalendarTester.tblCalendar.getSelectedColumn();
System.out.print(arrayOfMonths[month].toString() + " ");
MyCalendarTester.realDay = Integer.parseInt(MyCalendarTester.tblCalendar.getValueAt(MyCalendarTester.tblCalendar.convertRowIndexToModel(rowEvent),
MyCalendarTester.tblCalendar.convertColumnIndexToModel(colEvent)).toString());
System.out.print(MyCalendarTester.tblCalendar.getValueAt(MyCalendarTester.tblCalendar.convertRowIndexToModel(rowEvent),
MyCalendarTester.tblCalendar.convertColumnIndexToModel(colEvent)) + " ");
System.out.println(MyCalendarTester.currentYear);
//Apply renderers
MyCalendarTester.tblCalendar.setDefaultRenderer(MyCalendarTester.tblCalendar.getColumnClass(0), new tblCalendarRenderer());
MyCalendarTester.tblCalendar.getCellRenderer(MyCalendarTester.tblCalendar.convertRowIndexToModel(rowEvent), MyCalendarTester.tblCalendar.convertColumnIndexToModel(colEvent));
}
});
//Draw calendar
for (int i=1; i<=nod; i++){
int row = new Integer((i+som-2)/7);
int column = (i+som-2)%7;
MyCalendarTester.mtblCalendar.setValueAt(i, row, column);
}
//Apply renderers
MyCalendarTester.tblCalendar.setDefaultRenderer(MyCalendarTester.tblCalendar.getColumnClass(0), new tblCalendarRenderer());
}
static class tblCalendarRenderer extends DefaultTableCellRenderer{
public Component getTableCellRendererComponent (JTable table, Object value, boolean selected, boolean focused, int row, int column){
super.getTableCellRendererComponent(table, value, selected, focused, row, column);
if (column == 0 || column == 6){ //Week-end
setBackground(new Color(255, 220, 220));
}
else{ //Week
setBackground(new Color(255, 255, 255));
}
if (value != null){
if (Integer.parseInt(value.toString()) == MyCalendarTester.realDay &&
MyCalendarTester.currentMonth == MyCalendarTester.realMonth && MyCalendarTester.currentYear == MyCalendarTester.realYear){ //Today
setBackground(new Color(220, 220, 255));
}
}
setBorder(null);
setForeground(Color.black);
return this;
}
}