Question

How to create weekly calendar GUI in Java Language? I want to implement a calendar display...

How to create weekly calendar GUI in Java Language?
I want to implement a calendar display current week, and can go back and forth to see the past week and next week. Anyhelp with detail is appreciated. Thank you!
For example for this current week: S    M T W T F S
                                                             28 29 30 31 1 2 3
Above is my expected output.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE

import javax.swing.*;

import javax.swing.table.*;

import java.awt.*;

import java.awt.event.*;

import java.util.*;

public class Main{

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.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 previous());

btnNext.addActionListener(new next());

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

refresh (realMonth, realYear); //Refresh calendar

}

  

public static void refresh(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 CalendarGUI());

}

  

static class CalendarGUI 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 previous implements ActionListener{

public void actionPerformed (ActionEvent e){

if (currentMonth == 0){ //Back one year

currentMonth = 11;

currentYear -= 1;

}

else{ //Back one month

currentMonth -= 1;

}

refresh(currentMonth, currentYear);

}

}

static class next implements ActionListener{

public void actionPerformed (ActionEvent e){

if (currentMonth == 11){ //Foward one year

currentMonth = 0;

currentYear += 1;

}

else{ //Foward one month

currentMonth += 1;

}

refresh(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);

refresh(currentMonth, currentYear);

}

}

}

}

Add a comment
Know the answer?
Add Answer to:
How to create weekly calendar GUI in Java Language? I want to implement a calendar display...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java GUI Help! Hi, I have a Java GUI exercise that I need to complete and...

    Java GUI Help! Hi, I have a Java GUI exercise that I need to complete and was wondering if I could have a little bit of help... you can see it below. Create a simple graphical application that will enable a user to perform push, pop and peek operations on a stack and display the resulting stack (using toString) in a text area. Any help would be much appreciated! Thank you.

  • Please try to write the code with Project 1,2 and 3 in mind. And use java language, thank you very much. Create an Edit Menu in your GUI Add a second menu to the GUI called Edit which will have one me...

    Please try to write the code with Project 1,2 and 3 in mind. And use java language, thank you very much. Create an Edit Menu in your GUI Add a second menu to the GUI called Edit which will have one menu item called Search. Clicking on search should prompt the user using a JOptionPane input dialog to enter a car make. The GUI should then display only cars of that make. You will need to write a second menu...

  • Java: student directory GUI You need to implement three classes: Person Student StudentDirectory StudentMain Start by...

    Java: student directory GUI You need to implement three classes: Person Student StudentDirectory StudentMain Start by implementing Person and Student classes. Once you are sure you can serialize and deserialize and ArrayList of Students to and from a file, move on to building the GUI application. Person: The Person class should implement serializable interface. It contains the following: Person's first name (String) Person's last name (String) Person's id number Person's date of birth (Date) public String toString(): This method method...

  • I need the following written in Java please, thank you ' We want you to implement...

    I need the following written in Java please, thank you ' We want you to implement a java class that will show details on users and throw exceptions where needed. The following requirements specify what fields you are expected to implement in your User class: - A private String firstName that specifies the first name of the user - A private String lastName that specifies the last name of the user - A private int age that specifies user's age...

  • Language : JAVA Part A Create a class CompanyDoc, representing an official document used by a...

    Language : JAVA Part A Create a class CompanyDoc, representing an official document used by a company. Give it a String title and an int length. Throughout the class, use the this. notation rather than bare instance variables and method calls.   Add a default constructor. Add a parameterized constructor that takes a value for title. Use this( appropriately to call one constructor from another. Add a toString(), which returns a string with the title, and the length in parentheses. So...

  • I want to extend this GUI application in java language. Thanks for the help in advance. import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.Action...

    I want to extend this GUI application in java language. Thanks for the help in advance. import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class FormWindow {     private JFrame frame;     /**      * Launch the application.      */     public static void main(String[] args) {         EventQueue.invokeLater(new Runnable() {             public void run() {                 try {                     FormWindow window = new FormWindow();                     window.frame.setVisible(true);                 } catch (Exception e) {                     e.printStackTrace();                 }             }         });     }     /**      * Create the application.      */     public FormWindow() {         initialize();    ...

  • Write a function in matlab for these parameters (char) A string representing 7 days of the...

    Write a function in matlab for these parameters (char) A string representing 7 days of the week (eg. 'N M T W R F S') (double) A vector representing 7 dates of the week (eg. [4 5 6 8 79 10]) (double) A positive or negative number of days (char) A string representing 7 days of the new week (double) A vector representing 7 dates of the new week circshift() It's fairly simple to determine what the date was or...

  • Need help with java In this program you will use a Stack to implement backtracking to solve Sudok...

    need help with java In this program you will use a Stack to implement backtracking to solve Sudoku puzzles. Part I. Implement the stack class.  Created a generic, singly-linked implementation of a Stack with a topPtr as the only instance variable. Implement the following methods only: public MyStack() //the constructor should simply set the topPtr to null public void push(E e) public E pop()  Test your class thoroughly before using it within the soduku program Part II. Create...

  • I. User Interface Create a JavaFX application with a graphical user interface (GUI) based on the...

    I. User Interface Create a JavaFX application with a graphical user interface (GUI) based on the attached “GUI Mock-Up”. Write code to display each of the following screens in the GUI: A. A main screen, showing the following controls: • buttons for “Add”, “Modify”, “Delete”, “Search” for parts and products, and “Exit” • lists for parts and products • text boxes for searching for parts and products • title labels for parts, products, and the application title B. An add...

  • This program needs to be in JAVA language. Also, I need to create my own LinkedList...

    This program needs to be in JAVA language. Also, I need to create my own LinkedList class, I can not use the Java LinkedList Library. Please read all aspects of the program, it needs to display 200 random numbers that are 5 digits long sorted from smallest to largest. I can not use Collection(s) or packages libraries. Should only need: import java.util.Random; import java.util.Scanner; Please provide output screenshots after the code. Thank you! You are going to create a Linked...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT