Jcalender in Swing Java - java

// I am creating customize jcalender in swing
//I am facing problem regarding dates set
//i.e actual month is start from tuesday and it is starting from wednesday
// I am finding problem regarding setting values in calender-model
//Above code is running fine but problem in showing actual dates
//please suggest me to make necessary changes
import java.awt.Color;
public class Calendar extends JFrame {
private JPanel contentPane;
String[] years = { "2008", "2009", "2010" ,"2011","2012","2013","2014"};
JComboBox comboBox = new JComboBox(years);
String[] months = { "January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December" };
JList list = new JList(months);
JScrollPane scrollPane = new JScrollPane(list);
CalendarModel model = new CalendarModel();
JTable table = new JTable(model);
public Calendar() {
super();
getContentPane().setLayout(null);
comboBox.setBounds(10, 10, 100, 30);
comboBox.setSelectedIndex(5);
comboBox.addItemListener(new ComboHandler());
scrollPane.setBounds(200, 10, 150, 100);
list.setSelectedIndex(10);
list.addListSelectionListener(new ListHandler());
table.setBounds(10, 150, 550, 200);
model.setMonth(comboBox.getSelectedIndex() + 1998, list.getSelectedIndex());
getContentPane().add(comboBox);
getContentPane().add(scrollPane);
table.setGridColor(Color.black);
table.setShowGrid(true);
getContentPane().add(table);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(530,300);
setVisible(true);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calendar frame = new Calendar();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public class ComboHandler implements ItemListener {
public void itemStateChanged(ItemEvent e) {
System.out.println("ItemState change Method called ");
model.setMonth(comboBox.getSelectedIndex() + 1998, list.getSelectedIndex());
table.repaint();
}
}
public class ListHandler implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
model.setMonth(comboBox.getSelectedIndex() + 1998, list.getSelectedIndex());
table.repaint();
}
}
}
class CalendarModel extends AbstractTableModel {
String[] days = { "Sun" , "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
int[] numDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
String[][] calendar = new String[7][7];
public CalendarModel() {
//setting name of days (mon,tues)
for (int i = 0; i < days.length; ++i)
{
System.out.println("day[i] *** "+days[i]);
calendar[0][i] = days[i];
}
for (int i = 1; i < 7; ++i){
for (int j = 0; j < 7; ++j)
{
System.out.println("calendar[i][j] value i ** "+i +" j value "+ j );
calendar[i][j] = " ";
}
}
}
public int getRowCount() {
return 7;
}
public int getColumnCount() {
return 7;
}
public Object getValueAt(int row, int column) {
System.out.println("get Value at ** "+calendar[row][column]);
return calendar[row][column];
}
/*
public void setValueAt(Object value, int row, int column) {
System.out.println("set Value at ** "+(String) value);
calendar[row][column] = (String) value;
}*/
public void setMonth(int year, int month) {
for (int i = 1; i < 7; ++i)
{
for (int j = 0; j < 7; ++j)
{
calendar[i][j] = " ";
}
}
java.util.GregorianCalendar cal = new java.util.GregorianCalendar();
cal.set(year, month, 1);
int offset = cal.get(java.util.GregorianCalendar.DAY_OF_WEEK) - 1;
offset += 7;
int num = daysInMonth(year, month);
for (int i = 0; i < num; ++i) {
System.out.println("offset *** "+Integer.toString(i+1));
calendar[offset / 7][offset % 7] = Integer.toString(i+1);
++offset;
}
}
public boolean isLeapYear(int year) {
System.out.println("Is Leap Year *** ");
if (year % 4 == 0)
return true;
return false;
}
public int daysInMonth(int year, int month) {
System.out.println("day In month*** ");
int days = numDays[month];
if (month == 1 && isLeapYear(year))
++days;
System.out.println("days *** "+days);
return days;
}
}

I don't know if these are related but...
public void itemStateChanged(ItemEvent e) {
int index = comboBox.getSelectedIndex();
System.out.println("index = " + index + "; " + (index + 1998));
model.setMonth(comboBox.getSelectedIndex() + 1998, list.getSelectedIndex());
table.repaint();
}
Doesn't produce results which match those that are listed within the combo box. For example, if you select the first value, it will equal 1998, not 2008
So, if I select 2013 from the combo box, I'm actually getting 2003.
When I changed it to
public void itemStateChanged(ItemEvent e) {
int index = comboBox.getSelectedIndex();
System.out.println("index = " + index + "; " + (index + 2008));
model.setMonth(comboBox.getSelectedIndex() + 2008, list.getSelectedIndex());
table.repaint();
}
It gave me better results.
I also changed
java.util.GregorianCalendar cal = new java.util.GregorianCalendar();
to
java.util.Calendar cal = java.util.Calendar.getInstance();
You should avoid making assumptions about the users calendar system if possible...
I'd also avoid null layouts as well ;)
You should also avoid calling table.repaint when you change the table model, instead try using fireTableDataChanged from within the setMonth method
I would, personally, add the listeners to the combobox and JList before setting there selected indexes, this will allow the listeners to update the model for you...
You'll also need to fix you ListHandler so that it uses 2008 instead 1998

Have a try with this in setMonth method
public void setMonth(int year, int month)
Change
calendar[offset / 7][offset % 7] = Integer.toString(i+1);
To
calendar[offset / 7][offset % 7] = Integer.toString(i+2);

try this.. use - 2 instead of - 1 in offset calculation.
java.util.GregorianCalendar cal = new java.util.GregorianCalendar();
cal.set(year, month, 1);
int offset = cal.get(java.util.GregorianCalendar.DAY_OF_WEEK)- 2 ;
offset += 7;
int num = daysInMonth(year, month);
for (int i = 0; i < num; ++i) {
System.out.println("offset *** "+Integer.toString(i+1));
calendar[offset / 7][offset % 7] = Integer.toString(i+1);
++offset;

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!

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);
}
}
}
}

JOptionPane displaying HTML problems in Java

Okay, so I have this code, it prompts a month and a year from the user and prints the calendar for that month. I'm having some problems though.
the HTML font editing only affects the month.
the days of the week are not aligned in columns correctly.
Thanks!
package calendar_program;
import javax.swing.JOptionPane;
public class Calendar {
public static void main(String[] args) {
StringBuilder result=new StringBuilder();
// read input from user
int year=getYear();
int month=getMonth();
String[] allMonths={
"", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
int[] numOfDays= {0,31,28,31,30,31,30,31,31,30,31,30,31};
if (month == 2 && isLeapYear(year)) numOfDays[month]=29;
result.append(" "+allMonths[month]+ " "+ year+"\n"+" S M Tu W Th F S"+"\n");
int d= getstartday(month, 1, year);
for (int i=0; i<d; i++){
result.append(" ");
// prints spaces until the start day
}
for (int i=1; i<=numOfDays[month];i++){
String daysSpace=String.format("%4d", i);
result.append(daysSpace);
if (((i+d) % 7==0) || (i==numOfDays[month])) result.append("\n");
}
//format the final result string
String finalresult= "<html><font face='Arial'>"+result;
JOptionPane.showMessageDialog(null, finalresult);
}
//prompts the user for a year
public static int getYear(){
int year=0;
int option=0;
while(option==JOptionPane.YES_OPTION){
//Read the next data String data
String aString = JOptionPane.showInputDialog("Enter the year (YYYY) :");
year=Integer.parseInt(aString);
option=JOptionPane.NO_OPTION;
}
return year;
}
//prompts the user for a month
public static int getMonth(){
int month=0;
int option=0;
while(option==JOptionPane.YES_OPTION){
//Read the next data String data
String aString = JOptionPane.showInputDialog("Enter the month (MM) :");
month=Integer.parseInt(aString);
option=JOptionPane.NO_OPTION;
}
return month;
}
//This is an equation I found that gives you the start day of each month
public static int getstartday(int m, int d, int y){
int year = y - (14 - m) / 12;
int x = year + year/4 - year/100 + year/400;
int month = m + 12 * ( (14 - m) / 12 ) - 2;
int num = ( d + x + (31*month)/12) % 7;
return num;
}
//sees if the year entered is a leap year, false if not, true if yes
public static boolean isLeapYear (int year){
if ((year % 4 == 0) && (year % 100 != 0)) return true;
if (year % 400 == 0) return true;
return false;
}
}
Here's a rather stupid idea.
Rather then formatting your results using spaces, which may be affected by variance in the individual font widths of a variable width font...use a HTML table instead, or a JTable, or JXMonthView from the SwingX project
HTML Table
String dayNames[] = {"S", "M", "Tu", "W", "Th", "F", "S"};
result.append("<html><font face='Arial'>");
result.append("<table>");
result.append("<tr>");
for (String dayName : dayNames) {
result.append("<td align='right'>").append(dayName).append("</td>");
}
result.append("</tr>");
result.append("<tr>");
for (int i = 0; i < d; i++) {
result.append("<td></td>");
}
for (int i = 0; i < numOfDays[month]; i++) {
if (((i + d) % 7 == 0)) {
result.append("</tr><tr>");
}
result.append("<td align='right'>").append(i + 1).append("</td>");
}
result.append("</tr>");
result.append("</table>");
result.append("</html>");
JTable Example
MyModel model = new MyModel();
List<String> lstRow = new ArrayList<String>(7);
for (int i = 0; i < d; i++) {
lstRow.add("");
}
for (int i = 0; i < numOfDays[month]; i++) {
if (((i + d) % 7 == 0)) {
model.addRow(lstRow);
lstRow = new ArrayList<String>(7);
}
lstRow.add(Integer.toString(i + 1));
}
if (lstRow.size() > 0) {
while (lstRow.size() < 7) {
lstRow.add("");
}
model.addRow(lstRow);
}
JTable table = new JTable(model);
// Kleopatra is so going to kill me for this :(
Dimension size = table.getPreferredScrollableViewportSize();
size.height = table.getRowCount() * table.getRowHeight();
table.setPreferredScrollableViewportSize(size);
JOptionPane.showMessageDialog(null, new JScrollPane(table));
public static class MyModel extends AbstractTableModel {
public static final String[] DAY_NAMES = {"S", "M", "Tu", "W", "Th", "F", "S"};
private List<List<String>> lstRowValues;
public MyModel() {
lstRowValues = new ArrayList<List<String>>(25);
}
#Override
public int getRowCount() {
return lstRowValues.size();
}
#Override
public String getColumnName(int column) {
return DAY_NAMES[column];
}
#Override
public int getColumnCount() {
return 7;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
List<String> rowData = lstRowValues.get(rowIndex);
return rowData.get(columnIndex);
}
public void addRow(List<String> lstValues) {
lstRowValues.add(lstValues);
fireTableRowsInserted(getRowCount(), getRowCount());
}
}
Or you can go have a look at JXMonthView
There are a couple issues I noticed. For one, instead of getting your own days in the month or leap year info, you could use the java.util.Calendar class, which will do that for you.
Also, \n newlines don't behave well when interspersed with HTML formatting, so try using < br/> instead. This is causing the font choice to work improperly.
It looks like extra spaces also get stripped, so surrounding everything with a < pre> tag will fix that.

How to implement more than one Images in form and new Date instances

In the CalendarCanvas class, the idea is to press on any day in the Calendar and a form will be presented with the actual date of the day THE USER picked (not just today's date as it's doing now) and underneath the form will be the image pertaining to the form (eg. June 21st (image.jpg)).
I'm having two problems.
Number one, the program only likes one image which is the Men.img. It will display that image in all of the three forms. The other two images will not display at all.
And I don't understand because I first started with one form and the images.jpg image and that image worked. All I did was create 2 new forms and switch the order of images.
I even reduced the sizes (width/height & KB) to match with Men.jpg but it still doesn't show. The string inside the ImageItem constructor doesn't even show.
Lastly how do I create a new instance of the calendar.getSelectedDate().toString() method to show the new user picked date so I can put that above the image when the user picks a different day?
In the keyPressed method, the commented out new instance of Alert will do that for me but I don't want an alert, I want it to be the title of the forms pertaining to what day the user picked.
Below is my code:
Class CalendarMidlet:
import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
* #author addylesson
*/
public class CalendarMidlet extends MIDlet {
private Display mydisplay;
private Command f;
private Displayable d;
public CalendarMidlet(){}
public void startApp() {
d = new CalendarCanvas(this);
f = new Command("Exit", Command.EXIT, 0);
d.addCommand(f);
d.setCommandListener(new CommandListener()
{
public void commandAction(Command c, Displayable s)
{
if(c == f)
notifyDestroyed();
}
} );
mydisplay = Display.getDisplay(this);
mydisplay.setCurrent(d);
}
public void startOver() {
final Displayable d = new CalendarCanvas(this);
d.addCommand(f);
d.setCommandListener(new CommandListener()
{
public void commandAction(Command c, Displayable s)
{
if(c == f)
notifyDestroyed();
}
} );
mydisplay.setCurrent(d);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Class CalendarCanvas:
import java.io.IOException;
import java.util.Date;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class CalendarCanvas extends Canvas
{
CalendarWidget calendar = null;
CalendarMidlet midlet = null;
private Alert alert;
private List mList;
private Command f,e,n;
private Display mydisplay;
private Form form;
private Form form2;
private Form form3;
private ImageItem imageItem;
private ImageItem imageItem2;
private ImageItem imageItem3;
public CalendarCanvas(final CalendarMidlet m)
{
String day = calendar.getSelectedDate().toString();
this.midlet = m;
calendar = new CalendarWidget(new Date());
calendar.headerFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE);
calendar.weekdayFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
calendar.weekdayBgColor = 0xccccff;
calendar.weekdayColor = 0x0000ff;
calendar.headerColor = 0xffffff;
form = new Form(day);
form2 = new Form("New Page");
form3 = new Form("New Page");
try
{
imageItem = new ImageItem(
"Men In Black 3: ",
Image.createImage("Men.jpg"),
ImageItem.LAYOUT_DEFAULT,
"DuKe");
form.append(imageItem);
} catch(Exception s) {}
try
{
imageItem2 = new ImageItem(
"Jordon vs Knicks: ",
Image.createImage("images.jpg"),
ImageItem.LAYOUT_DEFAULT,
"Not");
form2.append(imageItem2);
} catch(Exception s) {}
try
{
imageItem3 = new ImageItem(
"Horoscope: ",
Image.createImage("Men.jpg"),
ImageItem.LAYOUT_DEFAULT,
"DuKe");
form3.append(imageItem3);
} catch(Exception s) {}
alert = new Alert("Listen", "On this day "
+calendar.getSelectedDate().toString()+ "stuff happened", null, null);
alert.setTimeout(Alert.FOREVER);
n = new Command("Next", Command.SCREEN,0);
f = new Command("Back", Command.BACK, 0);
e = new Command("Exit", Command.EXIT, 1);
form.addCommand(f);
form.addCommand(n);
form2.addCommand(f);
form2.addCommand(n);
form3.addCommand(f);
form3.addCommand(e);
form.setCommandListener(new CommandListener()
{
public void commandAction(Command c, Displayable s)
{
if (c == f)
m.startOver();
if (c == e)
m.notifyDestroyed();
if (c == n)
Display.getDisplay(midlet).setCurrent(form2);
}
} );
form2.setCommandListener(new CommandListener()
{
public void commandAction(Command c, Displayable s)
{
if (c == f)
m.startOver();
if (c == e)
m.notifyDestroyed();
if (c == n)
Display.getDisplay(midlet).setCurrent(form3);
}
} );
form3.setCommandListener(new CommandListener()
{
public void commandAction(Command c, Displayable s)
{
if (c == f)
m.startOver();
if (c == e)
m.notifyDestroyed();
}
} );
calendar.initialize();
}
protected void keyPressed(int key)
{
int keyCode = getGameAction(key);
String day = calendar.getSelectedDate().toString();
if(keyCode == FIRE)
{
/*Display.getDisplay(midlet).setCurrent(
new Alert("Selected date",
day, null,
AlertType.CONFIRMATION)
);*/
Display.getDisplay(midlet).setCurrent(form);
}
else
{
calendar.keyPressed(keyCode);
repaint();
}
}
protected void paint(Graphics g)
{
g.setColor(0xff0000);
g.fillRect(0, 0, getWidth(), getHeight());
calendar.paint(g);
}
}
Class CalendarWidget:
import java.util.Calendar;
import java.util.Date;
import javax.microedition.lcdui.*;
public class CalendarWidget
{
static final String[] MONTH_LABELS = new String[]{
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
};
static final String[] WEEKDAY_LABELS = new String[]{
"M", "T", "W", "T", "F", "S", "S"
};
/* starting week day: 0 for monday, 6 for sunday */
public int startWeekday = 0;
/* elements padding */
public int padding = 2;
/* cells border properties */
public int borderWidth = 4;
public int borderColor = 0x000000;
/* weekday labels properties */
public Font weekdayFont = Font.getDefaultFont();
public int weekdayBgColor = 0xcccccc;
public int weekdayColor = 0xffffff;
/* header (month-year label) properties */
public Font headerFont = Font.getDefaultFont();
public int headerBgColor = 0xff0000;
public int headerColor = 0xff0000;
/* cells properties */
public Font font = Font.getDefaultFont();
public int foreColor = 0xffffff;
public int bgColor = 0xcccccc;
public int selectedBgColor = 0x000000;
public int selectedForeColor = 0xff0000;
/* internal properties */
int width = 0;
int height = 0;
int headerHeight = 0;
int weekHeight = 0;
int cellWidth = 0;
int cellHeight = 0;
/* internal time properties */
long currentTimestamp = 0;
Calendar calendar = null;
int weeks = 0;
public CalendarWidget(Date date)
{
calendar = Calendar.getInstance();
//we'll see these 2 methods later
setDate(date);
initialize();
}
public Date getSelectedDate()
{
return calendar.getTime();
}
public void setDate(Date d)
{
currentTimestamp = d.getTime();
calendar.setTime(d);
//weeks number can change, depending on week starting day and month total days
this.weeks = (int)Math.ceil(((double)getStartWeekday() + getMonthDays()) / 7);
}
public void setDate(long timestamp)
{
setDate(new Date(timestamp));
}
void initialize()
{
//let's initialize calendar size
this.cellWidth = font.stringWidth("MM") + 3 * padding;
this.cellHeight = font.getHeight() + 15 * padding;
this.headerHeight = headerFont.getHeight() + 2 * padding;
this.weekHeight = weekdayFont.getHeight() + 2 * padding;
this.width = 7 * (cellWidth + borderWidth) + borderWidth;
initHeight();
}
void initHeight()
{
this.height =
headerHeight + weekHeight +
this.weeks * (cellHeight + borderWidth) + borderWidth;
}
int getMonthDays()
{
int month = calendar.get(Calendar.MONTH);
switch(month)
{
case 3:
case 5:
case 8:
case 10:
return 30;
case 1:
return calendar.get(Calendar.YEAR) % 4 == 0 && calendar.get(Calendar.YEAR) % 100 != 0 ? 29 : 28;
default:
return 31;
}
}
int getStartWeekday()
{
//let's create a new calendar with same month and year, but with day 1
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
c.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
c.set(Calendar.DAY_OF_MONTH, 1);
//we must normalize DAY_OF_WEEK returned value
return (c.get(Calendar.DAY_OF_WEEK) + 5) % 7;
}
public void keyPressed(int key)
{
switch(key)
{
case Canvas.UP:
go(-7);
break;
case Canvas.DOWN:
go(7);
break;
case Canvas.RIGHT:
go(1);
break;
case Canvas.LEFT:
go(-1);
break;
}
}
void go(int delta)
{
int prevMonth = calendar.get(Calendar.MONTH);
setDate(currentTimestamp + 86400000 * delta);
//we have to check if month has changed
//if yes, we have to recalculate month height
//since weeks number could be changed
if(calendar.get(Calendar.MONTH) != prevMonth)
{
initHeight();
}
}
public void paint(Graphics g)
{
//painting background
g.setColor(bgColor);
g.fillRect(0, 0, width, height);
//painting header (month-year label)
g.setFont(headerFont);
g.setColor(headerColor);
g.drawString(MONTH_LABELS[calendar.get(Calendar.MONTH)] + " " + calendar.get(Calendar.YEAR), width / 2, padding, Graphics.TOP | Graphics.HCENTER);
//painting week days labels
g.translate(0, headerHeight);
g.setColor(weekdayBgColor);
g.fillRect(0, 0, width, weekHeight);
g.setColor(weekdayColor);
g.setFont(weekdayFont);
for(int i = 0; i < 7; i++)
{
g.drawString(WEEKDAY_LABELS[(i + startWeekday) % 7],
borderWidth + i * (cellWidth + borderWidth) + cellWidth / 2,
padding,
Graphics.TOP | Graphics.HCENTER
);
}
g.translate(0, weekHeight);
g.setColor(borderColor);
for(int i = 0; i <= weeks; i++)
{
g.fillRect(0, i * (cellHeight + borderWidth), width, borderWidth);
}
for(int i = 0; i <= 7; i++)
{
g.fillRect(i * (cellWidth + borderWidth), 0, borderWidth, height - headerHeight - weekHeight);
}
int days = getMonthDays();
int dayIndex = (getStartWeekday() - this.startWeekday + 7) % 7;
g.setColor(foreColor);
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
for(int i = 0; i < days; i++)
{
int weekday = (dayIndex + i) % 7;
int row = (dayIndex + i) / 7;
int x = borderWidth + weekday * (cellWidth + borderWidth) + cellWidth / 2;
int y = borderWidth + row * (cellHeight + borderWidth) + padding;
if(i + 1 == currentDay)
{
g.setColor(selectedBgColor);
g.fillRect(
borderWidth + weekday * (cellWidth + borderWidth),
borderWidth + row * (cellHeight + borderWidth),
cellWidth, cellHeight);
g.setColor(selectedForeColor);
}
g.drawString("" + (i + 1), x, y, Graphics.TOP | Graphics.HCENTER);
if(i + 1 == currentDay)
{
g.setColor(foreColor);
}
}
g.translate(0, - headerHeight - weekHeight);
}
}
There are no evident mistakes in the code snippet you posted.
To easier find out what could possibly go wrong when your MIDlet becomes complicated like that, add logging statements and run it in emulator watching console output.
You definitely need to add logging within catch blocks. To find out why I am making such a strong statement, search Web for something like Java swallow exceptions.
Other points where I'd recommend logging are within commandAction and when invoking setCurrent. When developing, feel free to add more where you feel the need to (keyPressed looks like a good candidate for that, too).
public class Log {
// utility class to keep logging code in one place
public static void log (String message) {
System.out.println(message);
// when debugging at real device, S.o.p above can be refactored
// - based on ideas like one used here (with Form.append):
// http://stackoverflow.com/questions/10649974
// - Another option would be to write log to RMS
// and use dedicated MIDlet to read it from there
// - If MIDlet has network connection, an option is
// to pass log messages over the network. Etc etc...
}
}
// ... other classes...
// ...
catch (Exception e) {
Log.log("unexpected exception: [" + e + "]");
}
// ...
public void commandAction(Command c, Displayable s) {
Log.log("command: [" + c.getCommandLabel()
+ "] at screen: [" + d.getTitle() + "]");
// ...
}
// ...
Log.log("set current: [" + someDisplayable.getTitle() + "]");
mydisplay.setCurrent(someDisplayable);
// ...
protected void keyPressed(int key) {
Log.log("key pressed: [" + getKeyName(key) + "]");
// ...
}

Categories