最近刚学了gui部分的内容,练手和两个同学一起做了一个小日历,第一次做没啥经验,代码多多少少有点不规范的,各位见谅,下面浅浅讲一下思路。

代码已给出了每段比较详细的注释,整体分FirstFrame和MainFrame,first上有两个按钮,分别加监听触发退出和进入主页面

然后main中是整体精华所在,通过不断setText每个按钮上的文字,来达到切换时,日期自动切换的功能,然后,有年份选择和月份选择两个列表框,通过获取列表框中的内容,来设置当前应该显示的时间。

这个是mainframe的页面:

然后本日历记事本还可以通过点击当天按钮,然后唤起一个文本框,可以输入想要记录的备忘事项,并且,当下次打开程序时,上次记录的事项可以通过文件可持续化保存,这也属于一个小功能。

整体项目分三个java文件,分别是TextBook:主要代码,TextFile:文件操作,封装在一个类中了,Start启动器

在文章底部有源码链接

下面是TextBook.java文件:

package com.tt.Textbook;import java.awt.*;import java.awt.event.*;import javax.swing.*;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;//初始页面
class FirstFrame extends JFrame
{public FirstFrame(){//container分为上下表格布局Container FirstContainer = this.getContentPane();FirstContainer.setLayout( new GridLayout(2,1) );//需要两个面板,分别是标题和退出框以及进入按钮Panel panel1 = new Panel( new BorderLayout() );Panel panel2 = new Panel( new GridLayout(1,3) );//下部分的1行3列表格布局Panel panel3 = new Panel( new GridLayout(2,1) );//下面中间的二层布局Panel panel4 = new Panel( new FlowLayout() );//下中之一Panel panel5 = new Panel( new FlowLayout() );//下中之二//导入标题图片ImageIcon Titleimg = new ImageIcon( "photo/title.png" );JLabel l1 = new JLabel();l1.setIcon( Titleimg );JLabel l2 = new JLabel();l2.setIcon( new ImageIcon("............") );JLabel l3 = new JLabel();l3.setIcon( new ImageIcon("............") );panel1.add( l1, BorderLayout.CENTER );//进入主页面按钮JButton b1 = new JButton("退出程序");JButton b2 = new JButton("进入主页面 ");panel2.add( l2 );panel4.add( b2 );panel5.add( b1 );panel3.add( panel4 );panel3.add( panel5 );panel2.add( panel3 );panel2.add( l3 );//container添加两个面板FirstContainer.add( panel1 );FirstContainer.add( panel2 );b1.addActionListener(new ActionListener() {@Overridepublic void actionPerformed( ActionEvent e ) {System.exit(0);}});b2.addActionListener(new ActionListener() //添加监听事件,点击后可以打开主Frame{@Overridepublic void actionPerformed(ActionEvent e) {new MainFrame();dispose();}});//一些初始化操作this.setVisible(true);this.setBounds(500,300,700,500);this.setTitle( "桌面记事本" );this.setDefaultCloseOperation( EXIT_ON_CLOSE );this.setResizable( false );}
}//主要界面
class MainFrame extends JFrame
{private String content;private JComboBox YearBox=new JComboBox();private JComboBox MonthBox=new JComboBox();//两个标签,在init中设置字体样式private  JLabel YearLabel=new JLabel("年份:");private  JLabel MonthLabel=new JLabel("月份:");//两个按钮,需要满足监听功能private JButton b_ok=new JButton("确定");private   JButton b_today=new JButton("今天");//前后两个按钮private JButton upJButton=new JButton( new ImageIcon("photo/line_left.png"));private JButton downJButton=new JButton(new ImageIcon("photo/line_right.png"));//使用日期类,获取当前年份,月份,日期private Date date = new Date();//属于一个工具对象,对日期的操作。//日期类的get方法获取当前时间private int NowYear = date.getYear() + 1900;private int NowMonth = date.getMonth();private boolean todayFlag = false;//标志开始设置成false是因为有一个初始化private JButton[] b_week=new JButton[7];private  ItemButton[] b_day=new ItemButton[42];private String[] week= {"MON","TUE","WED","THU","FRI","SAT","SUN"};private int Month=0;private String Year=null;private static JLabel BeijingTime;private Calendar nowTime=Calendar.getInstance();private static String sday;public void init()                            //初始化{Container containerMain=this.getContentPane();containerMain.setLayout(new BorderLayout());//首先进行页面布局,分为两个panel,操作panel和主日历panelJPanel PanelOpreater = new JPanel(new FlowLayout());JPanel PanelMain = new JPanel(new GridLayout(7,7,4,4));JPanel PanelNow = new JPanel(new FlowLayout());//可写可不写//container1.setLayout(new BorderLayout());//设置label字体样式YearLabel.setFont(new Font("Dialog",Font.BOLD,16));MonthLabel.setFont(new Font("Dialog",Font.BOLD,16));for(int i = NowYear - 20;i <= NowYear + 100;i++)//年份范围为前后二十年{YearBox.addItem(i+"");}YearBox.setSelectedIndex(20);//当前年份for(int i = 1; i <= 12; i++)//仅有12个月{MonthBox.addItem(i+"");}MonthBox.setSelectedIndex(NowMonth);//先把操作面板添加好按钮和标签PanelOpreater.add(YearLabel);PanelOpreater.add(YearBox);PanelOpreater.add(MonthLabel);PanelOpreater.add(MonthBox);PanelOpreater.add(b_ok);PanelOpreater.add(b_today);//获取当前类的监听事件,ok和today可以共用一个事件b_ok.addActionListener(new FindActionListener());b_today.addActionListener(new FindActionListener());//up和down按钮upJButton.addActionListener(new BesideActionListener());downJButton.addActionListener(new BesideActionListener());//对星期进行设置for( int i=0; i<7; i++ ){b_week[i] = new JButton( week[i] );if( i == 5 || i == 6 )b_week[i].setForeground( Color.red );PanelMain.add( b_week[i] );}//把day按钮加进去for(int i=0; i<42; i++){b_day[i]=new ItemButton("");PanelMain.add(b_day[i]);}this.SetCalendar();JLabel time = new JLabel();time.setForeground(Color.black);time.setBounds(30, 0, 500, 130);time.setFont(new Font("微软雅黑", Font.BOLD, 30));final JLabel varTime = time;Timer timeAction = new Timer(100, new ActionListener() {public void actionPerformed(ActionEvent e) {long timemillis = System.currentTimeMillis();// 转换日期显示格式SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");varTime.setText(df.format(new Date(timemillis)));}});timeAction.start();PanelNow.add(varTime);containerMain.add(PanelOpreater,BorderLayout.NORTH);containerMain.add(upJButton,BorderLayout.WEST);containerMain.add(PanelMain,BorderLayout.CENTER);containerMain.add(downJButton,BorderLayout.EAST);containerMain.add(PanelNow,BorderLayout.SOUTH);}public void SetCalendar()                  //需要传入列表框中选中的年份,月份;然后重新设置表格内容{int SumDays=0;if(todayFlag)//是今天{Year=NowYear+"";Month=NowMonth;}else//不是今天,根据列表框中的选择{Year=YearBox.getSelectedItem().toString();//object类中,转成字符串Month=MonthBox.getSelectedIndex();//默认设置月份从0开始}int intYear=Integer.parseInt(Year)-1900;//将字符串转成int型Date FirstDay = new Date(intYear, Month, 1);GregorianCalendar cal = new GregorianCalendar();cal.setTime(FirstDay);int counter=1;//计数器,用来设置时间if(Month == 0||Month == 2||Month == 4||Month == 6||Month == 7||Month == 9||Month == 11)//{SumDays = 31;} else if(Month == 3||Month == 5||Month == 8||Month == 10) {SumDays = 30;} else {if( cal.isLeapYear(intYear) )    //判断闰年{SumDays = 29;} else {SumDays = 28;}}int FirstLocation=FirstDay.getDay();for(int i=((FirstLocation-1)+7)%7;i<((FirstLocation-1)+7)%7+SumDays;i++){if(Month==NowMonth && intYear==NowYear-1900 && i==((FirstLocation-1)+7)%7+date.getDate()-1){b_day[i].setForeground(Color.ORANGE);b_day[i].setText((counter++)+"");}else {b_day[i].setText((counter++) + "");b_day[i].setForeground(Color.black);}if(i%7==5 || i%7==6){if(!(Month==NowMonth && intYear==NowYear-1900 && i==((FirstLocation-1)+7)%7+date.getDate()-1))b_day[i].setForeground(Color.red);}}//没有用的地方清空for(int i=0;i<((FirstLocation-1)+7)%7;i++)b_day[i].setText("");for(int i=((FirstLocation-1)+7)%7+SumDays;i<42;i++)b_day[i].setText("");}class ItemButton extends JButton            //按钮事件触发{public ItemButton(String name){super();this.setText(name);this.setVisible(true);this.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {sday=e.getActionCommand();if( sday!="" )                            //防止日期空白按钮被打开写文件try {new TextJFrame();} catch (IOException ioException) {ioException.printStackTrace();}}});}}class TextJFrame extends JFrame               //文本框frame,用来输入待办事项{public TextJFrame() throws IOException {this.setTitle("备忘事项");Container TextContainer=this.getContentPane();TextContainer.setLayout(new BorderLayout());String syear = (String) YearBox.getSelectedItem();String smonth = (String) MonthBox.getSelectedItem();String fname = null;                                         //用于判断的文件名字:是否存在if(smonth.length()<2){if(sday.length()<2)fname = syear+"0"+smonth+"0"+sday;elsefname = syear+"0"+smonth+sday;} else {if(sday.length()<2)fname = syear+smonth+"0"+sday;elsefname = syear+smonth+sday;}File file = new File("src//"+fname);               //创建文档,可以根据前面传来的 key 修改文件名用于后期的读出if (!file.exists()) {                                       //原文件不存在, 需要新建文件file.createNewFile();content=null;System.out.println("文件已创建");} else {                                                    //原文件存在, 可以直接打开 并 续写content = TextFile.read("src//"+fname);      //已经获取文件内容System.out.println("文件已存在");}TextField textMain=new TextField(content);                    //文本框所在textMain.addActionListener(new TextActionListener() );       //添加监听事件//使用一个返回按钮JButton ret=new JButton("返回按钮");ret.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {dispose();}});TextContainer.add(textMain,BorderLayout.CENTER);TextContainer.add(ret,BorderLayout.SOUTH);//文本窗口的一些初始化工作this.setVisible(true);this.setBounds(500, 300, 700 ,500 );this.setResizable(false);}}class FindActionListener implements ActionListener{//监听ok和today的事件@Overridepublic void actionPerformed(ActionEvent e) {//点击通过判断todayflag,true就返回当天,列表框中的内容变化就变成false然后跳转,用到Date类中的函数//跳转时,要调用一个SetCalendar函数if(e.getSource()==b_ok){todayFlag=false;SetCalendar();//跳转操作}if(e.getSource()==b_today){todayFlag=true;//先设置成true然后通过SetCalendar方法跳转//刷新列表框中的初始值YearBox.setSelectedIndex(20);MonthBox.setSelectedIndex(NowMonth);SetCalendar();}}}class BesideActionListener implements ActionListener//侧翼双栏的控制{@Overridepublic void actionPerformed(ActionEvent e) {if(e.getSource()==upJButton){int monthb=MonthBox.getSelectedIndex();int year = YearBox.getSelectedIndex();if( monthb - 1 != -1) {MonthBox.setSelectedIndex(monthb - 1);todayFlag = false;SetCalendar();}else {MonthBox.setSelectedIndex(11);YearBox.setSelectedIndex(year-1);todayFlag = false;SetCalendar();}}else if(e.getSource()==downJButton){int monthb=MonthBox.getSelectedIndex();int year = YearBox.getSelectedIndex();if( monthb + 1 != 12) {MonthBox.setSelectedIndex(monthb + 1);todayFlag = false;SetCalendar();}else {MonthBox.setSelectedIndex(0);YearBox.setSelectedIndex(year+1);todayFlag = false;SetCalendar();}}}}class TextActionListener implements ActionListener//内部监听类{@Overridepublic void actionPerformed(ActionEvent e)                        //在这之前先判断同名文件是否存在,如果存在则读出,不存在则新建{                                                             //新建文件存储在src文件夹内String syear=(String) YearBox.getSelectedItem();String smonth=(String) MonthBox.getSelectedItem();String fname=null;if(smonth.length()<2){if(sday.length()<2)fname=syear+"0"+smonth+"0"+sday;elsefname=syear+"0"+smonth+sday;} else {if(sday.length()<2)fname=syear+smonth+"0"+sday;elsefname=syear+smonth+sday;}TextField field=(TextField)e.getSource();                     //获得一些资源TextFile.write( "src//" + fname, field.getText() );  //将 field 中的内容写入 data.txt//             例子测试//              public static void main(String[] args) {//                  String file = read("e:\\data\\data3.txt");           //读出文件//                    System.out.println(file);                           //输出到控制台//                  write("e:\\data\\data5.txt",file);                    //写入到 xx 文件////                 TextFile text = new TextFile("e:\\data\\data3.txt");     //读出/文件到 TextFile//                 System.out.println(text);                                   //输出//                  text.write("e:\\data\\data6.txt");                            //将 TextFile 写入到 xx 路径的文件//             }//             System.out.println( field.getText());//             field.setText("");}}public MainFrame(){this.init();//此处也可以把初始化封装在一个init方法里this.setTitle("日历");this.setVisible(true);this.setBounds(500, 300, 700 ,500 );this.setResizable(false);this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);this.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {int result = JOptionPane.showConfirmDialog(null, "确认退出?", "确认",                            JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);if(result == JOptionPane.OK_OPTION){System.exit(0);}}});}
}

因为是第一次做的项目,所以肯定有很多地方不足的,非常欢迎大家指出问题,一起讨论

点此查看完整项目源码

基于java GUI实现的一个日历记事本小项目相关推荐

  1. java gui论文_毕业设计论文-基于JAVA GUI的电子邮件客户端软件的设计与实现.doc

    毕业设计论文-基于JAVA GUI的电子邮件客户端软件的设计与实现.doc 还剩 41页未读, 继续阅读 下载文档到电脑,马上远离加班熬夜! 亲,很抱歉,此页已超出免费预览范围啦! 如果喜欢就下载吧, ...

  2. java课程设计日历记事本_《Java程序设计》课程设计日历记事本.doc

    <Java程序设计>课程设计日历记事本 PAGE PAGE 2 本科生课程设计 课程名称 Java程序设计课程设计 课程编号 j1620011 题目 日历记事本 学号 2008116222 ...

  3. 基于JAVA集合写的一个梭哈游戏

    基于JAVA集合写的一个梭哈游戏. 游戏思路: 1,首先使用一个List数组保存一副无序的扑克牌(使用集合工具类) 2,使用一个Map集合和TreeSet集合保存玩家手上的手牌 3,使用一个Map集合 ...

  4. (超多图)基于Android studio开发的一个简单入门小应用(超级详细!!)(建议收藏)

    基于Android studio开发的一个简单入门小应用 一.前言 二.前期准备 三.开发一个小应用 五.运行应用 一.前言 在暑假期间,我学习JAVA基础,为了能早日实现自己用代码写出一个app的& ...

  5. ***JAVA*和*Eclipse*开发一个换装小游戏**

    JAVA和Eclipse开发一个换装小游戏** 家有一女如有一宝,最近女朋友的少女心有点爆棚,作为一个计算机专业的人,我的情商简直是低到吓人,但是我还是想到了,亲自给女朋友做一个换装的小游戏,来满足女 ...

  6. 基于tutk方案的p2p源码_基于JAVA的局域网文件共享平台P2P实训项目源码(毕业设计 课程设计)...

    [实例简介] 基于JAVA的局域网文件共享平台P2P实训项目源码(毕业设计 课程设计). 可直接运行.做毕业设计.课程设计或者想研究下技术的可以下载学习.需要更多资源的可以关注我. [实例截图] [核 ...

  7. 手把手教你完成一个数据科学小项目(9):情感分析与词云

    前言 请先阅读"中国年轻人正带领国家走向危机",这锅背是不背? 一文,以对"手把手教你完成一个数据科学小项目"系列有个全局性的了解. 本系列代码统一开源在Git ...

  8. 0301 - 一个比价的小项目

    这两天帮朋友做了个 比价 的小项目,主要是为了练手 Vue 及相关网站开发. 主要功能: 批量查询产品对应的京东价格 手动根据京东价格调整批发价格 将产品及价格信息,以网页形式分享出去 由于是私人项目 ...

  9. c语言为什么要建项目,一个C语言小项目为什么都说牛逼

    原标题:一个C语言小项目为什么都说牛逼 意在鼓励C语言学者.更有兴趣,学习更富有创业和乐趣! 推荐加学习交流群:658807522 可以在一起学习交流,既是参赛选手,又是学者,也可以先学习再参赛,反正 ...

最新文章

  1. Lowest Common Ancestor of a Binary Search Tree(树中两个结点的最低公共祖先)
  2. C# 视频监控系列(11):H264播放器——封装API[HikPlayM4.dll]
  3. 反应器组件 ACE_Reactor
  4. gis地图和普通地图的区别_GIS之如何添加WMTS地图
  5. 生成报告配置xml_升职加薪利器:Python+Pytest框架在Jenkins上生成Allure测试报告
  6. 微软CEO:人工智能应该帮助而非取代劳动者
  7. 使用Nacos配置中心云端化本地application.properties
  8. javascript基础知识(13) Date
  9. [error]:启用sqlserver配置管理器异常,内存不足
  10. psycopg2 (python与postgresql)
  11. verilog 3段式状态机
  12. 完美解决office07或2010安装错误1706
  13. 一文掌握多分类logistic回归
  14. 建模教程_Zbrush沼泽猎人角色制作教程
  15. .NET 数组之间进行转换 Array.ConvertAll
  16. JavaScript 设置放大镜效果
  17. java将图片均匀分成9份,怎样把一张图片快速切成平均等分/切图? - 杂谈
  18. 基于S7-300 PLC组态王组态的锅炉燃烧控制系统的设计
  19. Go 中的 error 居然可以这样封装
  20. 用c++做一个简单的计算器

热门文章

  1. piaget读法_这些名表的发音 你都读对了吗?(内含音频)
  2. JavaWeb - jQuery
  3. 年入几十万的美国程序员:工资涨不过物价 都不敢叫外卖点奶茶
  4. 关于C++语言的发展前景
  5. 快讯 I 金秋武汉,共话“区块链+:创新驱动变革”主题沙龙(附PPT)
  6. 向量,标量对向量求导数
  7. 2019.9.2 耀中国际学校 初级汉语 班
  8. 干货 | 携程 SOA 的 Service Mesh 架构落地
  9. 大量拼多多快递物流怎么批量跟踪查询?
  10. 猴子选大王问题(Monkey King)