GridLayout Quiz: layout a month calendar - Java Swing

Java examples for Swing:GridLayout

Introduction

Display a calendar for a single month, including headings for the seven days of the week and a title for the month across the top.

Demo Code

import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] arguments) {

    CalMonth cal = new CalMonth();
  }//from w ww  .j av a 2  s . c om
}

class CalMonth extends JFrame {
  JLabel[] days = new JLabel[31];
  JLabel[] dayTitles = new JLabel[7];
  JLabel monthTitle = new JLabel("March 2015");

  CalMonth() {
    super("October 2000");
    setSize(260, 260);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    FlowLayout flow = new FlowLayout();
    setLayout(flow);
    JPanel titlePane = new JPanel();
    titlePane.setLayout(flow);
    titlePane.add(monthTitle);
    add(titlePane);
    JPanel monthPane = new JPanel();
    GridLayout calLayout = new GridLayout(6, 7);
    monthPane.setLayout(calLayout);
    String[] dayNames = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
    for (int i = 0; i < 7; i++) {
      dayTitles[i] = new JLabel(dayNames[i]);
      monthPane.add(dayTitles[i]);
    }
    for (int i = 0; i < days.length; i++) {
      days[i] = new JLabel("" + (i + 1));
      monthPane.add(days[i]);
    }
    add(monthPane);
    setVisible(true);
  }

}

Related Tutorials