Insert external class(JTable) into Jpanel - java

I'm currently working on a project where I have to inser a Jtable(which is a calendar) into a Jpanel.
The problem is that i cant find a way to make it work in the panel(it doesn't even appear).
In part is because I dont have an object to fill the table and that's where I need help because I cant find a way to make it work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
class Calendar{
int month = java.util.Calendar.getInstance().get(java.util.Calendar.MONTH);
int year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);;
JLabel l = new JLabel("", JLabel.CENTER);
String day = "";
JTable d;
JButton[] button = new JButton[49];
public Calendar() {
String[] header = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
d = new JTable(header, 0);
DefaultTableModel calModel = new DefaultTableModel();
d.setBounds(20, 200, 500, 350);
for (int x = 0; x < button.length; x++) {
final int selection = x;
button[x] = new JButton();
button[x].setFocusPainted(false);
button[x].setBackground(Color.white);
if (x > 6)
button[x].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
day = button[selection].getActionCommand();
}
});
if (x < 7) {
button[x].setText(header[x]);
button[x].setForeground(Color.red);
}
d.add(button[x]);
}
JButton previous = new JButton("<< Previous");
previous.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
month--;
displayDate();
}
});
JButton next = new JButton("Next >>");
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
month++;
displayDate();
}
});
displayDate();
}
public void displayDate() {
for (int x = 7; x < button.length; x++)
button[x].setText("");
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
"MMMM yyyy");
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.set(year, month, 1);
int dayOfWeek = cal.get(java.util.Calendar.DAY_OF_WEEK);
int daysInMonth = cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
for (int x = 6 + dayOfWeek, day = 1; day <= daysInMonth; x++, day++)
button[x].setText("" + day);
l.setText(sdf.format(cal.getTime()));
}
}
Can someone please help me?

Related

How do I create a calendar application with a character next to a date

I have attached two codes here, one with Class name "CalenderApplication" which is a java swing application and the other is with Class name "JavaCalender".
What I want to do is to create a java swing application like the one with Class name "CalenderApplication" but to include a character next to date like I did with the code with Class name "JavaCalender"
If you run the code with Class "Java Calender" you will see it has a character next to the date but I want it to be a java swing Application.
Calender Application
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class CalenderApplication extends JFrame {
DefaultTableModel model;
Calendar cal = new GregorianCalendar();
JLabel label; SwingCalendar() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("Swing Calandar");
this.setSize(300,200);
this.setLayout(new BorderLayout());
this.setVisible(true);
label = new JLabel(); label.setHorizontalAlignment(SwingConstants.CENTER);
JButton b1 = new JButton("prev.");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cal.add(Calendar.MONTH, -1);
updateMonth();
}
});
JButton b2 = new JButton("next");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cal.add(Calendar.MONTH, +1);
updateMonth();
}
});
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout()); panel.add(b1,BorderLayout.WEST);
panel.add(label,BorderLayout.CENTER); panel.add(b2,BorderLayout.EAST);
String [] columns = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
model = new DefaultTableModel(null,columns);
JTable table = new JTable(model);
JScrollPane pane = new JScrollPane(table);
this.add(panel,BorderLayout.NORTH); this.add(pane,BorderLayout.CENTER);
this.updateMonth();
}
void updateMonth() {
cal.set(Calendar.DAY_OF_MONTH, 1);
String month = cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);
int year = cal.get(Calendar.YEAR);
label.setText(month + " " + year);
int startDay = cal.get(Calendar.DAY_OF_WEEK);
int numberOfDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int weeks = cal.getActualMaximum(Calendar.WEEK_OF_MONTH);
model.setRowCount(0);
model.setRowCount(weeks);
int i = startDay-1;
for(int day=1; day<=numberOfDays; day++) {
model.setValueAt(day, i/7 , i%7 );
i = i + 1;
}
}
public static void main(String[] arguments) {
JFrame.setDefaultLookAndFeelDecorated(true);
CalenderApplication sc = new CalenderApplication();
}
}
Java Calender
import java.util.Calendar;
import java.util.Scanner;
import java.util.GregorianCalendar;
import java.util.Locale;
public class JavaCalender {
static int theCount = 0;
public static void main(String[] args) {
int year = 2022;
int yearCounter = 2022;
Calendar cal = new GregorianCalendar();
int startDay;
int numberOfDays;
int monthCount = 1;
for (int i=5; i<42; i++){
cal.set(year, i, 1);
startDay = cal.get(Calendar.DAY_OF_WEEK);
numberOfDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
if (i == 24) {
yearCounter = yearCounter + 1;
}
if (i == 12) {
yearCounter = yearCounter + 1;
}
System.out.println();
System.out.print(cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US));
//System.out.println( " " + year);
System.out.println( " " + yearCounter);
printMonth(numberOfDays,startDay);
System.out.println();
}
}
private static void printMonth(int numberOfDays, int startDay) {
String[] alphabet = {"|A","|B","|C","|D","|E","|F","|G","|H","|I","|J","|K","|L","|N","|O","|P","|Q","|R","|S","|T","|U","|V",""};
int weekdayIndex = 0;
System.out.println("Sund Mond Tues Wedn Thur Frid Sata");
for (int day = 1; day < startDay; day++) {
System.out.print(" ");
weekdayIndex++;
}
for (int day = 1; day <= numberOfDays; day++) {
System.out.printf("%1$2d", day);
if (theCount < 21) {
System.out.print(alphabet[theCount]);
}
theCount++;
if (theCount == 21) {
theCount = 0;
}
weekdayIndex++;
if (weekdayIndex == 7) {
weekdayIndex = 0;
System.out.println();
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}
Any kind of help will be appreciated!

How can I make a calendar using JComboBox?

I want to make it adaptive, like if Feb got 29 days in 2000 but it will change into 28 when 2001.
I want to do it while using JComboBox
How can I make action calendar using a combo box?
JComboBox jcb,jcb1,jcb2;
db(){
JFrame jf = new JFrame("register");
jf.setLayout=(new FlowLayout());
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String aa1="0"+1+"-"+"0"+2+"-"+2000;
date = LocalDate.parse(aa1,dtf);
Integer day[] = new Integer[date.lengthOfMonth()];
for(int i=0;i<date.lengthOfMonth();i++) {
day[i]=i+1;
}
jcb = new JComboBox<>(day);
Integer month[] = new Integer[12];
for(int i=0;i<12;i++) {
month[i]=i+1;
}
jcb1 = new JComboBox<>(month);
Integer year[] = new Integer[80];
for(int i=0;i<80;i++) {
year[i]=i+1940;
}
jcb2 = new JComboBox<>(year);
jf.add(jcb);
jf.add(jcb1);
jf.add(jcb2);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setBounds(300,300,300,300);
jf.setVisible(true);
}
As #Andrew Thompson mentioned in comments, JComboBoxes for date selection is not a good idea. Take a look at Which one is the best Java datepicker.
However, if you still insist of using comboboxes, in order to achieve what you want, you will have to add an ActionListener to month/year combobox in order to re-fix the model (items) of days combobox.
Take a look at this example:
public class Test extends JFrame implements ActionListener {
private JComboBox<Integer> yearBox;
private JComboBox<Integer> monthBox;
private JComboBox<Integer> dayBox;
public Test() {
super("test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout());
yearBox = new JComboBox<>();
for (int i = 1940; i <= LocalDateTime.now().getYear(); i++) {
yearBox.addItem(i);
}
yearBox.addActionListener(this);
monthBox = new JComboBox<>();
for (int i = 1; i <= 12; i++) {
monthBox.addItem(i);
}
monthBox.addActionListener(this);
dayBox = new JComboBox<>();
add(new JLabel("year:"));
add(yearBox);
add(new JLabel("month:"));
add(monthBox);
add(new JLabel("day:"));
add(dayBox);
//Start with current year selected
yearBox.setSelectedIndex(yearBox.getItemCount() - 1);
setSize(400, 400);
setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent e) {
int year = (int) yearBox.getSelectedItem();
int month = (int) monthBox.getSelectedItem();
int daysInThisMonth = LocalDate.of(year, month, 1).lengthOfMonth();
int previousSelection = dayBox.getSelectedItem() != null ? (int) dayBox.getSelectedItem() : 1;
dayBox.removeAllItems();
for (int i = 1; i <= daysInThisMonth; i++) {
dayBox.addItem(i);
}
if (previousSelection >= dayBox.getItemCount())
//select last index of month
dayBox.setSelectedIndex(dayBox.getItemCount() - 1);
else
dayBox.setSelectedItem(previousSelection);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Test().setVisible(true));
}
}

Highlight just the current date in the month on datepicker in java

I have a datepicker program, which allows me to choose date. I want to highlight the current date in the current month and current year only. All others not to be highlighted. I have buttons on which I display the dates in a month. I am able to highlight the current date in the current month and current year, but the same cell is highlighted in all the months in all years. How can I avoid this?
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import java.awt.Component;
import java.awt.event.*;
import java.awt.*;
import java.awt.Toolkit;
import java.awt.Component.*;
import java.awt.Graphics;
import java.awt.Cursor.*;
import java.text.*;
public class DatePicker
{
int month = Calendar.getInstance().get(Calendar.MONTH);
int year = Calendar.getInstance().get(Calendar.YEAR);
JLabel l = new JLabel("", JLabel.CENTER);
String day = "";
JDialog d;
JButton[] button = new JButton[49];
public DatePicker(JFrame parent)
{
d = new JDialog();
d.setModal(true);
String[] header = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
JPanel p1 = new JPanel(new GridLayout(7, 7));
p1.setPreferredSize(new Dimension(430, 120));
for(int x = 0; x < button.length; x++)
{
final int selection = x;
button[x] = new JButton();
button[x].setFocusPainted(false);
button[x].setBackground(Color.white);
if(x > 6)
button[x].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
day = button[selection].getActionCommand();
d.dispose();
}
});
if(x < 7)
{
button[x].setText(header[x]);
button[x].setForeground(Color.red);
}
p1.add(button[x]);
}
JPanel p2 = new JPanel(new GridLayout(1, 3));
JButton previous = new JButton("<< Previous");
previous.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
month--;
displayDate();
}
});
p2.add(previous);
p2.add(l);
JButton next = new JButton("Next >>");
next.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
month++;
displayDate();
}
});
p2.add(next);
d.add(p1, BorderLayout.CENTER);
d.add(p2, BorderLayout.SOUTH);
d.pack();
d.setLocationRelativeTo(parent);
displayDate();
d.setVisible(true);
}
public void displayDate()
{
for(int x = 7; x < button.length; x++)
button[x].setText("");
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMMM yyyy");
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
Font font = new Font("Courier", Font.BOLD, 12);
Calendar curr = new GregorianCalendar();
int currdate = curr.get(Calendar.DAY_OF_MONTH);
int currmon = curr.get(Calendar.MONTH);
int curryear = curr.get(Calendar.YEAR);
int date = cal.get(Calendar.DAY_OF_MONTH);
int mon = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
int day1 = cal.get(Calendar.DAY_OF_WEEK);
int start = (7 - (date - day1) % 7) % 7;
int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("currdate : " + currdate);
System.out.println("currmon : " + currmon);
System.out.println("mon : " + mon);
System.out.println("curryear : " + curryear);
System.out.println("year : " + year);
for(int x = 6 + dayOfWeek, day = 1; day <= daysInMonth; x++, day++)
{
button[x].setText("" + day);
System.out.println("x : " + x);
System.out.println("day : " + day);
if(currdate == (x - 12) && currmon == mon && curryear == year)
{
// button[x].setFont(font);
button[day].setBackground(Color.GREEN);
}
else
button[x].setBackground(Color.white);
}
// for(int i = 1; i <= days; i++)
l.setText(sdf.format(cal.getTime()));
d.setTitle("Date Picker");
}
public String setPickedDate()
{
if(day.equals(""))
return day;
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MM-dd-yyyy");
Calendar cal = Calendar.getInstance();
cal.set(year, month, Integer.parseInt(day));
return sdf.format(cal.getTime());
}
}
update my post
You are missing else block:
if(currdate == (x - 12) && currmon == mon && curryear == year) {
button[x].setFont(font);
button[x].setBackground(Color.GREEN);
} else {
button[x].setFont(?); //<-- replace ? with desired font
button[x].setBackground(?); //<-- replace ? with desired color
}

Ideas on creating events in a java swin calendar

I am looking for ideas and suggestions on how to go about adding events that can be created and edited to my swing app.
I would like the app to stay fairly basic, but know that I will/should link it to a database to hold the events.
Here is the current code that
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class CalendarProgram {
static JLabel lblMonth, lblYear;
static JButton btnPrev, btnNext;
static JTable tblCalendar;
static JComboBox cmbYear;
static JFrame frmMain;
static Container pane;
static DefaultTableModel mtblCalendar; // Table model
static JScrollPane stblCalendar; // The scrollpane
static JPanel pnlCalendar;
static int realYear, realMonth, realDay, currentYear, currentMonth;
public static void main(String args[]) {
// Look and feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (UnsupportedLookAndFeelException e) {
}
// Prepare frame
frmMain = new JFrame("Resource System"); // Create frame
frmMain.setSize(360, 375); // Set size to 400x400 pixels
pane = frmMain.getContentPane(); // Get content pane
pane.setLayout(null); // Apply null layout
frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close when X
// is clicked
// Create controls
lblMonth = new JLabel("January");
lblYear = new JLabel("Change year:");
cmbYear = new JComboBox();
btnPrev = new JButton("<<");
btnNext = new JButton(">>");
mtblCalendar = new DefaultTableModel() {
public boolean isCellEditable(int rowIndex, int mColIndex) {
return true;
}
};
tblCalendar = new JTable(mtblCalendar);
stblCalendar = new JScrollPane(tblCalendar);
pnlCalendar = new JPanel(null);
// Set border
pnlCalendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
// Register action listeners
btnPrev.addActionListener(new btnPrev_Action());
btnNext.addActionListener(new btnNext_Action());
cmbYear.addActionListener(new cmbYear_Action());
// Add controls to pane
pane.add(pnlCalendar);
pnlCalendar.add(lblMonth);
pnlCalendar.add(lblYear);
pnlCalendar.add(cmbYear);
pnlCalendar.add(btnPrev);
pnlCalendar.add(btnNext);
pnlCalendar.add(stblCalendar);
// Set bounds
pnlCalendar.setBounds(0, 0, 320, 335);
lblMonth.setBounds(160 - lblMonth.getPreferredSize().width / 2, 25,
100, 25);
lblYear.setBounds(10, 305, 80, 20);
cmbYear.setBounds(230, 305, 80, 20);
btnPrev.setBounds(10, 25, 50, 25);
btnNext.setBounds(260, 25, 50, 25);
stblCalendar.setBounds(10, 50, 300, 250);
// Make frame visible
frmMain.setResizable(false);
frmMain.setVisible(true);
// Get real month/year
GregorianCalendar cal = new GregorianCalendar(); // Create calendar
realDay = cal.get(GregorianCalendar.DAY_OF_MONTH); // Get day
realMonth = cal.get(GregorianCalendar.MONTH); // Get month
realYear = cal.get(GregorianCalendar.YEAR); // Get year
currentMonth = realMonth; // Match month and year
currentYear = realYear;
// Add headers
String[] headers = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // All
// headers
for (int i = 0; i < 7; i++) {
mtblCalendar.addColumn(headers[i]);
}
tblCalendar.getParent().setBackground(tblCalendar.getBackground()); // Set
// background
// No resize/reorder
tblCalendar.getTableHeader().setResizingAllowed(false);
tblCalendar.getTableHeader().setReorderingAllowed(false);
// Single cell selection
tblCalendar.setColumnSelectionAllowed(true);
tblCalendar.setRowSelectionAllowed(true);
tblCalendar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Set row/column count
tblCalendar.setRowHeight(38);
mtblCalendar.setColumnCount(7);
mtblCalendar.setRowCount(6);
// Populate table
for (int i = realYear - 100; i <= realYear + 100; i++) {
cmbYear.addItem(String.valueOf(i));
}
// Refresh calendar
refreshCalendar(realMonth, realYear); // Refresh calendar
}
public static void refreshCalendar(int month, int year) {
// Variables
String[] months = { "January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November",
"December" };
int nod, som; // Number Of Days, Start Of Month
// Allow/disallow buttons
btnPrev.setEnabled(true);
btnNext.setEnabled(true);
if (month == 0 && year <= realYear - 10) {
btnPrev.setEnabled(false);
} // Too early
if (month == 11 && year >= realYear + 100) {
btnNext.setEnabled(false);
} // Too late
lblMonth.setText(months[month]); // Refresh the month label (at the top)
lblMonth.setBounds(160 - lblMonth.getPreferredSize().width / 2, 25,
180, 25); // Re-align label with calendar
cmbYear.setSelectedItem(String.valueOf(year)); // Select the correct
// year in the combo box
// Clear table
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
mtblCalendar.setValueAt(null, i, j);
}
}
// Get first day of month and number of days
GregorianCalendar cal = new GregorianCalendar(year, month, 1);
nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
som = cal.get(GregorianCalendar.DAY_OF_WEEK);
// Draw calendar
for (int i = 1; i <= nod; i++) {
int row = new Integer((i + som - 2) / 7);
int column = (i + som - 2) % 7;
mtblCalendar.setValueAt(i, row, column);
}
// Apply renderers
tblCalendar.setDefaultRenderer(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()) == realDay
&& currentMonth == realMonth && currentYear == realYear) { // Today
setBackground(new Color(220, 220, 255));
}
}
setBorder(null);
setForeground(Color.black);
return this;
}
}
static class btnPrev_Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (currentMonth == 0) { // Back one year
currentMonth = 11;
currentYear -= 1;
} else { // Back one month
currentMonth -= 1;
}
refreshCalendar(currentMonth, currentYear);
}
}
static class btnNext_Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (currentMonth == 11) { // Foward one year
currentMonth = 0;
currentYear += 1;
} else { // Foward one month
currentMonth += 1;
}
refreshCalendar(currentMonth, currentYear);
}
}
static class cmbYear_Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (cmbYear.getSelectedItem() != null) {
String b = cmbYear.getSelectedItem().toString();
currentYear = Integer.parseInt(b);
refreshCalendar(currentMonth, currentYear);
}
}
}
}
Any ideas would help greatly. Basically the idea here is to have a standalone calendar that one can add events to and change events already listed. And I understand that swing isn't the most piratical solution.

View Schedule on Calendar

I'm working on an application that has the user open a calendar view, and schedule different tasks (similar to what you can do in outlook). I have the Calendar view, but don't know where to go from here. This is borrowed code btw. I've updated some of it to meet some of my intent.
I'm thinking of using mysql as the database to store the task dates, but how do I populate my calendar with the dates from the database? I've attached the borrowed code. Any suggestions are welcome...
//Import packages
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class ViewCalendar {
JLabel lblMonth, lblYear;
JButton btnPrev, btnNext;
JTable tblCalendar;
JComboBox cmbYear;
JFrame frmMain;
Container pane;
DefaultTableModel mtblCalendar; //Table model
JScrollPane stblCalendar; //The scrollpane
JPanel pnlCalendar;
int realYear, realMonth, realDay, currentYear, currentMonth;
public void viewCalendar() {
System.out.println("*Calendar open*");
//Look and feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (UnsupportedLookAndFeelException e) {
}
//Prepare frame
frmMain = new JFrame("Scheduled Repairs"); //Create frame
frmMain.setSize(330, 375); //Set size to 400x400 pixels
pane = frmMain.getContentPane(); //Get content pane
pane.setLayout(null); //Apply null layout
frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Close when X is clicked
//Create controls
lblMonth = new JLabel("January");
lblYear = new JLabel("Change year:");
cmbYear = new JComboBox();
btnPrev = new JButton("<<");
btnNext = new JButton(">>");
mtblCalendar = new DefaultTableModel() {
public boolean isCellEditable(int rowIndex, int mColIndex) {
return false;
}
};
tblCalendar = new JTable(mtblCalendar);
stblCalendar = new JScrollPane(tblCalendar);
pnlCalendar = new JPanel(null);
//Set border
pnlCalendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
//Register action listeners
btnPrev.addActionListener(new btnPrev_Action());
btnNext.addActionListener(new btnNext_Action());
cmbYear.addActionListener(new cmbYear_Action());
//Add controls to pane
pane.add(pnlCalendar);
pnlCalendar.add(lblMonth);
pnlCalendar.add(lblYear);
pnlCalendar.add(cmbYear);
pnlCalendar.add(btnPrev);
pnlCalendar.add(btnNext);
pnlCalendar.add(stblCalendar);
//Set bounds
pnlCalendar.setBounds(0, 0, 320, 335);
lblMonth.setBounds(160 - lblMonth.getPreferredSize().width / 2, 25, 100, 25);
lblYear.setBounds(10, 305, 80, 20);
cmbYear.setBounds(230, 305, 80, 20);
btnPrev.setBounds(10, 25, 50, 25);
btnNext.setBounds(260, 25, 50, 25);
stblCalendar.setBounds(10, 50, 300, 250);
//Make frame visible
frmMain.setResizable(true);
frmMain.setVisible(true);
//Get real month/year
GregorianCalendar cal = new GregorianCalendar(); //Create calendar
realDay = cal.get(GregorianCalendar.DAY_OF_MONTH); //Get day
realMonth = cal.get(GregorianCalendar.MONTH); //Get month
realYear = cal.get(GregorianCalendar.YEAR); //Get year
currentMonth = realMonth; //Match month and year
currentYear = realYear;
//Add headers
String[] headers = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; //All headers
for (int i = 0; i < 7; i++) {
mtblCalendar.addColumn(headers[i]);
}
tblCalendar.getParent().setBackground(tblCalendar.getBackground()); //Set background
//No resize/reorder
tblCalendar.getTableHeader().setResizingAllowed(false);
tblCalendar.getTableHeader().setReorderingAllowed(false);
//Single cell selection
tblCalendar.setColumnSelectionAllowed(true);
tblCalendar.setRowSelectionAllowed(true);
tblCalendar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Set row/column count
tblCalendar.setRowHeight(38);
mtblCalendar.setColumnCount(7);
mtblCalendar.setRowCount(6);
//Populate table
for (int i = realYear - 100; i <= realYear + 100; i++) {
cmbYear.addItem(String.valueOf(i));
}
//Refresh calendar
refreshCalendar(realMonth, realYear); //Refresh calendar
}
public void refreshCalendar(int month, int year) {
//Variables
String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
int nod, som; //Number Of Days, Start Of Month
//Allow/disallow buttons
btnPrev.setEnabled(true);
btnNext.setEnabled(true);
if (month == 0 && year <= realYear - 10) {
btnPrev.setEnabled(false);
} //Too early
if (month == 11 && year >= realYear + 100) {
btnNext.setEnabled(false);
} //Too late
lblMonth.setText(months[month]); //Refresh the month label (at the top)
lblMonth.setBounds(160 - lblMonth.getPreferredSize().width / 2, 25, 180, 25); //Re-align label with calendar
cmbYear.setSelectedItem(String.valueOf(year)); //Select the correct year in the combo box
//Clear table
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
mtblCalendar.setValueAt(null, i, j);
}
}
//Get first day of month and number of days
GregorianCalendar cal = new GregorianCalendar(year, month, 1);
nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
som = cal.get(GregorianCalendar.DAY_OF_WEEK);
//Draw calendar
for (int i = 1; i <= nod; i++) {
int row = new Integer((i + som - 2) / 7);
int column = (i + som - 2) % 7;
mtblCalendar.setValueAt(i, row, column);
}
//Apply renderers
tblCalendar.setDefaultRenderer(tblCalendar.getColumnClass(0), new tblCalendarRenderer());
}
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()) == realDay && currentMonth == realMonth && currentYear == realYear) { //Today
setBackground(new Color(220, 220, 255));
}
}
setBorder(null);
setForeground(Color.black);
return this;
}
}
class btnPrev_Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (currentMonth == 0) { //Back one year
currentMonth = 11;
currentYear -= 1;
} else { //Back one month
currentMonth -= 1;
}
refreshCalendar(currentMonth, currentYear);
}
}
class btnNext_Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (currentMonth == 11) { //Foward one year
currentMonth = 0;
currentYear += 1;
} else { //Foward one month
currentMonth += 1;
}
refreshCalendar(currentMonth, currentYear);
}
}
class cmbYear_Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (cmbYear.getSelectedItem() != null) {
String b = cmbYear.getSelectedItem().toString();
currentYear = Integer.parseInt(b);
refreshCalendar(currentMonth, currentYear);
}
}
}
}

Categories