我在更改 JCalendar 中特定日期的颜色时遇到问题。在某些情况下,我可以正确更改日期面板的颜色,如下所示:
它正确突出显示了我从数据库中检索到的 10 月 5 日和 10 月 13 日。
但大多数情况下,突出显示的日期都不正确,如下所示:
它应该突出显示 2017 年 12 月 10 日,而不是 5 日。它似乎没有计算周日到周四的空组件,这就是它显示第五个的原因。
我尝试遵循解决方案 here但我不明白该怎么做。如果您能帮助我解决这个问题而不需要过多更改代码,我将不胜感激。
conn=sqlconn.ConnectDB();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH,1);
int offset = cal.get(Calendar.DAY_OF_WEEK);
int mon = calendar.getMonthChooser().getMonth() + 1;
int yr = calendar.getYearChooser().getYear();
JPanel jPanel = calendar.getDayChooser().getDayPanel();
Component component[] = jPanel.getComponents();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sql = "SELECT DAYOFMONTH(reserve_date) as day, MONTH(reserve_date) as month, YEAR(reserve_date) as year FROM reservation";
try
{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
text.setText("");
while(rs.next()){
int dayOfMonth = rs.getInt("day");
int month = rs.getInt("month");
int year = rs.getInt("year");
if(mon == month && yr == year){
component[dayOfMonth + offset].setBackground(Color.green);
}
}
pst.close();
rs.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
finally{
try{
rs.close();
pst.close();
}catch(Exception e){JOptionPane.showMessageDialog(null, e);}
}
最佳答案
我通过在该月的第一周找到不可见的组件解决了这个问题。
for(int i = 7; i < 14; i++){
if(component[i].isVisible() == false){
ctr++;
}
}
然后我将 ctr 的值添加到数组元素中:
if(mon == month && yr == year){
component[dayOfMonth + offset + ctr].setBackground(Color.green);
}
一切都按预期进行。我希望这对某人有帮助!
关于java - 如何更改 JCalendar 中特定日期的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47605957/