Im trying to set specific dates in my JCalendar in a different color depending on if there is something planned for that date in my database, the date is stored as"yyyy-MM-dd" in the database, I've seen similar posts here on stackOverflow but I just cant get it to work.
I'm not sure how "component[day].setBackground(Color.green)" works like and how I can set it to only dates that has something planned for them in the database
public void kalender() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
int offset = cal.get(Calendar.DAY_OF_WEEK);
int mon = kalender.getMonthChooser().getMonth() + 1;
int yr = kalender.getYearChooser().getYear();
JPanel jPanel = kalender.getDayChooser().getDayPanel();
Component component[] = jPanel.getComponents();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String kalenderdatum = format.format(kalender.getDate());
System.out.println(kalenderdatum);
String sql2 = "SELECT DATUM FROM MOTE";
try {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql2);
while (rs.next()) {
String datumet = rs.getString("DATUM");
String aret = datumet.substring(0, 4);
int year = Integer.parseInt(aret);
String manaden = datumet.substring(5,7);
int month = Integer.parseInt(manaden);
String dagen = datumet.substring(8,10);
int day = Integer.parseInt(dagen);
if(yr == year && mon == month)
{
component[day].setBackground(Color.green);
}
}
One solution that uses the JCalendar API is to create your own instance of
IDateEvaluatorand checks if a date has anything "special" about it.1. Converting
First I suggest getting your dates (
yyyy-MM-dd) into a list and convert them toDateobjects. For example:With the help of the following function:
2. Create your SpecialDateEvaluator
Then you need to create your own date evaluator that takes in the
Dateobjects that are going to be handled differently. A simple example would be the following:3. Utilize the date evaluator
To utilize the evaluator you need to add it to the
JDayChooser, taking in the list ofDateobjects and then setting theCalendaragain to refresh the view. For example:To see a full example of this (with a main method), see this example gist.