java实现日记软件代码 Java 实现日记软件
用java写的日历记事本代码?
详细代码
让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:空间域名、雅安服务器托管、营销软件、网站建设、宁都网站维护、网站推广。
//CalendarWindow类:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class CalendarWindow extends JFrame implements ActionListener,
MouseListener,FocusListener{
int year,month,day;
CalendarMessage calendarMessage;
CalendarPad calendarPad;
NotePad notePad;
JTextField showYear,showMonth;
JTextField [] showDay;
CalendarImage calendarImage;
Clock clock;
JButton nextYear,previousYear,nextMonth,previousMonth;
JButton saveDailyRecord,deleteDailyRecord,readDailyRecord;
File dir;
Color backColor=Color.gray;
public CalendarWindow(){
dir=new File("./dailyRecord");
dir.mkdir();
showDay=new JTextField[42];
for(int i=0;ishowDay.length;i++){
showDay[i]=new JTextField();
showDay[i].setBackground(backColor);
showDay[i].setLayout(new GridLayout(3,3));
showDay[i].addMouseListener(this);
showDay[i].addFocusListener(this);
}
calendarMessage=new CalendarMessage();
calendarPad=new CalendarPad();
notePad=new NotePad();
Calendar calendar=Calendar.getInstance();
calendar.setTime(new Date());
year=calendar.get(Calendar.YEAR);
month=calendar.get(Calendar.MONTH)+1;
day=calendar.get(Calendar.DAY_OF_MONTH);
calendarMessage.setYear(year);
calendarMessage.setMonth(month);
calendarMessage.setDay(day);
calendarPad.setCalendarMessage(calendarMessage);
calendarPad.setShowDayTextField(showDay);
notePad.setShowMessage(year,month,day);
calendarPad.showMonthCalendar();
doMark(); //给有日志的号码做标记,见后面的doMark()方法
calendarImage=new CalendarImage();
calendarImage.setImageFile(new File("sea.jpg"));
clock=new Clock();
JSplitPane splitV1=
new JSplitPane(JSplitPane.VERTICAL_SPLIT,calendarPad,calendarImage);
JSplitPane splitV2=
new JSplitPane(JSplitPane.VERTICAL_SPLIT,notePad,clock);
JSplitPane splitH=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,splitV1,splitV2);
add(splitH,BorderLayout.CENTER);
showYear=new JTextField(""+year,6);
showYear.setFont(new Font("TimesRoman",Font.BOLD,12));
showYear.setHorizontalAlignment(JTextField.CENTER);
showMonth=new JTextField(" "+month,4);
showMonth.setFont(new Font("TimesRoman",Font.BOLD,12));
showMonth.setHorizontalAlignment(JTextField.CENTER);
nextYear=new JButton("下年");
previousYear=new JButton("上年");
nextMonth=new JButton("下月");
previousMonth=new JButton("上月");
nextYear.addActionListener(this);
previousYear.addActionListener(this);
nextMonth.addActionListener(this);
previousMonth.addActionListener(this);
showYear.addActionListener(this);
JPanel north=new JPanel();
north.add(previousYear);
north.add(showYear);
north.add(nextYear);
north.add(previousMonth);
north.add(showMonth);
north.add(nextMonth);
add(north,BorderLayout.NORTH);
saveDailyRecord=new JButton("保存日志") ;
deleteDailyRecord=new JButton("删除日志");
readDailyRecord=new JButton("读取日志");
saveDailyRecord.addActionListener(this);
deleteDailyRecord.addActionListener(this);
readDailyRecord.addActionListener(this);
JPanel pSouth=new JPanel();
pSouth.add(saveDailyRecord);
pSouth.add(deleteDailyRecord);
pSouth.add(readDailyRecord);
add(pSouth,BorderLayout.SOUTH);
setVisible(true);//根据参数 b 的值显示或隐藏此 Window
setBounds(60,60,660,480);
validate();//验证此容器及其所有子组件
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置用户在此窗体上发起 "close" 时默认执行的操作
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==nextYear){
year++;
showYear.setText(""+year);
calendarMessage.setYear(year);
calendarPad.setCalendarMessage(calendarMessage);
calendarPad.showMonthCalendar();
notePad.setShowMessage(year,month,day);
doMark();
}
else if(e.getSource()==previousYear){
year--;
showYear.setText(""+year);
calendarMessage.setYear(year);
calendarPad.setCalendarMessage(calendarMessage);
calendarPad.showMonthCalendar();
notePad.setShowMessage(year,month,day);
doMark();
}
else if(e.getSource()==nextMonth){
month++;
if(month12) month=1;
showMonth.setText(" "+month);
calendarMessage.setMonth(month);
calendarPad.setCalendarMessage(calendarMessage);
calendarPad.showMonthCalendar();
notePad.setShowMessage(year,month,day);
doMark();
}
else if(e.getSource()==previousMonth){
month--;
if(month1) month=12;
showMonth.setText(" "+month);
calendarMessage.setMonth(month);
calendarPad.setCalendarMessage(calendarMessage);
calendarPad.showMonthCalendar();
notePad.setShowMessage(year,month,day);
doMark();
}
else if(e.getSource()==showYear){
String s=showYear.getText().trim();
char a[]=s.toCharArray();
boolean boo=false;
for(int i=0;ia.length;i++)
if(!(Character.isDigit(a[i])))
boo=true;
if(boo==true) //弹出“警告”消息对话框
JOptionPane.showMessageDialog(this,"您输入了非法年份","警告", JOptionPane.WARNING_MESSAGE);
else if(boo==false)
year=Integer.parseInt(s);
showYear.setText(""+year);
calendarMessage.setYear(year);
calendarPad.setCalendarMessage(calendarMessage);
calendarPad.showMonthCalendar();
notePad.setShowMessage(year,month,day);
doMark();
}
else if(e.getSource()==saveDailyRecord){
notePad.save(dir,year,month,day);
doMark();
}
else if(e.getSource()==deleteDailyRecord){
notePad.delete(dir,year,month,day);
doMark();
}
else if(e.getSource()==readDailyRecord)
notePad.read(dir,year,month,day);
}
public void mousePressed(MouseEvent e){
JTextField text=(JTextField)e.getSource();
String str=text.getText().trim();
try{ day=Integer.parseInt(str);
}
catch(NumberFormatException exp){
}
calendarMessage.setDay(day);
notePad.setShowMessage(year,month,day);
}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void focusGained(FocusEvent e){
Component com=(Component)e.getSource();
com.setBackground(Color.red);
}
public void focusLost(FocusEvent e){
Component com=(Component)e.getSource();
com.setBackground(backColor);
}
public void doMark(){
for(int i=0;ishowDay.length;i++){
showDay[i].removeAll();
String str=showDay[i].getText().trim();
try{
int n=Integer.parseInt(str);
if(isHaveDailyRecord(n)==true){ //见后面的isHaveDailyRecord()方法
JLabel mess=new JLabel("存");
mess.setFont(new Font("TimesRoman",Font.PLAIN,11));
mess.setForeground(Color.black) ;
showDay[i].add(mess);
} }
catch(Exception exp){}
}
calendarPad.repaint();
calendarPad.validate();
}
public boolean isHaveDailyRecord(int n){
String key=""+year+""+month+""+n;
String [] dayFile=dir.list();
boolean boo=false;
for(int k=0;kdayFile.length;k++){
if(dayFile[k].equals(key+".txt")){
boo=true;
break;
} }
return boo;
}
public static void main(String args[]){
new CalendarWindow();
}
}
//CalendarPad类:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class CalendarPad extends JPanel{
int year,month,day;
CalendarMessage calendarMessage;
JTextField [] showDay;
JLabel title[];
String [] 星期={"SUN/日","MON/一","TUE/二","WED/三","THU/四","FRI/五","SAT/六"};
JPanel north,center;
public CalendarPad(){
setLayout(new BorderLayout());
north=new JPanel();
north.setLayout(new GridLayout(1,7));
center=new JPanel();
center.setLayout(new GridLayout(6,7));
add(center,BorderLayout.CENTER);
add(north,BorderLayout.NORTH);
title=new JLabel[7];
for(int j=0;j7;j++){
title[j]=new JLabel();
title[j].setFont(new Font("TimesRoman",Font.BOLD,12));
title[j].setText(星期[j]);
title[j].setHorizontalAlignment(JLabel.CENTER);
title[j].setBorder(BorderFactory.createRaisedBevelBorder());
north.add(title[j]);
}
title[0].setForeground(Color.red);
title[6].setForeground(Color.blue);
}
public void setShowDayTextField(JTextField [] text){
showDay=text;
for(int i=0;ishowDay.length;i++){
showDay[i].setFont(new Font("TimesRoman",Font.BOLD,15));
showDay[i].setHorizontalAlignment(JTextField.CENTER);
showDay[i].setEditable(false);
center.add(showDay[i]);
}
}
public void setCalendarMessage(CalendarMessage calendarMessage){
this.calendarMessage=calendarMessage;
}
public void showMonthCalendar(){
String [] a=calendarMessage.getMonthCalendar();
for(int i=0;i42;i++)
showDay[i].setText(a[i]);
validate();
}
}
用java编写一个“我的日记”的界面并使其实现写日记的功能, 最好含有登陆界面的
代码如下,自己测试哦
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
import javax.swing.JColorChooser;
class Diary extends JFrame implements ActionListener,TreeSelectionListener{
JMenuBar menubar;
JMenu menu1,menu2,menu3,menu4,menu5,menu6;
JMenuItem item1,item2,item3,item4,item5,item6,item7,item8,item52,item61,item62,item63,item64;
JTextArea text=new JTextArea(20,40);
JButton b_save=new JButton("保存日志");
JButton b_del=new JButton("删除日志");
JButton b3=new JButton("锁定日志");
JButton b4=new JButton("解除锁定");
JSplitPane split1,split2;
JScrollPane scroll1,scroll2;
JPanel p;
JTree tree=null;
int i=0;
DefaultMutableTreeNode root;
DefaultMutableTreeNode month[]=new DefaultMutableTreeNode[13];
Diary(){
final JFrame frame = this;
menubar=new JMenuBar();
menu4=new JMenu("登陆");
item6=new JMenuItem("密码登陆");
menu4.add(item6);
menubar.add(menu4);
menu1=new JMenu("文件");
item1=new JMenuItem("新建");
item2=new JMenuItem("退出");
menu1.add(item1);
menu1.add(item2);
menubar.add(menu1);
menu2=new JMenu("编辑");
item3=new JMenuItem("复制");
item4=new JMenuItem("剪切");
item5=new JMenuItem("粘贴");
item52=new JMenuItem("全选");
menu2.add(item3);
menu2.add(item4);
menu2.add(item5);
menu2.add(item52);
menubar.add(menu2);
menu3=new JMenu("设置");
//item6=new JMenuItem("密码设置");
item63=new JMenuItem("设置字体颜色");
item64=new JMenuItem("设置背景颜色");
item61=new JMenuItem("锁定编辑区");
item62=new JMenuItem("解除锁定");
//menu3.add(item6);
menu3.add(item63);
menu3.add(item64);
menu3.add(item61);
menu3.add(item62);
menubar.add(menu3);
menu4=new JMenu("查看");
item7=new JMenuItem("状态栏");
menu4.add(item7);
menubar.add(menu4);
menu5=new JMenu("帮助");
item8=new JMenuItem("我的日记本信息");
menu5.add(item8);
menubar.add(menu5);
setJMenuBar(menubar); //把菜单条添加到窗口顶端
Container con=getContentPane(); //调用getContentPane()方法获的内容面板
root=new DefaultMutableTreeNode("日历记事本"); //结合树的输入与输出建立一个日历记事本
for(i=1;i=12;i++)
{
month[i]=new DefaultMutableTreeNode(""+i+"月");
root.add(month[i]);
}
for(i=1;i=12;i++)
{
if(i==1||i==3||i==5||i==7||i==8||i==10||i==12)
{
for(int j=1;j=31;j++)
month[i].add(new DefaultMutableTreeNode(j+"日"));
}
else if(i==4||i==6||i==9||i==11)
{
for(int j=1;j=30;j++)
month[i].add(new DefaultMutableTreeNode(j+"日"));
}
else
{
for(int j=1;j=28;j++)
month[i].add(new DefaultMutableTreeNode(j+"日"));
}
}
tree=new JTree(root);
p=new JPanel(); //使用JPanel创建一个面板
p.add(b_save);p.add(b_del);p.add(b3);p.add(b4); //把这4个按钮组件假如面板中
scroll1=new JScrollPane(text,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); //把文本框放入滚动窗格中
b_save.addActionListener((ActionListener) this); //按钮的监听器
b_del.addActionListener((ActionListener) this);
scroll2=new JScrollPane(tree);
split1=new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,p,scroll1); //水平拆分这4个按钮和文本区
split2=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,scroll2,split1); //竖直拆分树行日历和文本按钮区
item1.addActionListener((ActionListener) this); //菜单栏的监听器
item2.addActionListener((ActionListener) this);
item3.addActionListener((ActionListener) this);
item4.addActionListener((ActionListener) this);
item5.addActionListener((ActionListener) this);
item6.addActionListener((ActionListener) this);
item7.addActionListener((ActionListener) this);
item8.addActionListener((ActionListener) this);
item52.addActionListener((ActionListener) this);
item61.addActionListener((ActionListener) this);
item62.addActionListener((ActionListener) this);
item63.addActionListener((ActionListener) this);
tree.addTreeSelectionListener((TreeSelectionListener) this); //树形日历的监听器
con.setLayout(new FlowLayout()); //设置布局
setSize(600,500); //设置窗体的大小
Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screen.width-300)/2,(screen.height-220)/2);
setResizable(false); //设置窗口不可以调节大小
setVisible(true); //设置窗口为可视
con.add(split2); //把树形日历和按钮,文本区都加入到内容面板中
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //单击关闭图标后关闭窗口
}
public void valueChanged(TreeSelectionEvent e) //处理树形事件的接口
{
text.setText(null);
if(e.getSource()==tree)
{
DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
if(node.isLeaf())
{
String str=node.toString();
for( i=0;i=12;i++)
{
if(node.getParent()==month[i])
{
try{String temp=null;
File f=new File(node.getParent().toString()+str+".text");
FileReader file=new FileReader(f);
BufferedReader in=new BufferedReader(file);
while((temp=in.readLine())!=null)
text.append(temp+'\n');
file.close();
in.close();
}
catch(Exception el){}
}
}
}
}
}
//}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b_save) //保存按钮的实现方法
{
DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
String str=node.toString();
if(node.isLeaf())
{
try{
File f=new File(node.getParent().toString()+str+".text");
FileWriter tofile=new FileWriter(f);
BufferedWriter out=new BufferedWriter(tofile);
out.write(text.getText(),0,(text.getText()).length());
out.flush();
tofile.close(); out.close();
}
catch(Exception el){}
}
}
else if(e.getSource()==b_del)
{
int n=JOptionPane.showConfirmDialog(this, "该文件还没有保存,确定要删除吗?","确认对话框", JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
String str=node.toString();
if(node.isLeaf())
{
File f=new File(node.getParent().toString()+str+".text");
f.delete();
}
}
else if(n==JOptionPane.NO_OPTION)
{
System.exit(0);
}
}
else if(e.getSource()==b3)
{
text.setEditable(false);
}
else if(e.getSource()==b4)
{
text.setEditable(true);
}
String selected=e.getActionCommand(); //获取命令
if(selected.equals("退出")){ //执行"退出"命令
dispose();
}
else if(selected.equals("新建")){
text.setText("");
}
else if(selected.equals("复制"))
{
text.copy();
}
else if(selected.equals("剪切"))
{
text.cut();
}
else if(selected. equals("粘贴"))
{
text.paste();
}
else if(selected.equals("全选"))
{
text.selectAll();
}
else if(selected.equals("密码登陆"))
{
LoginWindow login=new LoginWindow();
}
else if(selected.equals("设置字体颜色")){
Color newColor=JColorChooser.showDialog(this, "选择字体颜色", text.getForeground());
if(newColor !=null)
{
text.setForeground(newColor);
}
}
else if(selected.equals("设置背景颜色"))
{
Color newColor=JColorChooser.showDialog(this, "选择背景颜色", text.getBackground());
if(newColor !=null)
{
text.setBackground(newColor);
}
}
else if(selected.equals("锁定编辑区"))
{
text.setEditable(false);
}
else if(selected.equals("解除锁定"))
{
text.setEditable(true);
}
}
}
class LoginWindow extends JFrame implements ActionListener {
JPanel p1=new JPanel(); //定义并建立面板
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JPanel p4=new JPanel();
JPanel p5=new JPanel();
JTextField text1=new JTextField(15); //用户名文本框
JPasswordField text2=new JPasswordField(15); //密码域
JButton ok=new JButton("确定");
JButton cancel=new JButton("取消");
LoginWindow()
{
setBackground(Color.DARK_GRAY); //设置背景颜色
Container con=getContentPane(); //取出内容面板
con.setLayout(new GridLayout(5,1)); //设置布局为5行1列
p2.add(new JLabel("用户名:"));p2.add(text1); //将组件添加到中间容器
p3.add(new JLabel("密码"));p3.add(text2);
p4.add(ok);p4.add(cancel);
ok.addActionListener(this); //注册事件监听器
cancel.addActionListener(this);
text1.addActionListener(this);
text2.addActionListener(this);
con.add(p1); con.add(p2); con.add(p3); con.add(p4); con.add(p5); //将面板添加到内容面板
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //单击关闭图标后关闭窗口
setSize(300,220); //设置窗口的大小
Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screen.width-300)/2,(screen.height-220)/2);
setTitle("登录窗口");
setResizable(false); // 不让用户改变窗口大小
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==ok||e.getSource()==text2){
if(text1.getText().trim().equals("meijianwen") text2.getText().trim().equals("070341320")){
dispose(); //关闭登陆窗口
}
else{
JOptionPane.showMessageDialog(null, "用户名或密码错误!");
text1.requestFocus(); //设置焦点
text1.setSelectionStart(0); //设置选中文本开始位置
text1.setSelectionEnd(text1.getText().length());
}
}
else if(e.getSource()==cancel){ //单击取消按钮
dispose();
//System.exit(0);
}
else if(e.getSource()==text1) //在用户名文本框按回车焦点移到密码域
text2.requestFocus();
}
}
public class MyDiary
{
public static void main(String args[])
{
JFrame.setDefaultLookAndFeelDecorated(true);
Font font=new Font("JFrame",Font.PLAIN,14); //定义字体
Enumeration keys=UIManager.getLookAndFeelDefaults().keys(); //枚举风格关键字
while(keys.hasMoreElements())
{
Object key=keys.nextElement();
// if(((String)key).equals("Menu.foreground")||((String)key).equals("MenuItem.foreground"))
// UIManager.put(key,Color.DARK_GRAY); //设置菜单文字颜色
if(UIManager.get(key)instanceof Font)UIManager.put(key,font);
}
Diary win=new Diary();
win.validate();
}
}
java日记本源代码
晚上,已经快九点钟了,我看了会儿电视,肚子饿得“咕咕”直叫,于是我对妈妈说:“我饿了。”妈妈说:“想吃些什么呢?”我想了想说:“那就吃点面条吧。”
“自己也十岁了,该做点事情了。”妈妈对我说。
于是我来到厨房自己下面条吃。我先放了半锅水,然后把锅放在煤气灶上烧,蓝色的炉火很快把水烧开了。打开锅盖,一股热所直扑我的脸,锅里的水上下翻滚。
我用勺子小心翼翼地打了点开水倒进碗里,然后抓一把干面放进锅里烧,再用筷子轻轻地翻一翻。趁锅里在煮面条的时候,我往碗里放作料把猪油、葱花、味精、酱油放进碗里 。眨眼工夫,只见锅里边一层白沫慢慢往外溢。我知道面已经熟了,就关掉了煤气灶,把面条装进碗里,再用筷子拌一拌就可以吃了。
用Java编写简易记事本源代码
importjava.awt.BorderLayout;importjava.awt.Container;importjava.awt.Font;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.InputEvent;importjava.awt.event.KeyAdapter;importjava.awt.event.KeyEvent;importjava.awt.event.MouseAdapter;importjava.awt.event.MouseEvent;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;importjavax.swing.BorderFactory;importjavax.swing.JFileChooser;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JMenu;importjavax.swing.JMenuBar;importjavax.swing.JMenuItem;importjavax.swing.JOptionPane;importjavax.swing.JPopupMenu;importjavax.swing.JScrollPane;importjavax.swing.JTextArea;importjavax.swing.KeyStroke;importjavax.swing.ScrollPaneConstants;importjavax.swing.SwingConstants;publicclassJNotePadUIextendsJFrame{privateJMenuItemmenuOpen;privateJMenuItemmenuSave;privateJMenuItemmenuSaveAs;privateJMenuItemmenuClose;privateJMenueditMenu;privateJMenuItemmenuCut;privateJMenuItemmenuCopy;privateJMenuItemmenuPaste;privateJMenuItemmenuAbout;privateJTextAreatextArea;privateJLabelstateBar;privateJFileChooserfileChooser;privateJPopupMenupopUpMenu;publicJNotePadUI(){super("新建文本文件");setUpUIComponent();setUpEventListener();setVisible(true);}privatevoidsetUpUIComponent(){setSize(640,480);//菜单栏JMenuBarmenuBar=newJMenuBar();//设置「文件」菜单JMenufileMenu=newJMenu("文件");menuOpen=newJMenuItem("打开");//快捷键设置menuOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));menuSave=newJMenuItem("保存");menuSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));menuSaveAs=newJMenuItem("另存为");menuClose=newJMenuItem("关闭");menuClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,InputEvent.CTRL_MASK));fileMenu.add(menuOpen);fileMenu.addSeparator();//分隔线fileMenu.add(menuSave);fileMenu.add(menuSaveAs);fileMenu.addSeparator();//分隔线fileMenu.add(menuClose);//设置「编辑」菜单JMenueditMenu=newJMenu("编辑");menuCut=newJMenuItem("剪切");menuCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));menuCopy=newJMenuItem("复制");menuCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK));menuPaste=newJMenuItem("粘贴");menuPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));editMenu.add(menuCut);editMenu.add(menuCopy);editMenu.add(menuPaste);//设置「关于」菜单JMenuaboutMenu=newJMenu("关于");menuAbout=newJMenuItem("关于JNotePad");aboutMenu.add(menuAbout);menuBar.add(fileMenu);menuBar.add(editMenu);menuBar.add(aboutMenu);setJMenuBar(menuBar);//文字编辑区域textArea=newJTextArea();textArea.setFont(newFont("宋体",Font.PLAIN,16));textArea.setLineWrap(true);JScrollPanepanel=newJScrollPane(textArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);ContainercontentPane=getContentPane();contentPane.add(panel,BorderLayout.CENTER);//状态栏stateBar=newJLabel("未修改");stateBar.setHorizontalAlignment(SwingConstants.LEFT);stateBar.setBorder(BorderFactory.createEtchedBorder());contentPane.add(stateBar,BorderLayout.SOUTH);popUpMenu=editMenu.getPopupMenu();fileChooser=newJFileChooser();}privatevoidsetUpEventListener(){//按下窗口关闭钮事件处理addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){closeFile();}});//菜单-打开menuOpen.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){openFile();}});//菜单-保存menuSave.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){saveFile();}});//菜单-另存为menuSaveAs.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){saveFileAs();}});//菜单-关闭文件menuClose.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){closeFile();}});//菜单-剪切menuCut.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){cut();}});//菜单-复制menuCopy.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){copy();}});//菜单-粘贴menuPaste.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){paste();}});//菜单-关于menuAbout.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){//显示对话框JOptionPane.showOptionDialog(null,"程序名称:\nJNotePad\n"+"程序设计:\n\n"+"简介:\n一个简单的文字编辑器\n"+"可作为验收Java的实现对象\n"+"欢迎网友下载研究交流\n\n"+"/","关于JNotePad",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null,null,null);}});//编辑区键盘事件textArea.addKeyListener(newKeyAdapter(){publicvoidkeyTyped(KeyEvente){processTextArea();}});//编辑区鼠标事件textArea.addMouseListener(newMouseAdapter(){publicvoidmouseReleased(MouseEvente){if(e.getButton()==MouseEvent.BUTTON3)popUpMenu.show(editMenu,e.getX(),e.getY());}publicvoidmouseClicked(MouseEvente){if(e.getButton()==MouseEvent.BUTTON1)popUpMenu.setVisible(false);}});}privatevoidopenFile(){if(isCurrentFileSaved()){//文件是否为保存状态open();//打开}else{//显示对话框intoption=JOptionPane.showConfirmDialog(null,"文件已修改,是否保存?","保存文件?",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null);switch(option){//确认文件保存caseJOptionPane.YES_OPTION:saveFile();//保存文件break;//放弃文件保存caseJOptionPane.NO_OPTION:open();break;}}}privatebooleanisCurrentFileSaved(){if(stateBar.getText().equals("未修改")){returnfalse;}else{returntrue;}}privatevoidopen(){//fileChooser是JFileChooser的实例//显示文件选取的对话框intoption=fileChooser.showDialog(null,null);//使用者按下确认键if(option==JFileChooser.APPROVE_OPTION){try{//开启选取的文件BufferedReaderbuf=newBufferedReader(newFileReader(fileChooser.getSelectedFile()));//设定文件标题setTitle(fileChooser.getSelectedFile().toString());//清除前一次文件textArea.setText("");//设定状态栏stateBar.setText("未修改");//取得系统相依的换行字符StringlineSeparator=System.getProperty("line.separator");//读取文件并附加至文字编辑区Stringtext;while((text=buf.readLine())!=null){textArea.append(text);textArea.append(lineSeparator);}buf.close();}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"开启文件失败",JOptionPane.ERROR_MESSAGE);}}}privatevoidsaveFile(){//从标题栏取得文件名称Filefile=newFile(getTitle());//若指定的文件不存在if(!file.exists()){//执行另存为saveFileAs();}else{try{//开启指定的文件BufferedWriterbuf=newBufferedWriter(newFileWriter(file));//将文字编辑区的文字写入文件buf.write(textArea.getText());buf.close();//设定状态栏为未修改stateBar.setText("未修改");}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"写入文件失败",JOptionPane.ERROR_MESSAGE);}}}privatevoidsaveFileAs(){//显示文件对话框intoption=fileChooser.showSaveDialog(null);//如果确认选取文件if(option==JFileChooser.APPROVE_OPTION){//取得选择的文件Filefile=fileChooser.getSelectedFile();//在标题栏上设定文件名称setTitle(file.toString());try{//建立文件file.createNewFile();//进行文件保存saveFile();}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"无法建立新文件",JOptionPane.ERROR_MESSAGE);}}}privatevoidcloseFile(){//是否已保存文件if(isCurrentFileSaved()){//释放窗口资源,而后关闭程序dispose();}else{intoption=JOptionPane.showConfirmDialog(null,"文件已修改,是否保存?","保存文件?",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null);switch(option){caseJOptionPane.YES_OPTION:saveFile();break;caseJOptionPane.NO_OPTION:dispose();}}}privatevoidcut(){textArea.cut();stateBar.setText("已修改");popUpMenu.setVisible(false);}privatevoidcopy(){textArea.copy();popUpMenu.setVisible(false);}privatevoidpaste(){textArea.paste();stateBar.setText("已修改");popUpMenu.setVisible(false);}privatevoidprocessTextArea(){stateBar.setText("已修改");}publicstaticvoidmain(String[]args){newJNotePadUI();}}
新闻名称:java实现日记软件代码 Java 实现日记软件
网站地址:http://pwwzsj.com/article/hjdsid.html