All Downloads are FREE. Search and download functionalities are using the official Maven repository.

se.wfh.libs.common.gui.widgets.datepicker.CalendarTableModel Maven / Gradle / Ivy

package se.wfh.libs.common.gui.widgets.datepicker;

import java.awt.ComponentOrientation;
import java.text.DateFormatSymbols;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Locale;

import javax.swing.table.AbstractTableModel;

public class CalendarTableModel extends AbstractTableModel {
	private static final long serialVersionUID = 1L;

	private boolean isRightToLeft;
	private int firstDayOfWeek = 1;
	private int offset = 0;
	private LocalDate baseDate;
	private LocalDate selectedDate;

	public CalendarTableModel(LocalDate value) {
		setSelectedDate(value);

	}

	@Override
	public int getRowCount() {
		return 6;
	}

	@Override
	public int getColumnCount() {
		return 7;
	}

	private int getRtLColIndex(int columnIndex) {
		if (isRightToLeft) {
			return (6 - columnIndex);
		} else {
			return columnIndex;
		}
	}

	@Override
	public LocalDate getValueAt(int rowIndex, int columnIndex) {
		return baseDate.plusDays(getRtLColIndex(columnIndex) + rowIndex * 7
				+ offset);
	}

	@Override
	public Class getColumnClass(int columnIndex) {
		return LocalDate.class;
	}

	@Override
	public String getColumnName(int column) {
		DateFormatSymbols df = new DateFormatSymbols();

		return df.getShortWeekdays()[1 + (getRtLColIndex(column) + firstDayOfWeek) % 7];
	}

	public final void setSelectedDate(LocalDate date) {
		this.selectedDate = date;

		dateChanged();
	}

	private void dateChanged() {
		this.baseDate = selectedDate.withDayOfMonth(1);

		int weekdayFirstOfMonth = baseDate.getDayOfWeek().getValue();
		firstDayOfWeek = WeekFields.of(Locale.getDefault()).getFirstDayOfWeek()
				.getValue();

		// offset depends on current locale and handles the drift to the left /
		// right on the calendar. offset = amount of days till first field in
		// calendar
		offset = firstDayOfWeek - weekdayFirstOfMonth;

		if (offset >= 0) {
			offset -= 7;
		}

		isRightToLeft = ComponentOrientation.getOrientation(Locale.getDefault()) == ComponentOrientation.RIGHT_TO_LEFT;
	}

	public final LocalDate getSelectedDate() {
		return selectedDate;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy