首页 > 文库大全 > 精品范文库 > 1号文库

Java上机实验报告

Java上机实验报告



第一篇:Java上机实验报告

Homework3实验报告

一、实验目的与要求

1、掌握Java中类和接口的基本知识;

2、继承的基本知识;

3、集合的基本操作

二、实验内容 1.PIMCollection 类

创建一个可以管理PIMEntities实体的集合,该类实现了Collection接口,且必须实现了以下方法:(1).getNotes();返回PIMCollection中所有的PIMNote项,如果不包含PIMNote项,则返回一个空集合

(2).getTodos();返回集合PIMCollection中所有的PIMTodo项,如果不包含PIMTodo项,则返回一个空集合

(3).getAppointment();返回集合PIMCollection中所有的PIMAppointment项,如果不包含PIMAppointment项。则返回一个空集合(4).getContacts();返回结合PIMCollection中所有的PIMContact项,如果不包含PIMContact项,则返回一个空集合

(5).getItemsForDate(Date d);返回集合PIMCollection中所有与d匹配的PIMEntities,如果没有匹配d的项,则返回一个空集合

(只有PIMTodo和PIMAppointment项,因为PIMNote和PIMContact跟日期没有关系)。

2.TestPIMCollection类(自己的测试类)

向PIMCollection集合类中加入了一些PIMEntity实体类,并用PIMCollection类中实现的方法分别筛选出了其中的PIMNote、PIMTodo、PIMAppointment、PIMContact、符合指定日期d的集合并打印输出。

三、实验器材

计算机+windows操作系统+eclipse

四、实验步骤

1.程序源代码(压缩在文件夹里)2.编译执行程序 3.记录执行结果

五、实验结果

1.TestPIMCollection的测试代码:

2.程序的执行结果:

如图所示:程序分别输出了Todo、Note、Appointment、Contact、以及匹配指定日期的结合的结果。

六、实验小结

1、熟悉了Java集合的基本内容和操作,也包括了泛型的一些知识。

2、通过这个实验巩固了java的基础知识:类和接口的有关知识,继承的应用。

3、掌握了在eclipse下编译执行Java程序的知识。

4、通过几次的编程,熟悉了java的编程规则。

5、综合应用所学知识完成java程序的分析、设计、调试和总结,为以后编写更复杂的java程序打下了很好的基础。

第二篇:上机实验报告格式

请各位同学按照下列格式写:否则按照0分记

上机实验报告格式

Matlab学习第?次上机实验报告(第?次)

姓名:???班级:???上机时间:??????

1.上机内容

2.建模及算法分析

3.程序

4.小结

5.参考文献

将文档发到我的邮箱里面

learn_matlab@163.com

第三篇:上机实验报告

一. 题目1. 建立一个学生档案,内容包括学号,姓名,年龄,性别,数学,物理和英语3门功课成绩。要求实现以下功能:1)数据输入;2)查询某个学生的成绩;3)按平均排列输出;4)统计某门课各分数段人数;5)删除某个学生记录;2. 编程实现对二位数进行加,减,乘运算,每运行一次程序做10道题,完成后给出成绩(每题10分)。二. 设计思想和模块划分1.1.先定义所需要的条件,例如,姓名,学号,性别,三门功课的成绩,平均分等。2.输入姓名,学号,性别,年龄,三门功课的成绩后,就输出相应的姓名,学号,性别,年龄,三门功课的成绩。3.打印表头;4.在求出平均分,并打印出平均分。5.在查找学生,并打印出学生的相关资料;并按照平均分的高低排列;6.在统计学生各科成绩是否》=60分,如果是就是通过,否就是没通过,最后打印出最后的结果。7.删除学生,选中删除的学生,如果确定要,那么该学生的一切记录就变为0;2.1.随机调用函数,产生两个其值为10到99的随机整数分别放在c,d中用作运算时的运算数。2.随机调用函数,产生一个值为1到3 的随机整数放入b中,用来选择不同的运算。根据b的值选择不同的运算。当b=1时,去进行c+d的运算练习;当b=2 时,去进行c-d的运算练习;当b=3时,去进行c×d的运算练习。每完成一个算题就给出是否正确的信息。3.根据答案正确与否统计。正确时,显示’right’;错误时,显示’wrong’。4.步骤1.2.3.4.重复10次。5.输出学生成绩。三. 运行结果1.Input the 1 student :num:03name:wfage:18sex:fmath:98phy:75eng:65Input the 2 student :num:06name:scage:17sex:fmath:78phy:45eng:65Input the 3 student :num:09name:ytage:17sex:mmath:69phy:75eng:501.readin 2.finds 3.del 4.tj 5.exit1-----------------------------table----num name age sex math phy eng ave------3 wf 18 f 98.0 75.0 65.0 79.3------9 yt 17 m 69.0 75.0 50.0 64.7-------6 sc 17 f 78.0 45.0 65.0 62.7-------1.readin 2.finds 3.del 4.tj 5.exit2Into number:3---num name age sex math phy eng ave---3 wf 18 f 98.0 75.0 65.0 79.3----1.readin 2.finds 3.del 4.tj 5.exit3Into number:6---num name age sex math phy eng ave---6 sc 17 f 78.0 45.0 65.0 62.6---true? Y/Ny1----------------table------------------num name age sex math phy eng ave----3 wf 18 f 98.0 75.0 65.0 79.3-----9 yt 17 m 69.0 75.0 50.0 64.7-----0 0 0 f 0.0 0.0 0.0 0.0-----1.readin 2.finds 3.del 4.tj 5.exit4 1.input the math 2.input the phy 3.input the eng 1math: pass num is :3 no pass num is :02.32+82=114right!97*15=1455right!99-58=41right!76-66=10right!58+13=71right!37+49=86right!99+52=151right!49*69=5462wrong!73-38=31wrong!86+34=120right!mark is 80四. 主要错误改正方法1.在本题的编写过程中常出现begin 和end 不配对,只要始它们的个数相同就可以了,就可以了。在程序中常出现的’unknown identifier’没有定义的错误,只要在程序前加上定义,就可以了。还有就是type mismatch’的类型不匹配,只要根据前后内容,重新定义,就可以了。2.在本题编写中,题目要求是两个两位数运算,如果写成c:=random(100)在运行过程中,就会出现一位数运算,只要把它写成c:=random(90)+10,就可以了。五. 实习小结1.第一题的程序编写比较复杂,需要较多的定义,因而在后面的程序部分,就常出现标识符重复,而导致的类型不匹配。还有就是每个部分编好后,上下不能连接,而无法调用。2.第二题较第一题简单,和书上的例题类似,所以,比较简单,但从中也出现一些不问题。以上两大题中出现的问题,要在同学的帮助下,才能完成。总的来说两题程序比较困难六. 程序清单1.program twins;const m=3;n=3;typestudent=recordnum:integer;name:string[3];age:integer;sex:char;s:array[1..n] of real;math,eng,phy:real;ave:real;end;sarr=array[1..m] of student;ta=array [1..m] of student;f=string[6];varstu:sarr;ct:ta;k,d:integer;procedure readin(var stu:sarr);const wrong='0<=data<=100 ,again!';var j,i:integer;a:student;beginwriteln;writeln('Input ',m,' num name sex math phy eng',' of student.');for j:=1 to m dobeginwriteln;writeln('Input the ',j,' student :');with a dobeginwrite('num:');readln(num);write('name:');readln(name);write('age:');readln(age);write('sex:');readln(sex);while(sex<>'m')and(sex<>'f')dobeginwrite('sex:');readln(sex)end;for i:=1 to n do begincase i of1:begin write('math:');readln(s[i]);while(s[i]<0)or(s[i]>100)dobeginwriteln(wrong);write('math:');readln(s[i]);end;end;2:begin write('phy:');readln(s[i]);while(s[i]<0)or(s[i]>100)dobeginwriteln(wrong);write('phy:');readln(s[i]);end;end;3:begin write('eng:');readln(s[i]);while(s[i]<0)or(s[i]>100)dobeginwriteln(wrong);write('eng:');readln(s[i]);end;end;end;end;stu[j]:=a;end;writeln;end;end;procedure ave(var stu:sarr);var j,i:integer;k:real;beginfor j:=1 to m dobegink:=0;with stu[j] dobeginfor i:=1 to n do k:=k+s[i];ave:=k/nend;end;end;procedure px(var stu:sarr);var tm:ta;j,i,p:integer;beginfor j:=1 to m dobeginp:=j;for i:=j+1 to m doif stu[i].ave>stu[p].ave then p:=i;tm[1]:=stu[p];stu[p]:=stu[j];stu[j]:=tm[1];end;end;procedure head(ct:ta);var i:integer;beginwrite(' ');for i:=1 to 72 do write('-');writeln;write('',' num':4,' ','name':9,' ','age':8,' ','sex':5,' ','math':6,' ','phy':9,' ','eng':8,' ');writeln('ave':6,' ');write(' ');for i:=1 to 72 do write('-');writeln;with ct[1] dobeginwrite('',num:7,' ',name:8,' ',age:8,' ',sex:5,' ');for i:=1 to n do write(s[i]:7,' ');write(ave:10,' ');writeln;end;write(' ');for i:=1 to 72 do write('-');writeln;end;procedure find(var stu:sarr);var n,i:integer;u:boolean;beginu:=true;while u dobeginwrite('Into number:');readln(n);for i:=1 to m dobeginif stu[i].num=n then beginct[1]:=stu[i];u:=false;d:=iend;end;end;end;procedure del(var stu:sarr);var i:integer;b:char;beginhead(ct);write('true? Y/N');readln(b);if b='y' then begin write('1');with stu[d] dobeginnum:=0;name:='0';age:=0;sex:='f';for i:=1 to n do s[i]:=0;ave:=0end;endelseend;procedure tj(var stu:sarr);var w1,q1,q2,num,j:integer;h1,h2,h3:boolean;beginh1:=false;h2:=false;h3:=false;q1:=0;q2:=0;writeln(' ':30,'1.input the math 2.input the phy 3.input the eng ');readln(w1);case w1 of1:h1:=true;2:h2:=true;3:h3:=true;end;if h1 thenbeginbeginfor j:=1 to m dowith stu[j] doif stu[j].math>=60 thenq1:=q1+1elseq2:=q2+1;writeln('math:');end;if h2 thenbeginbeginfor j:=1 to m dowith stu[j] doif stu[j].phy>=60 thenq1:=q1+1elseq2:=q2+1;writeln('phy:');end;if h3 thenbeginbeginfor j:=1 to m dowith stu[j] doif stu[j].eng>=60 thenq1:=q1+1elseq2:=q2+1;writeln('eng:');end;end;end;end;writeln(' ':5,'pass num is :',q1);writeln(' ':5,'no pass num is :',q2);end;procedure head1(var stu:sarr);var j,i:integer;beginwriteln('----------------table--------------':60);writeln;write(' ');for i:=1 to 72 do write('-');writeln;write('',' num':4,' ','name':9,' ','age':8,' ','sex':5,' ','math':6,' ','phy':9,' ','eng':8,' ');writeln('ave':6,' ');write(' ');for i:=1 to 72 do write('-');writeln;for j:=1 to m do beginwith stu[j] dobeginwrite('',num:7,' ',name:8,' ',age:8,' ',sex:5,' ');for i:=1 to n do write(s[i]:7:1,' ');write(ave:10:1,' ');writeln;end;write(' ');for i:=1 to 72 do write('-');writeln;end;end;beginreadin(stu);ave(stu);k:=0;while k<>5 dobeginwriteln('1.readin 2.finds 3.del 4.tj 5.exit');read(k);readln;while(k<>1)and(k<>2)and(k<>3)and(k<>4)and(k<>5)dobeginwriteln(' mistake,please again');read(k)end;case k of1: begin px(stu);head1(stu)end;2: begin find(stu);head(ct)end;3: begin find(stu);del(stu);px(stu);head1(stu)end;4: begin tj(stu);end;5: writeln('exit!');end;end;end..2.program shadow;var a,b,c,d,e:integer;right:boolean;procedure s1;beginwriteln('right!');right:=trueend;procedure s2;beginwriteln('wrong!');right:=falseend;procedure s3(x,y:integer);var h:integer;beginwrite(x,'+',y,'=');readln(h);if h=x+y then s1else s2 end;procedure s4(x,y:integer);var h,w:integer;beginif x

第四篇:java上机实验

1、实验一:多线程程序设计:炮打飞机

实验目的:学会使用多线程进行并发程序设计

实验内容:编写一个应用程序模拟大炮打飞机。在GUI界面上,飞机水平飞行,用界面上的按钮控制大炮的运行方向(如向左,向右,向上,向下)。当炮弹碰着飞机后,飞机坠落。

2、实验二:数据库编程:书目信息管理

实验目的:掌握数据库编程技术。能正确连接数据库,能对数据库中信息进行查询、插

入、删除、修改。

实验内容:在数据库中创建一张书目信息表,包括书名、作者、出版社、出版日期、书

号、价格字段。设计一个GUI界面进行书目管理。在该界面上有四个选项卡,分别是查询、插入、删除、修改。点击查询选项卡,出现的界面上有书名、作者、出版社、书号四个文本框,一个按钮和一个只读文本区。文本框内容可以为空,输入相应的查询信息后(例如根据书名查询可以仅输入书名),点击界面上的“查询”按钮,可以在界面下方的文本区中显示出符合条件的书目详细信息。点击插入选项卡,出现的界面上有书名、作者、出版社、出版日期、书号、价格文本框,一个按钮。在文本框中输入信息后,点击“插入”按钮,该书目信息插入数据库表中。点击删除选项卡,出现的界面上有书名文本框和一个按钮,输入书名后点击“删除”按钮,该书目信息从数据库表中删除。点击修改选项卡,出现的界面上有书名、作者、出版社、出版日期、书号、价格文本框,一个按钮。输入的书名必须是已存在的,否则会弹出消息框显示出错信息。输入信息后,点击“修改”按钮,数据库表中的相应书目信息被修改为新值。

3、实验三:Applet编程:鸭子的移动

实验目的:掌握Applet程序设计的方法,学会在Applet中绘制图片,能采用双缓冲技术进行图片绘制,会在Applet中采用多线程进行动画显示。能在Applet中实现动画的平滑显示,避免闪烁现象。

实验内容:在Applet窗口中显示一只鸭子图片,要求这只鸭子以每秒100帧的速率水平移动,移到窗口边界再返回移动。在窗口中点击鼠标,鸭子停止移动;再次点击鼠标,鸭子恢复移动。

4、实验四:网络编程:聊天室的实现

实验目的:会编写客户端和服务器程序实现C/S模式下的通信,会使用多线程进行网络编程。

实验内容:编写一个聊天室程序:客户端界面请自行设计,可使其具有个性化特征; 可在实现基本的聊天室功能的基础上添加个性化的功能。

第五篇:JAVA实验报告

河北北方学院信息科学与工程学院

《Java程序设计》

实 验 报 告

实验学期 202_ 至 202_ 学年 第 2 学期

学生所在系部 信息科学与工程学院 年级 202_ 专业班级 电子三班 学生姓名 冯洋 学号 201242220 任课教师 实验成绩

实验七 GUI标准组件及事件处理

一、课程设计目的: 《面向对象程序设计》是一门实践性很强的计算机专业基础课程,课程设计是学习完该课程后进行的一次较全面的综合练习。其目的在于通过实践加深学生对面向对象程序设计的理论、方法和基础知识的理解,掌握使用Java语言进行面向对象设计的基本方法,提高运用面向对象知识分析实际问题、解决实际问题的能力,提高学生的应用能力。

二、实验要求:

设计一个简单的文本编辑器,具有如下基本功能: 1)所见即所得的文本输入;

2)能方便地选中文本、复制、删除和插入文本; 3)具有一般编辑器所具有的查找和替换功能;

4)简单的排版,如设置字体和字号等。

三、课程设计说明:

1、需求分析:简单文本编辑器提供给用户基本的纯文本编辑功能,能够将用户录入的文本存储到本地磁盘中。能够读取磁盘中现有的纯文本文件,以及方便用户进行需要的编辑功能。文件操作能够实现新建、保存、打开文档等,编辑操作能过实现文本的剪贴、复制、粘贴等,格式操作能过实现字体设置、背景等,帮助操作能够实现关于主题的查看等功能

2、概要设计:

(一)其基本功能包括:

① 基本的文本操作功能。包括新建,保存,打开,保存。

② 基本的编辑功能。包括复制,剪贴,粘贴。③ 基本的格式功能,字体。④ 简单的帮助,关于主题。

(二)主要的组件包括:

① 基本的Frame框架; ② 菜单;

③ 打开文件对话框; ④ 保存文件对话框; ⑤ 颜色对话框; ⑥ 简单的帮助框架。

3、程序说明:

整个记事本分成:Jframe程序主体框架,Jmenu菜单栏、JtextArea文本输入区、PopupMenu右键菜单、JscrollPane滚动条、FonDialog字体类等。

本程序中首先定义一个Java Yang类继承JFrame作为最底层容器。要想记事本完成需求分析中相应的功能,还必须添加事件监听器。事件监听器不仅要添加在菜单栏和内容输入区,还需加在容器中。本程序中ActListener实现了ActionListener接口,用来监听并处理所有菜单项和内容输入区为事件源的事件。另外,还用来WindowListener来监听处理容器关闭触发的事件,WindowListener继承了WindowsAdapter类并覆盖了WindowsClosing方法。

四、程序调试:

1、调试分析:

(1)关于打开、保存和退出我运用了文件对话框, openFileDialog、saveFileDialog和System.exit()以及文件输入输出流来实现,新建功能我选用了 textArea.setText()方法.(2)对于剪贴,粘贴,复制的实现则用 复制

String text = textArea.getSelectedText();StringSelection selection= new StringSelection(text);clipboard.setContents(selection,null);粘贴

Transferable contents = clipboard.getContents(this);if(contents==null)return;String text;text=“";try { text =(String)contents.getTransferData(DataFlavor.stringFlavor);} catch(Exception ex){ } textArea.replaceRange(text,textArea.getSelectionStart(),textArea.getSelectionEnd());(3)至于字体功能的实现,则是新建了一个字体类,在这个类中设置了字形,字体以及大小并且有字体样式可预览用户当前的设置。FlowLayout()设置布局,setSize()设置大小add()添加需要用的原件。

添加监听器获取选择用户的字号大小

public void itemStateChanged(ItemEvent event){ size =(new Integer((String)event.getItem()).intValue());setCustomFont(new Font(name, type, size));} 设置字体

private void setCustomFont(Font customFont){ this.customFont = customFont;area.setFont(customFont);area.revalidate();} 获取字体

public Font getCustomFont(){ return(this.customFont);}

附录:源代码

//记事本主体类 import java.awt.event.*;import java.awt.*;import java.io.*;import java.awt.datatransfer.*;import javax.swing.*;

import java.awt.print.PrinterException;

public class MiniNote extends JFrame implements ActionListener {

JMenuBar menuBar = new JMenuBar();JMenu file = new JMenu(”文件(F)“), //菜单 edit = new JMenu(”编辑(E)“), format = new JMenu(”格式(O)“), view = new JMenu(”查看(V)“), help = new JMenu(”帮助(H)“);

JMenuItem[] menuItem ={ //菜单下拉项 new JMenuItem(”新建(N)“), new JMenuItem(”打开(O)“), new JMenuItem(”保存(S)“), new JMenuItem(”打印(P)“), new JMenuItem(”全选(A)“), new JMenuItem(”复制(C)“), new JMenuItem(”剪切(T)“), new JMenuItem(”粘贴(P)“), new JMenuItem(”自动换行(W)“), new JMenuItem(”字体(F)“), new JMenuItem(”状态栏(S)“), new JMenuItem(”帮助主题(H)“), new JMenuItem(”关于记事本(A)“), new JMenuItem(”页面设置(U)“), new JMenuItem(”退出(X)“), new JMenuItem(”查找(F)“), new JMenuItem(”查找下一个(N)“), new JMenuItem(”替换(R)“)};

JPopupMenu popupMenu = new JPopupMenu();;//右键菜单 JMenuItem [] menuItem1 ={ new JMenuItem(”撤销(Z)“), new JMenuItem(”剪切(X)“), new JMenuItem(”复制(C)“), new JMenuItem(”粘贴(V)“), new JMenuItem(”删除(D)“), new JMenuItem(”全选(A)“), };

private JTextArea textArea;//文本区域 private JScrollPane js;//滚动条 private JPanel jp;private FileDialog openFileDialog;//打开保存对话框 private FileDialog saveFileDialog;private Toolkit toolKit;//获取默认工具包。private Clipboard clipboard;//获取系统剪切板 private String fileName;//设置默认的文件名

/** * MiniEdit 方法定义 * * 实现记事本初始化 * **/ public MiniNote(){

fileName = ”无标题“;toolKit = Toolkit.getDefaultToolkit();clipboard = toolKit.getSystemClipboard();textArea =new JTextArea();js = new JScrollPane(textArea);jp = new JPanel();openFileDialog = new FileDialog(this,”打开“,FileDialog.LOAD);saveFileDialog = new FileDialog(this,”另存为“,FileDialog.SAVE);

js.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);jp.setLayout(new GridLayout(1,1));jp.add(js);textArea.setComponentPopupMenu(popupMenu);//文本区域添加右键 textArea.add(popupMenu);add(jp);setTitle(”迷你记事本“);setFont(new Font(”Times New Roman“,Font.PLAIN,15));setBackground(Color.white);setSize(800,600);setJMenuBar(menuBar);menuBar.add(file);menuBar.add(edit);menuBar.add(format);menuBar.add(view);menuBar.add(help);for(int i=0;i<4;i++){ file.add(menuItem[i]);edit.add(menuItem[i+4]);} for(int i=0;i<3;++i){ edit.add(menuItem[i+15]);} for(int i=0;i<2;++i){ format.add(menuItem[i+8]);help.add(menuItem[i+11]);} view.add(menuItem[10]);file.add(menuItem[14]);for(int i=0;i<6;++i){ popupMenu.add(menuItem1[i]);}

//窗口监听

addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ e.getWindow().dispose();System.exit(0);} });//注册各个菜单项的事件监听器

for(int i=0;i

Object eventSource = e.getSource();if(eventSource == menuItem[0])//新建动作 { textArea.setText(”“);} else if(eventSource == menuItem[1])//打开动作 { openFileDialog.setVisible(true);fileName = openFileDialog.getDirectory()+openFileDialog.getFile();if(fileName!= null){ openFile(fileName);} } else if(eventSource ==menuItem[2])//保存动作 { saveFileDialog.setVisible(true);fileName = saveFileDialog.getDirectory()+saveFileDialog.getFile();if(fileName!=null){ writeFile(fileName);} } else if(eventSource==menuItem[14])//退出动作 { System.exit(0);} else if(eventSource == menuItem[4]||eventSource == menuItem1[5])//全选动作 { textArea.selectAll();} else if(eventSource == menuItem[5]||eventSource == menuItem1[2])//复制动作 { String text = textArea.getSelectedText();StringSelection selection= new StringSelection(text);clipboard.setContents(selection,null);} else if(eventSource == menuItem[6]||eventSource == menuItem1[1])//剪切动作 { String text = textArea.getSelectedText();StringSelection selection = new StringSelection(text);clipboard.setContents(selection,null);textArea.replaceRange(”“, textArea.getSelectionStart(), textArea.getSelectionEnd());}

else if(eventSource == menuItem[7]||eventSource == menuItem1[3])//粘贴动作 { Transferable contents = clipboard.getContents(this);if(contents==null)return;String text;text=”“;try { text =(String)contents.getTransferData(DataFlavor.stringFlavor);} catch(Exception ex){

} textArea.replaceRange(text, textArea.getSelectionStart(),textArea.getSelectionEnd());} else if(eventSource == menuItem[8])//自动换行 { if(textArea.getLineWrap())textArea.setLineWrap(false);else textArea.setLineWrap(true);

} else if(eventSource == menuItem[9])//字体 {//实例化字体类

FontDialog fontdialog = new FontDialog(new JFrame(),”字体“,true);textArea.setFont(fontdialog.showFontDialog());//设置字体 }

else if(eventSource == menuItem[11])//帮助 { try { String filePath = ”C:/WINDOWS/Help/notepad.hlp“;Runtime.getRuntime().exec(”cmd.exe /c “+filePath);} catch(Exception ee){ JOptionPane.showMessageDialog(this,”打开系统的记事本帮助文件出错!“,”错误信息“,JOptionPane.INFORMATION_MESSAGE);} } else if(eventSource == menuItem[12])//关于记事本 { String help = ”记事本 版本1.0n操作系统:WIN 8 n编译器:eclipsen版权“ + ”所有: ESTON YANG n最终解释权归本人所有“ + ”“ + ”nBuild By 冯洋“ + ”n课程设计:JAVA“;JOptionPane.showConfirmDialog(null, help, ”关于记事本“, JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);

} else if(eventSource == menuItem[15]||eventSource == menuItem[16])//查找下一个 { search();

} else if(eventSource == menuItem[17])//替换 { substitude();} else if(eventSource == menuItem[3])//打印 { try { textArea.print();} catch(PrinterException e1){ e1.printStackTrace();}

} } /** * openFile方法 * * 从TXT读进数据到记事本 * **/ public void openFile(String fileName){

try {

File file = new File(fileName);FileReader readIn = new FileReader(file);int size =(int)file.length();int charsRead = 0;char[] content = new char[size];while(readIn.ready()){ charsRead += readIn.read(content,charsRead,size-charsRead);} readIn.close();textArea.setText(new String(content,0,charsRead));} catch(Exception e){ System.out.println(”Error opening file!“);} } /** * saveFile方法 * * 从记事本写进数据到TXT * **/ public void writeFile(String fileName){ try { File file = new File(fileName);FileWriter write = new FileWriter(file);write.write(textArea.getText());write.close();} catch(Exception e){ System.out.println(”Error closing file!“);} } /** * substitude方法 * * 实现替换功能 * */ public void substitude(){

final JDialog findDialog = new JDialog(this, ”查找与替换“, true);Container con = findDialog.getContentPane();con.setLayout(new FlowLayout(FlowLayout.LEFT));JLabel searchContentLabel = new JLabel(”查找内容(N):“);JLabel replaceContentLabel = new JLabel(”替换为(P):“);final JTextField findText = new JTextField(30);final JTextField replaceText = new JTextField(30);final JCheckBox matchcase = new JCheckBox(”区分大小写(C)“);ButtonGroup bGroup = new ButtonGroup();final JRadioButton up = new JRadioButton(”向上(U)“);final JRadioButton down = new JRadioButton(”向下(D)“);down.setSelected(true);//默认向下搜索

bGroup.add(up);bGroup.add(down);

JButton searchNext = new JButton(”查找下一个(F)“);JButton replace = new JButton(”替换(R)“);final JButton replaceAll = new JButton(”全部替换(A)“);

//”替换“按钮的事件处理

replace.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(replaceText.getText().length()== 0 && textArea.getSelectedText()!= null)

textArea.replaceSelection(”“);if(replaceText.getText().length()> 0 && textArea.getSelectedText()!= null)

textArea.replaceSelection(replaceText.getText());} });

//”替换全部“按钮的事件处理

replaceAll.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ textArea.setCaretPosition(0);//将光标放到编辑区开头 int a = 0, b = 0, replaceCount = 0;if(findText.getText().length()== 0){ JOptionPane.showMessageDialog(findDialog, ”请填写查找内容!“, ”提示“,JOptionPane.WARNING_MESSAGE);findText.requestFocus(true);return;} while(a >-1){ int FindStartPos = textArea.getCaretPosition();//获取光标位置

String str1, str2, str3, str4, strA, strB;str1 = textArea.getText();str2 = str1.toLowerCase();str3 = findText.getText();str4 = str3.toLowerCase();if(matchcase.isSelected())//大小写区分 { strA = str1;strB = str3;} else { strA = str2;strB = str4;}

if(up.isSelected())//向上搜索

{ if(textArea.getSelectedText()== null){ a = strA.lastIndexOf(strB, FindStartPos1);} } else //向下搜索

{ if(textArea.getSelectedText()== null){ a = strA.indexOf(strB, FindStartPos);

} else { a = strA.indexOf(strB, FindStartPos-findText.getText().length()+ 1);} }

if(a >-1){ if(up.isSelected()){

textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);} else if(down.isSelected()){

textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);} } else { if(replaceCount == 0){ JOptionPane.showMessageDialog(findDialog,”找不到您查找的内容!“, ”记事本“,JOptionPane.INFORMATION_MESSAGE);} else { JOptionPane.showMessageDialog(findDialog, ”成功替换“+ replaceCount + ”个匹配内容!“, ”替换成功“,JOptionPane.INFORMATION_MESSAGE);} } if(replaceText.getText().length()== 0&& textArea.getSelectedText()!= null)//用空字符代替选定内容

{

textArea.replaceSelection(”“);replaceCount++;} if(replaceText.getText().length()> 0&& textArea.getSelectedText()!= null)//用指定字符代替选定内容 {

textArea.replaceSelection(replaceText.getText());replaceCount++;} }//end while } });

//”查找下一个“按钮事件处理

searchNext.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){ int a = 0, b = 0;int FindStartPos = textArea.getCaretPosition();String str1, str2, str3, str4, strA, strB;str1 = textArea.getText();str2 = str1.toLowerCase();str3 = findText.getText();str4 = str3.toLowerCase();

//”区分大小写“的CheckBox被选中

if(matchcase.isSelected())//区分大小写

{ strA = str1;strB = str3;} else //不区分大小写 { strA = str2;strB = str4;} if(up.isSelected())//向上搜索

{ if(textArea.getSelectedText()== null){

a = strA.lastIndexOf(strB, FindStartPosfindText.getText().length()findText.getText().length()+ 1);} } if(a >-1){ if(up.isSelected()){

textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);} else if(down.isSelected()){

textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);} } else { JOptionPane.showMessageDialog(null, ”找不到您查找的内容!“, ”记事本“, JOptionPane.INFORMATION_MESSAGE);} } });

//”取消“按钮及事件处理

JButton cancel = new JButton(”取消“);cancel.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ findDialog.dispose();} });//创建”查找与替换“对话框的界面

JPanel bottomPanel = new JPanel();JPanel centerPanel = new JPanel();JPanel topPanel = new JPanel();JPanel direction = new JPanel();

direction.setBorder(BorderFactory.createTitledBorder(”方向“));direction.add(up);direction.add(down);

JPanel replacePanel = new JPanel();replacePanel.setLayout(new GridLayout(1, 2));replacePanel.add(searchNext);replacePanel.add(replace);replacePanel.add(replaceAll);replacePanel.add(cancel);

topPanel.add(searchContentLabel);topPanel.add(findText);

centerPanel.add(replaceContentLabel);centerPanel.add(replaceText);centerPanel.add(replacePanel);

bottomPanel.add(matchcase);bottomPanel.add(direction);

con.add(replacePanel);con.add(topPanel);con.add(centerPanel);con.add(bottomPanel);

//设置”查找与替换“对话框的大小、可更改大小(否)、位置和可见性

findDialog.setSize(550, 240);findDialog.setResizable(true);findDialog.setLocation(230, 280);findDialog.setVisible(true);}//方法mySearch()结束 /** * search方法 * * 实现查找功能 * */ public void search(){

final JDialog findDialog = new JDialog(this, ”查找下一个“, true);Container con = findDialog.getContentPane();con.setLayout(new FlowLayout(FlowLayout.LEFT));JLabel searchContentLabel = new JLabel(” 查找内容(N):“);

final JTextField findText = new JTextField(17);final JCheckBox matchcase = new JCheckBox(”区分大小写(C)“);ButtonGroup bGroup = new ButtonGroup();final JRadioButton up = new JRadioButton(”向上(U)“);final JRadioButton down = new JRadioButton(”向下(D)“);down.setSelected(true);//默认向下搜索

bGroup.add(up);bGroup.add(down);

JButton searchNext = new JButton(”查找下一个(F)“);

//”查找下一个“按钮事件处理

searchNext.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){ int a = 0, b = 0;int FindStartPos = textArea.getCaretPosition();String str1, str2, str3, str4, strA, strB;str1 = textArea.getText();str2 = str1.toLowerCase();str3 = findText.getText();str4 = str3.toLowerCase();

//”区分大小写“的CheckBox被选中

if(matchcase.isSelected())//不区分大小写

{ strA = str1;strB = str3;} else //区分大小写 { strA = str2;strB = str4;} if(up.isSelected())//向上搜索

{ if(textArea.getSelectedText()== null){

a = strA.lastIndexOf(strB, FindStartPosfindText.getText().length()findText.getText().length()+ 1);} } if(a >-1){ if(up.isSelected()){

textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);} else if(down.isSelected()){

textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);} } else { JOptionPane.showMessageDialog(null, ”找不到您查找的内容!“, ”记事本“, JOptionPane.INFORMATION_MESSAGE);} } });

//”取消“按钮及事件处理

JButton cancel = new JButton(” 取消 “);cancel.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ findDialog.dispose();} });//创建”替换“对话框的界面

JPanel bottomPanel = new JPanel();JPanel centerPanel = new JPanel();JPanel topPanel = new JPanel();JPanel direction = new JPanel();direction.setBorder(BorderFactory.createTitledBorder(”方向“));direction.add(up);direction.add(down);topPanel.add(searchContentLabel);topPanel.add(findText);topPanel.add(searchNext);bottomPanel.add(matchcase);bottomPanel.add(direction);bottomPanel.add(cancel);con.add(topPanel);con.add(centerPanel);con.add(bottomPanel);//设置”替换“对话框的大小、可更改大小(否)、位置和可见性

findDialog.setSize(425, 200);findDialog.setResizable(true);findDialog.setLocation(230, 280);findDialog.setVisible(true);}

/** * 主函数 * * * **/ public static void main(String[] args){

MiniNote note = new MiniNote();note.setVisible(true);}

} //字体类

import java.awt.Font;import java.awt.GraphicsEnvironment;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import java.awt.*;import javax.swing.*;import java.awt.event.*;import javax.swing.border.*;import java.util.*;public class FontDialog {

private Dialog fontdialog;private JButton okButton, cancelButton;private int width = 480;private int height = 250;private String name = ”Serif“;private int type = 0;private int size = 12;private Font customFont = new Font(”宋体“, Font.ITALIC, 12);private boolean okpressed = false;private boolean cancelpressed = false;private JLabel lbl1 = new JLabel(”字体:“);private JLabel lbl2 = new JLabel(”字形:“);private JLabel lbl3 = new JLabel(”大小:“);private JTextArea area;String[] zx = { ”常规“, ”加粗“, ”斜体“, ”基线“ };String[] dx = {”8“ , ”9“ , ”10“, ”12“, ”14“, ”15“, ”16“, ”18“,”20“, ”21“, ”22“, ”24“, ”26“, ”28“, ”30“, ”36“,”48“, ”54“,”72“ , ”89“};JLabel lbl = new JLabel(”字体样式Style“);private JComboBox cb1, cb3 = new JComboBox(dx), cb2 = new JComboBox(zx);private String[] zt;

public FontDialog(Frame owner, String title, boolean modal){

init();fontdialog = new Dialog(owner, title, modal);fontdialog.setLocation(owner.getLocation());fontdialog.setLayout(new FlowLayout());fontdialog.setSize(getWidth(), getHeight());fontdialog.add(lbl1);fontdialog.add(cb1);fontdialog.add(lbl2);fontdialog.add(cb2);fontdialog.add(lbl3);fontdialog.add(cb3);fontdialog.add(okButton);fontdialog.add(cancelButton);fontdialog.add(area);fontdialog.setResizable(false);fontdialog.setAlwaysOnTop(true);cancelButton.addActionListener(new fontListener());okButton.addActionListener(new fontListener());fontdialog.addWindowListener(new fontListener());

cb1.addItemListener(new ItemListener(){ // public void itemStateChanged(ItemEvent event){ //获取选择用户的字体类型

name =(String)event.getItem();setCustomFont(new Font(name, type, size));} });

cb2.addItemListener(new ItemListener(){ // public void itemStateChanged(ItemEvent event){ //获取选择用户的字形

String s =(String)event.getItem();if(s.equals(”常规“)){ type = Font.PLAIN;setCustomFont(new Font(name, type, size));} else if(s.equals(”加粗“)){ type = Font.BOLD;

字体动作 添加监听器字形动作 添加监听器 setCustomFont(new Font(name, type, size));} else if(s.equals(”斜体“)){ type = Font.ITALIC;setCustomFont(new Font(name, type, size));} else { type = Font.CENTER_BASELINE;setCustomFont(new Font(name, type, size));} } });

cb3.addItemListener(new ItemListener(){ //大小动作 public void itemStateChanged(ItemEvent event){ //添加监听器获取选择用户的字号大小

size =(new Integer((String)event.getItem()).intValue());setCustomFont(new Font(name, type, size));} });

}

public Font showFontDialog(){ fontdialog.setVisible(true);if(okpressed){ return getCustomFont();} else { return customFont;} }

private void init(){ //初始化 okButton = new JButton(”确定“);cancelButton = new JButton(”取消“);GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();zt = ge.getAvailableFontFamilyNames();cb1 = new JComboBox(zt);cb1.setMaximumRowCount(6);area = new JTextArea(6, 30);cb3 = new JComboBox(dx);cb3.setMaximumRowCount(6);okButton.setFocusable(true);area.setEditable(false);area.setText(new Date().toString());area.setBorder(new TitledBorder(”字体样式"));}

public void setWidth(int width){ this.width = width;}

public void setHeight(int height){ this.height = height;}

private int getWidth(){ return(this.width);}

private int getHeight(){ return(this.height);}

private void setCustomFont(Font customFont)//{ this.customFont = customFont;area.setFont(customFont);area.revalidate();}

public String toString(){ return FontDialog.class.toString();}

设置字体 public Font getCustomFont()//获取字体 { return(this.customFont);}

private class fontListener extends WindowAdapter implements ActionListener //监听事件类 { public void windowClosing(WindowEvent e){ fontdialog.dispose();}

public void actionPerformed(ActionEvent e){ if(e.getSource()== cancelButton){ fontdialog.dispose();cancelpressed = true;} else if(e.getSource()== okButton){ okpressed = true;setCustomFont(new Font(name, type, size));fontdialog.dispose();} } } }

相关内容

热门阅读

最新更新

随机推荐