还剩53页未读,继续阅读
本资源只提供10页预览,全部文档请下载后查看!喜欢就下载吧,查找使用更方便
文本内容:
71010124王海珍《面向对象设计java》第十五周实验总结第一部分理论部分JAR文件应用程序首选项存储Java WebStartJAR文件:
1.Java程序的打包程序编译完成后,程序员将.class文件压缩打包为.jar文件后,GUI界面程序就可以直接双击图标运行
2.jar文件(Java归档)既可以包含类文件,也可包含诸如图像和声音这些其它类型的文件
1.012015-06-16*©author CayHorstmann*/public classPropertiesTest{public staticvoid mainString[]argsEventQueue.invokeLater-{PropertiesFrame frame=new PropertiesFrame;frame.setVisibletrue;};/***A framethat restoresposition andsize froma propertiesfile and updates*the propertiesupon exit.*/class PropertiesFrameextends JFrameprivate static final int DEFAULTWIDTH=300;private static final intDEFAULTJIEIGHT=200;private FilepropertiesFile;private Propertiessettings;public PropertiesFrame//get position,size,title frompropertiesString userDir=System.getPropertyuser,home;File propertiesDir=new FileuserDir,〃・corejava;if!propertiesDir.exists propertiesDir.mkdir;propertiesFile=new FilepropertiesDir,“program,properties;Properties defaultsettings=new Properties;defaultSettings.setProperty〃left〃,〃0〃;defaultSettings.setProperty〃top〃,〃0〃;defaultSettings.setProperty^width^,〃+DEFAULT WIDTH;defaultSettings.setProperty,/height,z,〃+DEFAULT_HEIGHT;defaultSettings.setProperty title”,〃〃;settings=new PropertiesdefaultSettings;if propertiesFile.existstry InputStream in=new FilelnputStreampropertiesFilesettings,load in;catch lOExceptionexex.printStackTrace;int left=Integer,parselnt settings.getProperty z,leftz,;int top=Integer,parselnt settings.getProperty,ztop,/;int width=Integer,parselnt settings.getProperty,,width,/;int height=Integer,parselntsettings.getProperty^height^;setBoundsleft,top,width,height;//if notitle given,ask userStringtitle=settings.getProperty,ztitle,z;if title,equals title=JOptionPane.showInputDialogz,Please supplya frametitle:/z;if title==null title=setTitle title;addWindowListenernew WindowAdapterpublic voidwindowC1osingWindowEvent eventsettings.setPropertyleft”,〃〃+getX;settings.setProperty//top,,〃〃+getY;settings.setProperty,,width,/,〃〃+getWidth;settings.setProperty,zheight,z,〃〃+getHeight;settings.setProperty title”,getTitle;try OutputStream out=new FileOutputStreampropertiesFilesettings,storeout,Program Properties;}catch lOExceptionexex.printStackTrace;}System,exit0;测试程序31在elipse IDE中调试运行教材593页-594程序13-3,结合程序运行结果理解程序;1了解Preferences类中常用的方法;package preferences;import java.awt.import java.io.*;import java.util,prefs.import javax.swing.*;import javax.swing.filechooser.*;/**..progra.t.tes.preferenc.settings.Th.progra.remember,th.frame*position,size,and title.*©version
1.032015-06T2*©author CayHorstmann*/public classPreferencesTestpublic staticvoid mainString[]args{EventQueue.invokeLater-{PreferencesFrame frame=new PreferencesFrame;frame.setDefaultCloseOperationJFrame.EXIT_ON_CLOSE;frame.setVisibletrue;};/***A framethat restoresposition andsize fromuser preferencesand updatesthe*preferences uponexit.*/class PreferencesFrameextends JFrame{private staticfinal int DEFAULTJVIDTH=300;private staticfinal intDEFAULT HEIGHT=200;private Preferencesroot=Preferences.userRoot;private Preferencesnode=root,node〃/com/horstmann/corejava;public PreferencesFrame//get position,size,title frompreferences intleft=node.getlntleft”,0;int top=node.getlnt,ztopz,,0;int width=node,getlntwidth”,DEFAULT WIDTH;int height=node,getlntheight”,DEFAULT_HEIGHT;setBoundsleft,top,width,height;//if notitle given,ask userStringtitle=node,get title”,〃〃;if title,equals,,,ztitle=JOptionPane.showlnputDialog,zPlease supplya frametitle:;if title二二null title二〃〃;setTitletitle;//设置显示XML文件的文件选择器(manifest..-列出存档内容的列.-.更新已存在的JAR文…-.生成详细・的输出结..二解压存档中的命名的(或所有的)文..-.只存储方式,不用ZIP压缩格式
1.仓ll建JAR文.ja.c.jar-fil.input-file s.cwan.t.Great..JA.file.eg.
1.ja.c.MenuTest.ja.*.clas.*・gi.f-----------------------------------------------------------------------------------wan.th.outpu.t.g.t..fil.rathe,tha.t.stdout.
2.ja.cv.MenuTest.j a.*.clas.*.gi.vProduce,verbos.outpu.t.stdout.
3.ja.cv.MenuTest.ja..*-------------------------------------------------------------------------------------creat.al.content,i.curren.directory.
4.ja.cvO.MenuTest.ja..0一一—don.wan.th.JA.fil.t.b.compressed.
2.查看JAR文.ja.t.jar-fil.twan.t.vie.th.Tabi.o.content,o.th.JA.file.eg.
1.ja.tv.MenuTest.ja.v Produce,verbos.outpu.t.stdout.
3.提取JAR文.ja.x.jar-fil.[archived-file s.xwan.t.extrac.file.fro.th.JA.archive,eg.
1.ja.x.MenuTest.ja.cop y.gif仅提取文件copy.gif.
2.ja.x.MenuTest.ja.alex/copy.gif仅提取目录alex下.文件copy.gif.
3.ja.x.MenuTest.jar提取该JAR中的所有文件或目录
4.更新JAR文.ja.u.jar-fil.input-files.uwan.t.updat.a.existin.JA.file.eg.
1.ja.u.MenuTest.ja.copy.gi.
5.索引JAR文.ja..jar-fil.iinde.a.existin.JA.file.eg.
1.ja..MenuTest.jar清单文件final JFileChooserchooser=new JFileChooser;chooser.setCurrentDirectorynew File〃・〃;chooser.setFileFilter newFileNameExtensionFilter Z,XML files,xml;//设置菜单JMenuBar menuBar=new JMenuBar;setJMenuBarmenuBar;JMenu menu=new JMenu〃File〃;menuBar.addmenu;JMenuItem exportitem=new JMenuItemExportpreferences^;menu.add exportltem;exportltem.addActionListenerevent-{if chooser.showSaveDialogPreferencesFrame.this==JFileChooser.APPROVE^OPTIONtrysavePreferences;OutputStreamout=new FileOutputStreamchooser.getSelectedFile;node.exportSubtreeout;out.close;catch Exceptionee.printStackTrace;};JMenuItem importitem=new JMenuItemImportpreferences;menu,addimportltem;importitem.addActionListener event-{if chooser.showOpenDialogPreferencesFrame.this==JFileChooser.APPROVE_OPTIONtryInputStream in=new FileinputStreamchooser,getSelectedFile;Preferences.importPreferencesin;in.close;catch Exceptionee.printStackTrace;};JMenuItem exititem=new JMenuItem〃Exit〃;menu.addexititem;exititem.addActionListener event-{savePreferences;System,exit0;};public voidsavePreferencesnode,putlnt getX;node,putlnt〃top〃,getY;node,putlntwidth”,getWidth;node.putlnt height”,getHeight;node,put title”,getTitle;测试结果如下所示测试程序41在elipse IDE中调试运行教材619页-622程序13-6,结合程序运行结果理解程序;1掌握基于JNLP协议的java WebStart应用程序的发布方法package webstart;import java.awt.import javax.swing.*;/***A calculatorwith acalculation historythat canbe deployedas aJava WebStart application.*©version
1.042015-06T2*©author CayHorstmann*/public classCalculator{public staticvoid mainString[]args]EventQueue.invokeLater-{CalculatorFrame frame=new CalculatorFrame;frame.setDefaultCloseOperationJFrame.EXIT ONCLOSE;frame.setVisibletrue;};package webstart;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.FileNotFoundException;import java.io.lOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.Outputstream;import java.io.PrintStream;import java.net.MalformedURLException;import java.net.URL;import javax.jnlp.BasicService;import javax.jnlp.FileContents;import javax.jnlp.FileOpenService;import javax.jnlp.FileSaveService;import javax.jnlp.PersistenceService;import javax.jnlp.ServiceManager;import javax.jnlp.UnavailableServiceException;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;/***A framewith acalculator paneland amenu toload andsave thecalculator history.public classCalculatorFrame extends JFrameprivate CalculatorPanelpanel;public CalculatorFramesetTitle;panel=new CalculatorPanel;addpanel;JMenu fileMenu=new JMenuFile;JMenuBar menuBar=new JMenuBar;menuBar.addfileMenu;setJMenuBarmenuBar;JMenuItem openitem二fileMenu.add/z0pen/z;openitem.addActionListenerevent-open;JMenu Itern saveitem=f ileMenu.add/zSave,z;saveitem.addActionListenerevent-save;pack;/***Gets the title fromthe persistentstore orasks theuser forthetitleif thereis noprior*entry.*/public voidsetTitletryString title=null;BasicService basic=BasicServiceServiceManager.lookup z,javax.jnlp.BasicService;URL CodeBase=basic.getCodeBase;PersistenceService service=PersistenceService ServiceManager.lookup z/javax.jnlp.PersistenceService;URL key=new URLCodeBase,“title;tryFileContents contents=service.getkey;InputStreamin=contents.getlnputStreamO;每个JAR文件中包含一个用于描述归档特征的清单文件・manifest清单文件被命名为MANIFEST.MF,它位于JAR文件的一个特0殊的META-INF子目录中•最小的符合标准的清单文件是很简单的Manifest-Version
1.0复杂的清单文件包含多个条目,这些条目被分成多个节第一节被称为主节,作用于整个JAR文件随后的条目用来指定已命名条目的属性,可以是文件、包或者URL•清单文件的节与节之间用空行分开,最后一行必须以换行符结束否则,清单文件将无法被正确地读取-创建一个包含清单的JAR文件,应该运行jar cfmMyArchive.jar manifest,mf com/*,class-要更新一个已有JAR文件的清单,则需要将增加的部分放置到一个文本文件中,运行如下命令jar ufmMyArchive.jar manifest-additions,mf运行JAR文件•用户可以通过下面的命令来启动应用程序java-jar MyProgram.jar•窗口操作系统,可通过双击JAR文件图标来启动应用程序资源BufferedReader reader=new BufferedReadernew InputStreamReaderin;title=reader.readLineO;catch FileNotFoundExceptionetitle=JOptionPane.showInputDialogz/Please supplya frametitle:〃;if title二二null return;service,create key,100;FileContents contents=service.get key;Outputstream out=contents.getOutputStreamtrue;PrintStream printout=new PrintStreamout;printout,printtitle;}setTitletitle;catch UnavailableServiceException|lOException eJOptionPane.showMessageDialogthis,e;/***Opens ahistory fileandupdatesthe display.*/public voidopentryFileOpenService service二FileOpenService ServiceManager.lookup,zjavax.jnlp.FileOpenService;FileContents contents二service.openFileDialog,,.z,,new String[]“txt};JOptionPane.showMessageDialogthis,contents.getName;if contents!=nullInputStream in=contents,getInputStream;BufferedReader reader=new BufferedReadernewInputStreamReader in;String line;while line=reader.readLine!=nullpanel,append line;panel,append〃\n〃;}}catch UnavailableServiceExceptioneJOptionPane.showMessageDialogthis,e;catch lOExceptioneJOptionPane.showMessageDialogthis,e;/***Saves thecalculator historyto afile.*/public voidsavetry{ByteArrayOutputStream out二new ByteArrayOutputStream;PrintStream printout=new PrintStreamout;printout,printpanel.getText;InputStream data=new ByteArrayInputStreamout.toByteArray;FileSaveService service=FileSaveService ServiceManager.lookupz,javax.jnlp.FileSaveService;service.saveFileDialog,z.z,,new String[]{〃txt〃,data,〃calc・txt〃;catch UnavailableServiceExceptioneJOptionPane.showMessageDialogthis,e;catch lOExceptioneJOptionPane.showMessageDialogthis,e;package webstart;import java.awt.import java.awt.event.import javax.swing.*;import javax.swing,text.*;/**A panelwith calculatorbuttons anda resultdisplay.public classCalculatorPanel extendsJPanelprivate JTextAreadisplay;private JPanelpanel;private doubleresult;private StringlastCommand;private booleanstart;/**Lays outthe panel.*/public CalculatorPanelsetLayoutnew BorderLayout;result=0;lastCommand=〃=”;start二true;//add the display display=new JTextArea10,20;addnew JScrollPanedisplay,BorderLayout.NORTH;ActionListener insert=new InsertAction;ActionListener command=new CommandAction;//add the buttons ina4x4grid panel=new JPanel;panel.setLayoutnew GridLayout4,4;addButton〃8〃,insert;addButton〃9〃,insert;addButton〃/〃,command;addButton〃4〃,insert;addButton〃5〃,insert;addButton〃6〃,insert;addButton〃*〃,command;addButton〃1〃,insert;addButton〃2〃,insert;addButton〃3〃,insert;addButton command;addButton〃0〃,insert;addButton〃.〃,insert;addButton〃二〃,command;addButton〃+〃,command;addpanel,BorderLayout.CENTER;/**Gets the history text.©return thecalculator historypublic StringgetTextreturndisplay.getText;/**Appends astring to thehistorytext.©param sthe stringto append*/public voidappendString sdisplay.appends;/**Adds abutton tothe centerpanel.@param labelthe buttonlabel©param listenerthe buttonlistenerprivate voidaddButtonString label,ActionListener listenerJButtonbutton=new JButtonlabel;button.addActionListenerlistener;panel,addbutton;/**•Java中,应用程序使用的类通常需要一些相关的数据文件,这些文件称为资源Resource-图像和声音文件-带有消息字符串和按钮标签的文本文件-二进制数据文件,如描述地图布局的文件•类加载器知道如何搜索类文件,直到在类路径、存档文件或Web服务器上找到为止•利用资源机制对于非类文件也可以进行同样操作,具体步骤如下-获得资源的Class对象-如果资源是一个图像或声音文件,那么就需要调用getresource filename获得资源的URL位置,然后利用get Image或getAudioClip方法进行读取-如果资源是文本或二进制文件,那么就可以使用getResouceAsStream方法读取文件中的数据•资源文件可以与类文件放在同一个目录中,也可以将资源文件放在其它子目录中具体有以下两种方式-相对资源名如data/text/about,txt它会被解释为相对于加载这个资源的类所在的包-绝对资源名^n/corejava/title.txt•ResourceTest.java程序演示了资源加载的过程•编译、创建JAR文件和执行这个程序的命令如下-javac ResourceTest.java-jar cvfmThis action insertsthe buttonaction stringtotheend ofthedisplaytext.*/private classInsertAction implementsActionListenerpublic voidactionPerformedActionEvent eventStringinput=event.getActionCommand;start=false;display,append input;/**Thisactionexecutes thecommand thatthebuttonaction stringdenotes.*/private classCommandAction implementsActionListenerpublic voidactionPerformedActionEvent eventStringcommand=event.getActionCommand;if startif command,equals〃一〃display,appendcommand;start=false;elselastCommand=command;elsetryint lines=display.getLineCount;int lineStart=display.getLineStartOffsetlines-1;int lineEnd=display.getLineEndOffset lines-1;String value=display.getTextlineStart,lineEnd-lineStart;display,append〃〃;display,appendcommand calculateDouble.parseDoublevalue;ifcommand,equals〃=〃display,append//\n,/+result;lastCommand=command;display,append〃\n〃;start=true;}catch BadLocationExceptionee.printStackTrace;...Carrie,ou.th.pendin.calculation.©param xthe valueto beaccumulated withthe priorresult.public voidcalculate doublexelse if lastCommand.equals〃-result x;else iflastCommand.equals〃*〃result*二x;else iflastCommand.equals〃/〃result/二x;else iflastCommand.equals〃二〃result x;iflastCommand.equals〃+〃result+=x;代码出现错误实验2:GUI综合编程练习按实验十四分组名单,组内讨论完成以下编程任务练习1采用GUI界面设计以下程序,并进行部署与发布1编制一个程序,将身份证号.txt中的信息读入到内存中;1按姓名字典序输出人员信息;1查询最大年龄的人员信息;1查询最小年龄人员信息;1输入你的年龄,查询身份证号.txt中年龄与你最近人的姓名、身份证号、年龄、性别和出生地;1查询人员中是否有你的同乡1输入身份证信息,查询所提供身份证号的人员信息,要求输入一个身份证数字时,查询界面就显示满足查询条件的查询结果,且随着输入的数字的增多,查询匹配的范围逐渐缩小package demol;import java.awt.import javax.swing.public classButtonTest{public staticvoidmainString[]args{EventQueue.invokeLater-{JFrame frameframe.setTitle newMain;〃身份证〃;frame.setDefaultCloseOperationJFrame.EXIT_ON_CLOSE;frame.setVisibletrue;};}}ButtonTestpackage demol;import java.io.BufferedReader;import java.io.File;import java.io.FilelnputStream;importjava.io.InputStreamReader;import java.io.FileNotFoundException;importjava.io.lOException;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Scanner;import java.awt.import javax.swing.import java.awt.event.public classMain extendsJFrame{private staticArrayListStudent studentlist;private staticArrayListStudentlist;private JPanelpanel;private JPanelbuttonPanel;private staticfinal intDEFAULTWITH=600;private staticfinal intDEFAULTHEIGHT=300;public Main{studentlist=new ArrayList;Scanner scanner=newScanner System,in;File file=newFile〃C:\\Users\\ASUS\\Desktop\\身份证号.txt;try{FilelnputStream fis=newFilelnputStreamfile;BufferedReader in=new BufferedReadernewInputStreamReaderfis;String temp=null;while temp=in.readLine!=null{Scannerlinescanner=new Scannertemp;linescanner.useDelimiter z/〃;String name=linescanner,next;String number=linescanner.next;String sex=linescanner.next;String age=linescanner,next;String province二linescanner.nextLine;Studentstudent=new Student;student.setNamename;student,setnumber number;student.setsex sex;int a=Integer,parselntage;student,setage a;student.setprovince province;studentlist,addstudent;}}catch FileNotFoundExceptione{System.out.printin学生信息文件找不到〃;e.printStackTrace;}catch lOExceptione{System,out.printin〃学生信,总、文件读取错误〃;e.printStackTrace;}panel=new JPanel;panel,set LayoutnewBorderLayout;JTextArea jt=new JTextAreaO;panel,add jt;add panel,BorderLayout.NORTH;buttonPanel=new JPanel;buttonPanel.setLayoutnew GridLayout1,7;JButton jButton=new JButton字典排序;JButton jButtonl=new JButton〃年龄最大和年龄最小〃;JLabel lab=new JLabel〃猜猜你的老乡〃;JTextField jtl=new JTextField;JLabel labl=new JLabel〃找找同龄人年龄相近〃;JTextField jt2=new JTextField;JLabel lab2=new JLabel〃输入你的身份证号码〃;JTextField jt3=new JTextField;JButton JButton2=new JButton〃退出〃;jButton.setBounds110,90,60,30;jButtonl.setBounds110,90,60,30;jtl.setBounds110,90,60,30;jt
2.setBounds110,90,60,30;jt
3.setBounds110,90,60,30;jButton
2.setBounds110,90,60,30;jButton.addActionListenernew ActionListener{public voidactionPerformedActionEvent e{Collections,sort studentlist;jt.setText studentlist.toStringO;}};jButtonl.addActionListenernew ActionListener{public voidactionPerformedActionEvent e{int max=0,min=100;int j,kl=0,k2=0;for inti=1;istudentlist,size;i++{j=studentlist,geti.getageO;if jmax{max=j;kl=i;}if jmin{min=j;k2=i;}}jt.setText〃年龄最大+studentlist,getkl+〃年龄最小〃+studentlist.getk2;}};jButton
2.addActionListener newActionListener{public voidactionPerformedActionEvent e{dispose;System,exit0;}};jtl.addActionListenernew ActionListener{public voidactionPerformedActionEvent e{String find=jtl.getText;String text二〃〃;String place=find.substring0,3;for inti=0;istudentlist.size;i++{if studentlist,geti.getprovince.substringd,
4.equals place{text+=〃\n〃+studentlist・get i;jt・setText〃老乡:〃+text;}}}};jt
2.addActionListenernew ActionListener{public voidactionPerformedActionEvente{String yourage=jt
2.getText;int a二Integer,parselntyourage;int near=ageneara;int value=a-studentlist,get near.getage;jt.setText〃年龄相近〃+studentlist,getnear;}};Jt
3.addActionListenernew ActionListener{public voidactionPerformedActionEvente{list二new ArrayListO;Collections,sort studentlist;String key=jt
3.getText;for inti=1;i studentlist.size;i++{if studentlist,geti.getnumber.containskey{list,addstudent list,geti;jt.setText你可能是:\n〃+list;“System,out.printin〃可能的人〃+student list,get i;//jt.setText〃可能的人:〃+student list,get i;}}}};buttonPanel.addjButton;buttonPanel.addjButtonl;buttonPanel.addlab;buttonPanel.addjtl;buttonPanel.addlabl;buttonPanel.addjt2;buttonPanel.addlab2;buttonPanel.addjt3;buttonPanel.add jButton2;add buttonPanel,BorderLayout.SOUTH;setSizeDEFAULTJVITH,DEFAULT HEIGHT;}public staticint agenearint age{int min=53,value=0,k=0;for inti=0;istudentlist,size;i++{value=studentlist,geti.getage-age;if value0value二-value;if valuemin{min=value;k=i;}}return k;}}Main回日upackage demol;public classStudent implementsComparableStudent{private Stringname;private Stringnumber;private Stringsex;private intage;private Stringprovince;public StringgetName{return name;}public voidsetNameString name{this,name=name;}public Stringgetnumber{return number;}public voidsetnumberString number{this,number=number;}public StringgetsexO{return sex;}public voidsetsexString sex{this.sex=sex;}public intgetage{return age;}public voidsetageint age{//inta二Integer,parselntage;this.age=age;}public Stringgetprovince{return province;}public voidsetprovinceString province{this.province=province;}public intcompareToStudent o{return this.name.compareToo.getNameO;}public StringtoStringO{return name+〃\t〃+sex+〃\t〃+age+〃\t〃+number+〃\t〃+province+〃\n〃;}}Student运行结果:字典排序:
1.查询最大年龄的人员信息;
2.查询最小年龄人员信息;找老乡:年龄相近的人:ResourceTest.jar ResourceTest.mf class*gif*.txt-java・-jar ResourceTest.jar
1.实验目的与要求1掌握Java应用程序的打包操作;22了解应用程序存储配置信息的两种方法;3掌握基于JNLP协议的java WebStart应用程序的发布方法;⑸掌握Java GUI编程技术
1.实验目的与要求1掌握Java应用程序的打包操作;2了解应用程序存储配置信息的两种方法;3掌握基于JNLP协议的java WebStart应用程序的发布方法;5掌握Java GUI编程技术实验1导入第13章示例程序,测试程序并进行代码注性
2.实验内容和步骤测试程序11在elipse IDE中调试运行教材585页程序13-1,结合程序运行结果理解程序;输入身份证信息,查询所提供身份证号的人员信息,要求输入一个身份证数字时,查询界面就显示满足查询条件的查询结果,且随着输入的数字的增多,查询匹配的范围逐渐缩小输入数字2时:输入数字26时:输入数字265时:练习2:采用GUI界面设计以下程序,并进行部署与发布1编写一个计算器类,可以完成加、减、乘、除的操作1利用计算机类,设计一个小学生100以内数的四则运算练习程序,由计算机随机产生10道加减乘除练习题,学生输入答案,由程序检查答案是否正确,每道题正确计10分,错误不计分,10道题测试结束后给出测试总分;将程序中测试练习题及学生答题结果输出到文件,文件名为1test.txtopackage ui_test;import java.awt.import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.lOException;importjava.util.ArrayList;import javax.swing.public classMyExGUI extendsJFrame{ArrayListString user_zongti=new ArrayListString;ArrayListString user_zonganswer=new ArrayListString;ArrayListString user_answer=new ArrayListString;ArrayListString true_answer=new ArrayListString;ArrayListString jta_timu=newArrayListString;ArrayListString jtazong=new ArrayListString;ArrayListIntegeruser fenshu=new ArrayListInteger;JMenuBar jm;//菜单条组件JMenu menu;//菜单JMenuItemiteml,item2;//菜单项JMenu build;//二级菜单JMenuItem file,project;TextArea answer_all=new TextArea;TextField jta=new TextField;TextField jtaanswer=new TextField;JLabelnum answer=new JLabel;JLabel answer;JToolBar jtb;//工具条JButton jbl,jb2,jb3,jb4,jb5,jb6,jb7,jb next;intanswer_count;int answer_fenshu;public MyExGUI{//仓ll建菜单jm=new JMenuBar;menu=new JMenu〃文件F〃;menu.setMnemonic,f;//助记符build=new助enu〃新建“;file=new JMenuItem文件〃;project=new JMenuItem〃答题〃;iteml=new JMenuItem〃保存S〃;item2=new JMenuItem〃退出〃;answer=new JLabel第1题;//添加菜单项至菜单上build,add file;build.addproject;menu,addbuild;menu,additeml;menu.additem2;menu.addSeparator;//将菜单加入至菜单栏jm.add menu;JPanel contentPanel二new JPanel;contentPanel.setLayout null;JLabel daan=new JLabel〃答案〃;JLabel dengyu二new JLabel〃=〃;num_answer=answer;num_answer.setFontnew Font〃宋体〃,Font.BOLD,22;jb_next二new JButton〃下一题〃;jta.setFont newFont〃宋体〃,Font.BOLD,22;jta_answer.setFont newFont〃宋体〃,Font.BOLD,22;jb_next.setFont newFont〃宋体〃,Font.BOLD,22;daan.setFont newFont z,宋体〃,Font.BOLD,22;dengyu.setFontnew Font〃宋体〃,Font.BOLD,22;contentPanel.addnum_answer;contentPanel.add daan;contentPanel.adddengyu;contentPanel.addjta;contentPanel.addjta answer;contentPanel.addanswer_all;contentPanel.addjb_next;num_answer.setBounds90,20,130,50;daan.setBounds250,20,90,50;jta.setBounds50,70,150,30;dengyu.setBounds205,70,20,20;jta_answer.setBounds230,70,100,30;jb_next.setBounds350,70,110,30;answer_all.setBounds50,120,400,300;this,setJMenuBar jm;//添加菜单栏,不能设定位置,会自动放在最上部this,addcontentPanel;this.setTitle在线答题系统〃;this.setSize600,500;this.setVisibletrue;this.setDefaultCloseOperationJFrame.EXIT_ON_CLOSE;iteml.addActionListenernew ActionListener{public voidactionPerformedActionEvent argO{FileOutputStream outSTr=null;BufferedOutputStream Buff=null;boolean flag=true;Filefile;//String test;do{//test二〃test〃+count;String inputValue二JOptionPane.showInputDialogC^Please inputfile name;file=newFileinputValue+test,txt;if!file.existsO{//创建文件try{flag=file.createNewFile;}catch lOExceptione{e.printStackTrace;}flag=false;}else{JOptionPane.showMessageDialognull,〃该文件名已存在,请重新输入〃,“ERROR”,JOptionPane.ERROR MESSAGE;flag=true;}}while flag;//写入文件String uanswer;try{outSTr=new FileOutputStreamfile;Buff=new BufferedOutputStreamoutSTr;System,out.printin〃选择是后执行的代码〃+user_zongti.size+user_answer.size;for inti=0;iuser_zongti.size;i++{try{Buff,writeuser_zongti.geti.getBytes;Buff,write z/z/.getBytes;u_answer=user_answer.geti;if u_answer.equals〃〃u_answer二〃没有作答〃;Buff,write u_a.nswer.getBytes;Buff,write/z\r\nz,.getBytes;}catch lOExceptione{e.printStackTrace;i一一;}}Buff,flush;Buff,close;}catch lOExceptione{e.printStackTrace;}try{outSTr.close;}catch lOExceptione{e.printStackTrace;}user_zongti.clear;user_answer.clear;}};project.addActionListenernewActionListener{public voidactionPerformedActionEvent argO{arithmetic art=newarithmetic;true_answer=art.list_answer;jta_timu=art.list_timu;jta_zong=art.list;answer_count=1;answer_all.setText z,,/;for inti=0;iart.list timu.size;i++{user_zongti.addjta_zong.geti;answer_all.appendjta_timu.geti;answer_all.append〃\r\n〃;}num_answer.setText〃第〃+answer count+〃题〃;jta.setTextjta_timu.getanswer_count-1;answer_count++;}};jb_next.addActionListenernew ActionListener{public voidactionPerformedActionEvent argO{String temp;temp=jta_answer.getTextO;if jta.getText.equals〃〃{JOptionPane.showMessageDialog null,〃错误,请导入题库〃,〃错误〃,JOptionPane.ERROR_MESSAGE;return;}jta_answer.setText,,,z;if answer_count=10{if islntegertemp{user_answer.addtemp;System,out.printin〃选择否后执行的代码〃+temp+〃user_size〃+user_answer.sizeO;num_answer・setText〃第〃+answer_count+〃题〃;jta.setTextjta_timu.getanswer_count-1;answer_count++;}else{JOptionPane.showMessageDialognull,〃错误〃,〃请输入数字〃,JOptionPane.ERROR_MESSAGE;}}转载于.cnblogs.com/wvw-whz-1997/p/
10087640.html一全文完一1将所生成的JAR文件移到另外一个不同的目录中,再运行该归档文件,以便确认程序是从JAR文件中,而不是从当前目录中读取的资源1掌握创建JAR文件的方法;package resource;import java.awt.import java.io.*;import java.net.*;import java.util.import javax.swing.*;/***©version
1.412015-06-12*©author CayHorstmann*/public classResourceTestpublic staticvoid mainString[]argsEventQueue.invokeLater-{JFrame frame=new ResourceTestFrame;frame.setTitle,,ResourceTest/,;frame.setDefaultCloseOperationJFrame.EXIT ONCLOSE;frame.setVisibletrue;};/***A framethat loadsimage andtext resources.*/class ResourceTestFrameextendsJFrameprivatestaticfinalintDEFAULTJVIDTH=300;privatestaticfinalintDEFAULTJIEIGHT=300;public ResourceTestFramesetSizeDEFAULTJVIDTH,DEFAULT_HEIGHT;URL aboutURL=getClass.getResource z,about.gif,;Image img二new ImageiconaboutURL.getlmageO;seticonimageimg;JTextArea textArea=new JTextArea;InputStream stream=getClass.getResourceAsStreamabout.txt〃;try Scannerin=new Scannerstream,〃UTF-8〃{while in.hasNext textArea.append in.nextLineO+〃\n〃;addtextArea;。
个人认证
优秀文档
获得点赞 0