100个Java经典例子--初学者的利器高手的宝典JavaSE
来源:互联网 发布:360文件恢复软件下载 编辑:程序博客网 时间:2024/04/27 22:02
- package test1;
- /**
- * Title: Hello Java World
- * Description: 简单的Java程序,只显示一个信息。
- * filename: HelloWorld.java
- */
- public class HelloWorld {
- public static void main(String[] args) {
- System.out.println("Hello Java World!");
- }
- }
- package test2;
- /**
- * Title: Java语言流程演示
- * Description: 演示Java中几种常用的流程控制操作
- * Filename: flowDome.java
- */
- public class flowDemo{
- public static void main(String[] arges){
- int iPara1,iPara2,iEnd;
- if(arges.length!=3)
- {
- System.out.println("USE :java flowDome parameter1 parameter2 circle");
- System.out.println("parameter1 : 比较条件1,数字类型");
- System.out.println("parameter2 : 比较条件2,数字类型");
- System.out.println("circle :循环次数");
- System.out.println("ego:java flowDome 1 2 5");
- return;
- }else{
- iPara1 = Integer.parseInt(arges[0]);
- iPara2 = Integer.parseInt(arges[1]);
- iEnd = Integer.parseInt(arges[2]);
- }
- //if语句
- if(iPara2>iPara1)
- {
- System.out.println("if 条件满足!");
- System.out.println("第2个数比第1个数大!");
- }
- else
- {
- System.out.println("if 条件不满足!");
- System.out.println("第2个数比第1个数小!");
- }
- //for循环操作
- for(int i=0;i<iEnd;i++)
- {
- System.out.println("这是for 第"+i+"次循环");
- }
- //while循环操作
- int i=0;
- while(i<iEnd)
- {
- System.out.println("这是while 第"+i+"次循环");
- i++;
- }
- //do-while循环操作
- int j=0;
- do
- {
- System.out.println("这是do-while 第"+j+"次循环");
- j++;
- }while(j<iEnd);
- }
- }
- package test3;
- /**
- * Title: 数组数据操作
- * Description: 演示一维数组和多维数组的初始化和基本操作
- * Filename: myArray.java
- */
- public class myArray{
- //初始化数组变量
- char[] cNum = {'1','2','3','4','5','6','7','8','9','0'};
- char[] cStr = {'a','b','c','d','e','f','g','h',
- 'i','j','k','l','m','n','o','p',
- 'q','r','s','t','u','v','w','x','y','z'};
- int[] iMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
- String[] sMail = {"@","."};
- /**
- *<br>方法说明:校验电子邮件
- *<br>输入参数:String sPara 被校验的电子邮件字符
- *<br>返回类型:boolean 如果校验的格式符合电子邮件格式返回true;否则返回false
- */
- public boolean isMail(String sPara){
- for(int i=0;i<sMail.length;i++){
- if(sPara.indexOf(sMail[i])==-1)
- return false;
- }
- return true;
- }
- /**
- *<br>方法说明:判断是否是数字
- *<br>输入参数:String sPara。 需要判断的字符串
- *<br>返回类型:boolean。如果都是数字类型,返回true;否则返回false
- */
- public boolean isNumber(String sPara){
- int iPLength = sPara.length();
- for(int i=0;i<iPLength;i++){
- char cTemp = sPara.charAt(i);
- boolean bTemp = false;
- for(int j=0;j<cNum.length;j++){
- if(cTemp==cNum[j]){
- bTemp = true;
- break;
- }
- }
- if(!bTemp) return false;
- }
- return true;
- }
- /**
- *<br>方法说明:判断是否都是英文字符
- *<br>输入参数:String sPara。要检查的字符
- *<br>返回类型:boolean。如果都是字符返回true;反之为false
- */
- public boolean isString(String sPara){
- int iPLength = sPara.length();
- for(int i=0;i<iPLength;i++){
- char cTemp = sPara.charAt(i);
- boolean bTemp = false;
- for(int j=0;j<cStr.length;j++){
- if(cTemp==cStr[j]){
- bTemp = true;
- break;
- }
- }
- if(!bTemp) return false;
- }
- return true;
- }
- /**
- *<br>方法说明:判断是否是闰年
- *<br>输入参数:int iPara。要判断的年份
- *<br>返回类型:boolean。如果是闰年返回true,否则返回false
- */
- public boolean chickDay(int iPara){
- return iPara%100==0&&iPara%4==0;
- }
- /**
- *<br>方法说明:检查日期格式是否正确
- *<br>输入参数:String sPara。要检查的日期字符
- *<br>返回类型:int。0 日期格式正确,-1 月或这日不合要求, -2 年月日格式不正确
- */
- public int chickData(String sPara){
- @SuppressWarnings("unused")
- boolean bTemp = false;
- //所输入日期长度不正确
- if(sPara.length()!=10) return -2;
- //获取年
- String sYear = sPara.substring(0,4);
- //判断年是否为数字
- if(!isNumber(sYear)) return -2;
- //获取月份
- String sMonth = sPara.substring(5,7);
- //判断月份是否为数字
- if(!isNumber(sMonth)) return -2;
- //获取日
- String sDay = sPara.substring(8,10);
- //判断日是否为数字
- if(!isNumber(sDay)) return -2;
- //将年、月、日转换为数字
- int iYear = Integer.parseInt(sYear);
- int iMon = Integer.parseInt(sMonth);
- int iDay = Integer.parseInt(sDay);
- if(iMon>12) return -1;
- //闰年二月处理
- if(iMon==2&&chickDay(iYear)){
- if(iDay>29) return 2;
- }else{
- if(iDay>iMonth[iMon-1]) return -1;
- }
- return 0;
- }
- /**
- *<br>方法说明:主方法,测试用
- *<br>输入参数:
- *<br>返回类型:
- */
- public static void main(String[] arges){
- myArray mA = new myArray();
- //校验邮件地址
- boolean bMail = mA.isMail("tom@163.com");
- System.out.println("1 bMail is "+bMail);
- bMail = mA.isMail("tom@163com");
- System.out.println("2 bMail is "+bMail);
- //演示是否是数字
- boolean bIsNum = mA.isNumber("1234");
- System.out.println("1:bIsNum="+bIsNum);
- bIsNum = mA.isNumber("123r4");
- System.out.println("2:bIsNum="+bIsNum);
- //演示是否是英文字符
- boolean bIsStr = mA.isString("wer");
- System.out.println("1:bIsStr="+bIsStr);
- bIsStr = mA.isString("wer3");
- System.out.println("2:bIsStr="+bIsStr);
- //演示检查日期
- int iIsTime = mA.chickData("2003-12-98");
- System.out.println("1:iIsTime="+iIsTime);
- iIsTime = mA.chickData("2003-111-08");
- System.out.println("2:iIsTime="+iIsTime);
- iIsTime = mA.chickData("2003-10-08");
- System.out.println("3:iIsTime="+iIsTime);
- iIsTime = mA.chickData("2000-02-30");
- System.out.println("4:iIsTime="+iIsTime);
- }
- }
- package test4;
- import java.util.*;
- /**
- * Title: 矢量操作<
- * Description: 演示一个矢量(Vector)的基本操作
- * Filename: operateVector.java
- */
- public class operateVector
- {
- /*
- *<br>方法说明:生成一个4*4的二维Vector,供使用。
- *<br>输入参数:
- *<br>输出变量:Vector
- *<br>其它说明:
- */
- public Vector<Object> buildVector(){
- Vector<Object> vTemps = new Vector<Object>();
- for(int i=0;i<4;i++){
- Vector<Object> vTemp = new Vector<Object>();
- for (int j=0;j<4;j++){
- vTemp.addElement("Vector("+i+")("+j+")");
- }
- vTemps.addElement(vTemp);
- }
- return vTemps;
- }
- /*
- *<br>方法说明:插入数据
- *<br>输入参数:Vector vTemp 待插入的数据对象
- *<br>输入参数:int iTemp 插入数据的位置
- *<br>输入参数:Object oTemp 插入数据值
- *<br>输出变量:Vector 结果
- *<br>其它说明:如果插入位置超出实例实际的位置将返回null
- */
- public Vector<Object> insert(Vector<Object> vTemp,int iTemp,Object oTemp){
- if(iTemp>vTemp.size()){
- print("数据超界!");
- return null;
- }else{
- vTemp.insertElementAt(oTemp,iTemp);
- }
- return vTemp;
- }
- /*
- *<br>方法说明:移除数据
- *<br>输入参数:Vector vTemp 待删除矢量对象
- *<br>输入参数:int iTemp 删除数据的位置
- *<br>输出变量:Vector
- *<br>其它说明:如果删除超界的数据,将返回null
- */
- public Vector<Object> delete(Vector<Object> vTemp,int iTemp){
- if(iTemp>vTemp.size()){
- print("数据超界!");
- return null;
- }else{
- vTemp.removeElementAt(iTemp);
- }
- return vTemp;
- }
- /*
- *<br>方法说明:修改数据
- *<br>输入参数:Vector vTemp 待修改矢量对象
- *<br>输入参数:int iTemp 修改数据的位置
- *<br>输入参数:Object oTemp 修改数据值
- *<br>输出变量:Vector
- *<br>其它说明:如果修改位置超界的数据,将返回null
- */
- public Vector<Object> updata(Vector<Object> vTemp,int iTemp,Object oTemp){
- if(iTemp>vTemp.size()){
- print("数据超界!");
- return null;
- }else{
- vTemp.setElementAt(oTemp,iTemp);
- }
- return vTemp;
- }
- /*
- *<br>方法说明:输出信息
- *<br>输入参数:String sTemp 输出信息名称
- *<br>输入参数:Object oTemp 输出信息值
- *<br>返回变量:无
- */
- public void print(String sTemp,Vector<Object> oTemp){
- System.out.println(sTemp+"数据:");
- this.print(oTemp);
- }
- /**
- *<br>方法说明:打印输出(过载)
- *<br>输入参数:Object oPara 输出的对象
- *<br>返回类型:无
- */
- public void print(Object oPara){
- System.out.println(oPara);
- }
- /**
- *<br>方法说明:打印输出(过载)
- *<br>输入参数:Vector vPara 显示输出矢量对象
- *<br>返回类型:无
- */
- public void print(Vector<Object> vPara){
- for(int i=0;i<vPara.size();i++){
- System.out.println(vPara.elementAt(i));
- }
- }
- /**
- *<br>方法说明:主方法,程序入口
- *<br>输入参数:String[] args
- *<br>返回类型:无
- */
- public static void main(String[] args)
- {
- operateVector ov = new operateVector();
- Vector<Object> vTemp = ov.buildVector();
- ov.print("vTemp0",vTemp);
- Vector<Object> vResult = ov.insert(vTemp,2,"添加的数据");
- ov.print("vResult",vResult);
- Vector<Object> vResultup = ov.updata(vResult,2,"修改的数据");
- ov.print("vResultmp",vResultup);
- Vector<Object> vResultnow = ov.delete(vResultup,2);
- ov.print("vResultnow",vResultnow);
- }
- }
- package test5;
- import java.util.*;
- /**
- * Title: 哈希表操作
- * Description: 这是一个权限认证的例子,使用了哈希表作为数据的存储
- * Filename: RoleRight.java
- */
- public class RoleRight
- {
- private static Hashtable<String, String> rightList = new Hashtable<String, String>();
- /**
- *<br>方法说明:初始化数据
- *<br>输入参数:
- *<br>返回类型:
- */
- public void init()
- {
- String[] accRoleList = {"admin","satrap","manager","user","guest"};
- String[] rightCodeList = {"10001","10011","10021","20011","24011"};
- for(int i=0;i<accRoleList.length;i++)
- {
- rightList.put(accRoleList[i],rightCodeList[i]);
- }
- }
- /**
- *<br>方法说明:获取角色权限代码
- *<br>输入参数:String accRole 角色名称
- *<br>返回类型:String 权限代码
- */
- public String getRight(String accRole)
- {
- if(rightList.containsKey(accRole))
- return (String)rightList.get(accRole);
- else
- return null;
- }
- /**
- *<br>方法说明:添加角色和代码信息
- *<br>输入参数:String accRole 角色名称
- *<br>输入参数:String rightCode 角色权限代码
- *<br>返回类型:void (无)
- */
- public void insert(String accRole,String rightCode)
- {
- rightList.put(accRole,rightCode);
- }
- /**
- *<br>方法说明:删除角色权限
- *<br>输入参数:String accRole 角色名称
- *<br>返回类型:void(无)
- */
- public void delete(String accRole)
- {
- if(rightList.containsKey(accRole))
- rightList.remove(accRole);
- }
- /**
- *<br>方法说明:修改角色权限代码
- *<br>输入参数:String accRole 角色名称
- *<br>输入参数:String rightCode 角色权限代码
- *<br>返回类型:void(无)
- */
- public void update(String accRole,String rightCode)
- {
- //this.delete(accRole);
- this.insert(accRole,rightCode);
- }
- /**
- *<br>方法说明:打印哈希表中角色和代码对应表
- *<br>输入参数:无
- *<br>返回类型:无
- */
- public void print()
- {
- Enumeration<String> RLKey = rightList.keys();
- while(RLKey.hasMoreElements())
- {
- String accRole = RLKey.nextElement().toString();
- print(accRole+"="+this.getRight(accRole));
- }
- }
- /**
- *<br>方法说明:打印信息(过载)
- *<br>输入参数:Object oPara 打印的信息内容
- *<br>返回类型:无
- */
- public void print(Object oPara)
- {
- System.out.println(oPara);
- }
- /**
- *<br>方法说明:主方法,
- *<br>输入参数:
- *<br>返回类型:
- */
- public static void main(String[] args)
- {
- RoleRight RR = new RoleRight();
- RR.init();
- RR.print();
- RR.print("___________________________");
- RR.insert("presider","10110");
- RR.print();
- RR.print("___________________________");
- RR.update("presider","10100");
- RR.print();
- RR.print("___________________________");
- RR.delete("presider");
- RR.print();
- }
- }//end:)~
- package test6;
- /**
- * Title: 树参数
- * Description: 使用继承类,柳树就是树
- * Filename: osier.java
- */
- class tree
- {
- /**
- *<br>方法说明:树的树根
- */
- public void root()
- {
- String sSite = "土壤中";
- String sFunction = "吸收养份";
- print("位置:"+sSite);
- print("功能:"+sFunction);
- }
- /**
- *方法说明:树的树干
- */
- public void bolo()
- {
- String sSite = "地面";
- String sFunction = "传递养份";
- print("位置:"+sSite);
- print("功能:"+sFunction);
- }
- /**
- *方法说明:树的树枝
- */
- public void branch()
- {
- String sSite = "树干上";
- String sFunction = "传递养份";
- print("位置:"+sSite);
- print("功能:"+sFunction);
- }
- /**
- *方法说明:树的叶子
- */
- public void leaf()
- {
- String sSite = "树梢";
- String sFunction = "光合作用";
- String sColor = "绿色";
- print("位置:"+sSite);
- print("功能:"+sFunction);
- print("颜色:"+sColor);
- }
- /**
- *方法说明:显示信息
- *输入参数:Object oPara 显示的信息
- */
- public void print(Object oPara)
- {
- System.out.println(oPara);
- }
- /**
- *方法说明:主方法:
- */
- public static void main(String[] arges)
- {
- tree t = new tree();
- t.print("描述一棵树:");
- t.print("树根:");
- t.root();
- t.print("树干:");
- t.bolo();
- t.print("树枝:");
- t.branch();
- t.print("树叶:");
- t.leaf();
- }
- }
- /**
- * Title: 柳树参数
- * Description: 描述柳树的参数
- */
- class osier extends tree
- {
- /**
- *方法说明:过载树的树叶
- */
- public void leaf()
- {
- super.leaf();
- String sShape = "长形";
- super.print("形状:"+sShape);
- }
- /**
- *方法说明:扩展树的花
- */
- public void flower()
- {
- print("哈哈,柳树没有花!!");
- }
- /**
- *方法说明:主方法
- */
- public static void main(String[] args)
- {
- osier o = new osier();
- o.print("柳树树根:");
- o.root();
- o.print("柳树树干:");
- o.bolo();
- o.print("柳树树枝:");
- o.branch();
- o.print("柳树树叶:");
- o.leaf();
- o.print("柳树花:");
- o.flower();
- }
- }
- package test7;
- /**
- * Title: 接口和抽象函数
- * Description: 演示继承抽象函数和实现接口
- * Filename: newPlay.java
- */
- //接口
- interface player
- {
- int flag = 1;
- void play();//播放
- void pause();//暂停
- void stop();//停止
- }//end :)
- //抽象类
- abstract class playing
- {
- public void display(Object oPara)
- {
- System.out.println(oPara);
- }
- abstract void winRun();
- }//end :)
- //继承了playing抽象类和实现类player接口
- public class newPlay extends playing implements player
- {
- public void play()
- {
- display("newPlay.play()");//这里只是演示,去掉了代码。
- }
- public void pause()
- {
- display("newPlay.pause()");//这里只是演示,去掉了代码。
- }
- public void stop()
- {
- display("newPlay.stop()");//这里只是演示,去掉了代码。
- }
- void winRun()
- {
- display("newPlay.winRun()");//这里只是演示,去掉了代码。
- }
- public static void main(String[] args)
- {
- newPlay p = new newPlay();
- p.play();
- p.pause();
- p.stop();
- p.winRun();
- }
- }//end :)
- package test8.com;
- /**
- * Title: 标识符
- * Description: 演示标识符对类的访问控制
- * Filename:
- */
- public class classDemo1 {
- // 公有方法
- public void mechod1() {
- System.out.println("这是一个公有的方法!任何类都可以访问。");
- }
- // 授保护的方法
- protected void mechod2() {
- System.out.println("这是一个受到保护的方法!只有子类可以访问。");
- }
- // 私有的方法
- private void mechod3() {
- System.out.println("这是一个私有的方法!只有类本身才可以访问。");
- }
- public static void main(String[] args) {
- classDemo1 d = new classDemo1();
- d.mechod1();
- d.mechod2();
- d.mechod3();
- }
- }
- package test8.com;
- /**
- * Title: 标识符
- * Description: 演示标识符对类的访问控制
- * Filename:
- */
- public class classPlay
- {
- public static void main(String[] args){
- classDemo1 d = new classDemo1();
- d.mechod1();
- d.mechod2();
- //d.mechod3();
- }
- }
- package test8.net;
- import test8.com.classDemo1;
- /**
- * Title: 标识符
- * Description: 演示标识符对类的访问控制
- * Filename:
- */
- public class classPlay
- {
- public static void main(String[] args){
- classDemo1 d = new classDemo1();
- d.mechod1();
- //d.mechod2();
- //d.mechod3();
- }
- }
- package test9;
- /**
- * Title: 捕获异常和实现自己的异常
- * Description: 通过继承Exception类来实现自己的异常类。并使用try-catch来捕获这个异常。
- * Filename:
- */
- class MyException extends Exception {
- private static final long serialVersionUID = 1L;
- public MyException() {
- }
- public MyException(String msg) {
- super(msg);
- }
- public MyException(String msg, int x) {
- super(msg);
- i = x;
- }
- public int val() {
- return i;
- }
- private int i;
- }
- public class DemoException {
- /**
- *方法说明:使用MyException类中默认的构造器
- */
- public static void a() throws MyException {
- System.out.println("Throwing MyException from a()");
- throw new MyException();
- }
- /**
- *方法说明:使用MyException类中带信息的构造器
- */
- public static void b() throws MyException {
- System.out.println("Throwing MyException from b()");
- throw new MyException("Originated in b()");
- }
- /**
- *方法说明:使用了MyException中有编码的构造器
- */
- public static void c() throws MyException {
- System.out.println("Throwing MyException from c()");
- throw new MyException("Originated in c()", 47);
- }
- public static void main(String[] args) {
- try {
- a();
- } catch (MyException e) {
- e.getMessage();
- }
- try {
- b();
- } catch (MyException e) {
- e.toString();
- }
- try {
- c();
- } catch (MyException e) {
- e.printStackTrace();
- System.out.println("error code: " + e.val());
- }
- }
- } // end :)
- package test10;
- import javax.swing.*;
- import java.awt.*;
- /**
- * Title: 创建自己的窗体
- * Description:
- * Filename:mainFrame.java
- */
- public class mainFrame extends JFrame {
- private static final long serialVersionUID = 1L;
- /**
- *方法说明:构造器,通过传递参数来完成窗体的绘制。
- *输入参数:String sTitle 窗体标题
- *输入参数:int iWidth 窗体的宽度
- *输入参数:int iHeight 窗体的高度 返回类型:
- */
- public mainFrame(String sTitle, int iWidth, int iHeight) {
- Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();// 获取屏幕尺寸
- ImageIcon ii = new ImageIcon("middle.gif");
- setTitle(sTitle);// 设置窗体标题
- setIconImage(ii.getImage());// 设置窗体的图标
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);// 设置但关闭窗体时退出程序
- setSize(iWidth, iHeight);// 设置窗体大小
- int w = getSize().width;// 获取窗体宽度
- int h = getSize().height;// 获取窗体高度
- System.out.println("窗体宽:" + w + " 窗体高:" + h);
- int x = (dim.width - w) / 2;
- int y = (dim.height - h) / 2;
- setLocation(x, y);// 将窗体移到屏幕中间
- setVisible(true);// 显示窗体
- }
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);// 使用最新的SWING外观
- new mainFrame("main Frame Demo", 400, 300);
- }
- }
- package test11;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.KeyEvent;
- import javax.swing.AbstractButton;
- import javax.swing.ImageIcon;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- /**
- * Title: 按钮演示
- * Description: 提供一个按钮的演示。如何实现按钮和是一个按钮失效
- * Filename:
- */
- public class ButtonDemo extends JPanel
- implements ActionListener {
- private static final long serialVersionUID = 1L;
- protected JButton b1, b2, b3;
- /**
- *方法说明:构造器,初始图形界面构建
- */
- public ButtonDemo() {
- ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
- ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");
- ImageIcon rightButtonIcon = createImageIcon("images/left.gif");
- b1 = new JButton("失效中间按钮(D)", leftButtonIcon);
- b1.setVerticalTextPosition(AbstractButton.CENTER);//水平中间对齐
- b1.setHorizontalTextPosition(AbstractButton.LEADING);//相当于LEFT
- b1.setMnemonic(KeyEvent.VK_D);//将b1邦定alt+D键
- b1.setActionCommand("disable");
- b2 = new JButton("M中间按钮", middleButtonIcon);
- b2.setVerticalTextPosition(AbstractButton.BOTTOM);
- b2.setHorizontalTextPosition(AbstractButton.CENTER);
- b2.setMnemonic(KeyEvent.VK_M);//将b2邦定alt+M键
- b3 = new JButton("E激活中间按钮", rightButtonIcon);
- b3.setMnemonic(KeyEvent.VK_E);//将b3邦定alt+E键
- b3.setActionCommand("enable");
- b3.setEnabled(false);
- //给1和3添加事件监听
- b1.addActionListener(this);
- b3.addActionListener(this);
- //设置按钮提示文本
- b1.setToolTipText("点击这个按钮,将使中间的按钮失效!");
- b2.setToolTipText("点击这个按钮,没有任何的事件发生!");
- b3.setToolTipText("点击这个按钮,将使中间的按钮有效");
- //将按钮添加到JPanel中
- add(b1);
- add(b2);
- add(b3);
- }
- /**
- *方法说明:事件处理
- */
- public void actionPerformed(ActionEvent e) {
- if ("disable".equals(e.getActionCommand())) {
- b2.setEnabled(false);
- b1.setEnabled(false);
- b3.setEnabled(true);
- } else {
- b2.setEnabled(true);
- b1.setEnabled(true);
- b3.setEnabled(false);
- }
- }
- /**
- *方法说明:创建图标,
- *输入参数:String path 图标所在的路径
- *返回类型:ImageIcon 图标对象
- */
- protected static ImageIcon createImageIcon(String path) {
- java.net.URL imgURL = ButtonDemo.class.getResource(path);
- if (imgURL != null) {
- return new ImageIcon(imgURL);
- } else {
- System.err.println("Couldn't find file: " + path);
- return null;
- }
- }
- /**
- *方法说明:主方法
- */
- public static void main(String[] args) {
- //设置使用新的swing界面
- JFrame.setDefaultLookAndFeelDecorated(true);
- //创建一个窗体
- JFrame frame = new JFrame("ButtonDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //创建一个面板
- ButtonDemo newContentPane = new ButtonDemo();
- newContentPane.setOpaque(true);
- frame.setContentPane(newContentPane);
- //显示窗体
- frame.pack();
- frame.setVisible(true);
- }
- }
- package test12;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- /**
- * Title: 检查盒演示
- * Description: 选择不同的选择框显示不同的图片
- * Filename: CheckBoxDemo.java<
- */
- public class CheckBoxDemo extends JPanel
- implements ItemListener {
- private static final long serialVersionUID = 1L;
- JCheckBox chinButton;
- JCheckBox glassesButton;
- JCheckBox hairButton;
- JCheckBox teethButton;
- /*
- * 有四个检查盒,分别对应下巴、眼镜、头发和牙齿
- * 图片不是拼出来的,而是根据检查盒选择拼写图片文件名
- * 图片文件名的定义格式为"geek-XXXX.gif"
- * 其中 XXXX 根据检查盒的不同选择,而不同。它的格式如下:
- ---- //没有选择
- c--- //一个选择
- -g--
- --h-
- ---t
- cg-- //两个选择
- c-h-
- c--t
- -gh-
- -g-t
- --ht
- -ght //三个选择
- c-ht
- cg-t
- cgh-
- cght //所有都选
- */
- StringBuffer choices;
- JLabel pictureLabel;
- public CheckBoxDemo() {
- super(new BorderLayout());
- //创建检查盒
- chinButton = new JCheckBox("下巴(c)");
- chinButton.setMnemonic(KeyEvent.VK_C);
- chinButton.setSelected(true);
- glassesButton = new JCheckBox("眼镜(g)");
- glassesButton.setMnemonic(KeyEvent.VK_G);
- glassesButton.setSelected(true);
- hairButton = new JCheckBox("头发(h)");
- hairButton.setMnemonic(KeyEvent.VK_H);
- hairButton.setSelected(true);
- teethButton = new JCheckBox("牙齿(t)");
- teethButton.setMnemonic(KeyEvent.VK_T);
- teethButton.setSelected(true);
- //给检查盒添加监听
- chinButton.addItemListener(this);
- glassesButton.addItemListener(this);
- hairButton.addItemListener(this);
- teethButton.addItemListener(this);
- choices = new StringBuffer("cght");
- //放置一个带图片的标签
- pictureLabel = new JLabel();
- pictureLabel.setFont(pictureLabel.getFont().deriveFont(Font.ITALIC));
- updatePicture();
- //将检查盒放置到面版中
- JPanel checkPanel = new JPanel(new GridLayout(0, 1));
- checkPanel.add(chinButton);
- checkPanel.add(glassesButton);
- checkPanel.add(hairButton);
- checkPanel.add(teethButton);
- add(checkPanel, BorderLayout.LINE_START);
- add(pictureLabel, BorderLayout.CENTER);
- setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
- }
- /**
- *<br>方法说明:监听检查盒事件,拼凑图片的文件名XXXX部分
- *<br>输入参数:
- *<br>返回类型:
- */
- public void itemStateChanged(ItemEvent e) {
- int index = 0;
- char c = '-';
- Object source = e.getItemSelectable();
- if (source == chinButton) {
- index = 0;
- c = 'c';
- } else if (source == glassesButton) {
- index = 1;
- c = 'g';
- } else if (source == hairButton) {
- index = 2;
- c = 'h';
- } else if (source == teethButton) {
- index = 3;
- c = 't';
- }
- //取消选择事件
- if (e.getStateChange() == ItemEvent.DESELECTED) {
- c = '-';
- }
- //改变文件名字XXXX
- choices.setCharAt(index, c);
- updatePicture();
- }
- /**
- *<br>方法说明:绘制图片
- *<br>输入参数:
- *<br>返回类型:
- */
- protected void updatePicture() {
- //将得到的图片制成图标
- ImageIcon icon = createImageIcon(
- "images/geek/geek-"
- + choices.toString()
- + ".gif");
- pictureLabel.setIcon(icon);
- pictureLabel.setToolTipText(choices.toString());
- if (icon == null) {
- pictureLabel.setText("没有发现图片");
- } else {
- pictureLabel.setText(null);
- }
- }
- /**
- *<br>方法说明:获取图标
- *<br>输入参数:String path 图片路径
- *<br>返回类型:ImageIcon对象
- */
- protected static ImageIcon createImageIcon(String path) {
- java.net.URL imgURL = CheckBoxDemo.class.getResource(path);
- if (imgURL != null) {
- return new ImageIcon(imgURL);
- } else {
- System.err.println("Couldn't find file: " + path);
- return null;
- }
- }
- /**
- *<br>方法说明:主方法
- *<br>输入参数:
- *<br>返回类型:
- */
- public static void main(String s[]) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- //创建一个窗体,
- JFrame frame = new JFrame("CheckBoxDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //创建一个面板
- JComponent newContentPane = new CheckBoxDemo();
- newContentPane.setOpaque(true);
- frame.setContentPane(newContentPane);
- //显示窗体
- frame.pack();
- frame.setVisible(true);
- }
- }
- package test13;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import java.util.*;
- import java.text.SimpleDateFormat;
- /**
- * Title: ComboBox下拉域演示</p>
- * Description: 通过选择或这输入一种日期格式来格式化今天的日期
- * Filename: ComboBoxDemo.java
- */
- public class ComboBoxDemo extends JPanel
- implements ActionListener {
- private static final long serialVersionUID = 1L;
- static JFrame frame;
- JLabel result;
- String currentPattern;
- /**
- *方法说明:构造器。初始化窗体构件
- */
- public ComboBoxDemo() {
- setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
- String[] patternExamples = {
- "dd MMMMM yyyy",
- "dd.MM.yy",
- "MM/dd/yy",
- "yyyy.MM.dd G 'at' hh:mm:ss z",
- "EEE, MMM d, ''yy",
- "h:mm a",
- "H:mm:ss:SSS",
- "K:mm a,z",
- "yyyy.MMMMM.dd GGG hh:mm aaa"
- };
- currentPattern = patternExamples[0];
- //设置一个规范的用户界面
- JLabel patternLabel1 = new JLabel("输入一个字符格式或者");
- JLabel patternLabel2 = new JLabel("从下拉列表中选择一种:");
- JComboBox patternList = new JComboBox(patternExamples);
- patternList.setEditable(true);//标注这里ComboBox可进行编辑
- patternList.addActionListener(this);
- //创建一个显示结果用户界面
- JLabel resultLabel = new JLabel("当前 日期/时间",
- JLabel.LEADING);//相当于LEFT
- result = new JLabel(" ");
- result.setForeground(Color.black);
- result.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createLineBorder(Color.black),
- BorderFactory.createEmptyBorder(5,5,5,5)
- ));
- //布置构件
- JPanel patternPanel = new JPanel();
- patternPanel.setLayout(new BoxLayout(patternPanel,
- BoxLayout.PAGE_AXIS));
- patternPanel.add(patternLabel1);
- patternPanel.add(patternLabel2);
- patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
- patternPanel.add(patternList);
- JPanel resultPanel = new JPanel(new GridLayout(0, 1));
- resultPanel.add(resultLabel);
- resultPanel.add(result);
- patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
- resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
- add(patternPanel);
- add(Box.createRigidArea(new Dimension(0, 10)));
- add(resultPanel);
- setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
- reformat();
- }
- /**
- *方法说明:事件处理
- */
- public void actionPerformed(ActionEvent e) {
- JComboBox cb = (JComboBox)e.getSource();
- String newSelection = (String)cb.getSelectedItem();
- currentPattern = newSelection;
- reformat();
- }
- /**
- *方法说明:格式和显示今天的日期
- */
- public void reformat() {
- Date today = new Date();
- SimpleDateFormat formatter =
- new SimpleDateFormat(currentPattern);
- try {
- String dateString = formatter.format(today);
- result.setForeground(Color.black);
- result.setText(dateString);
- } catch (IllegalArgumentException iae) {
- result.setForeground(Color.red);
- result.setText("Error: " + iae.getMessage());
- }
- }
- /**
- *方法说明:主方法
- */
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- //创建一个窗体
- frame = new JFrame("ComboBoxDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //创建一个面版容器
- JComponent newContentPane = new ComboBoxDemo();
- newContentPane.setOpaque(true);
- frame.setContentPane(newContentPane);
- //显示窗体
- frame.pack();
- frame.setVisible(true);
- }
- }
- package test14;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import javax.swing.event.*;
- /**
- * Title: 列表框
- * Description: 通过输入框添加元素和点击“删除”按钮删除列表元素
- * Filename: ListDemo.java
- */
- public class ListDemo extends JPanel
- implements ListSelectionListener {
- private static final long serialVersionUID = 1L;
- private JList list;
- private DefaultListModel listModel;
- private static final String hireString = "添加";
- private static final String fireString = "删除";
- private JButton fireButton;
- private JTextField employeeName;
- public ListDemo() {
- super(new BorderLayout());
- //构建List的列表元素
- listModel = new DefaultListModel();
- listModel.addElement("Alan Sommerer");
- listModel.addElement("Alison Huml");
- listModel.addElement("Kathy Walrath");
- listModel.addElement("Lisa Friendly");
- listModel.addElement("Mary Campione");
- listModel.addElement("Sharon Zakhour");
- //创建一个List构件,并将列表元素添加到列表中
- list = new JList(listModel);
- //设置选择模式为单选
- list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- //初始化选择索引在0的位置,即第一个元素
- list.setSelectedIndex(0);
- list.addListSelectionListener(this);
- //设置列表可以同时看5个元素
- list.setVisibleRowCount(5);
- //给列表添加一个滑动块
- JScrollPane listScrollPane = new JScrollPane(list);
- JButton hireButton = new JButton(hireString);
- HireListener hireListener = new HireListener(hireButton);
- hireButton.setActionCommand(hireString);
- hireButton.addActionListener(hireListener);
- hireButton.setEnabled(false);
- fireButton = new JButton(fireString);
- fireButton.setActionCommand(fireString);
- fireButton.addActionListener(new FireListener());
- employeeName = new JTextField(10);
- employeeName.addActionListener(hireListener);
- employeeName.getDocument().addDocumentListener(hireListener);
- @SuppressWarnings("unused")
- String name = listModel.getElementAt(
- list.getSelectedIndex()).toString();
- //创建一个面板
- JPanel buttonPane = new JPanel();
- buttonPane.setLayout(new BoxLayout(buttonPane,
- BoxLayout.LINE_AXIS));
- buttonPane.add(fireButton);
- buttonPane.add(Box.createHorizontalStrut(5));
- buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
- buttonPane.add(Box.createHorizontalStrut(5));
- buttonPane.add(employeeName);
- buttonPane.add(hireButton);
- buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
- add(listScrollPane, BorderLayout.CENTER);
- add(buttonPane, BorderLayout.PAGE_END);
- }
- /**
- *类说明:“添加”按钮监听
- *类描述:当点击“添加”按钮后,实现将元素添加到列表框中
- */
- class FireListener implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- int index = list.getSelectedIndex();
- listModel.remove(index);
- int size = listModel.getSize();
- if (size == 0) { //如果没有了选择项,则是“删除”按钮实效
- fireButton.setEnabled(false);
- } else { //选择了一个
- if (index == listModel.getSize()) {
- //移除选项
- index--;
- }
- list.setSelectedIndex(index);
- list.ensureIndexIsVisible(index);
- }
- }
- }
- /**
- *类说明:“删除”按钮监听事件
- *类描述:实现删除列表元素
- */
- class HireListener implements ActionListener, DocumentListener {
- private boolean alreadyEnabled = false;
- private JButton button;
- public HireListener(JButton button) {
- this.button = button;
- }
- //必须实现 ActionListener.
- public void actionPerformed(ActionEvent e) {
- String name = employeeName.getText();
- //如果输入空或有同名
- if (name.equals("") || alreadyInList(name)) {
- Toolkit.getDefaultToolkit().beep();
- employeeName.requestFocusInWindow();
- employeeName.selectAll();
- return;
- }
- int index = list.getSelectedIndex(); //获取选择项
- if (index == -1) { //如果没有选择,就插入到第一个
- index = 0;
- } else { //如果有选择,那么插入到选择项的后面
- index++;
- }
- listModel.insertElementAt(employeeName.getText(), index);
- //重新设置文本
- employeeName.requestFocusInWindow();
- employeeName.setText("");
- //选择新的元素,并显示出来
- list.setSelectedIndex(index);
- list.ensureIndexIsVisible(index);
- }
- /**
- *方法说明:检测是否在LIST中有重名元素
- *输入参数:String name 检测的名字
- *返回类型:boolean 布尔值,如果存在返回true
- */
- protected boolean alreadyInList(String name) {
- return listModel.contains(name);
- }
- /**
- *方法说明:实现DocumentListener接口,必需实现的方法:
- */
- public void insertUpdate(DocumentEvent e) {
- enableButton();
- }
- /**
- *方法说明:实现DocumentListener接口,必需实现的方法
- */
- public void removeUpdate(DocumentEvent e) {
- handleEmptyTextField(e);
- }
- /**
- *方法说明:实现DocumentListener接口,必需实现的方法
- */
- public void changedUpdate(DocumentEvent e) {
- if (!handleEmptyTextField(e)) {
- enableButton();
- }
- }
- /**
- *方法说明:按钮使能
- */
- private void enableButton() {
- if (!alreadyEnabled) {
- button.setEnabled(true);
- }
- }
- /**
- *方法说明:实现DocumentListener接口,必需实现的方法,修改按钮的状态
- */
- private boolean handleEmptyTextField(DocumentEvent e) {
- if (e.getDocument().getLength() <= 0) {
- button.setEnabled(false);
- alreadyEnabled = false;
- return true;
- }
- return false;
- }
- }
- /**
- *方法说明:实现ListSelectionListener接口,必需实现的方法:
- */
- public void valueChanged(ListSelectionEvent e) {
- if (e.getValueIsAdjusting() == false) {
- if (list.getSelectedIndex() == -1) {
- fireButton.setEnabled(false);
- } else {
- fireButton.setEnabled(true);
- }
- }
- }
- /**
- *方法说明:主方法
- */
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- //创建一个窗体
- JFrame frame = new JFrame("ListDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //创建一个面版
- JComponent newContentPane = new ListDemo();
- newContentPane.setOpaque(true);
- frame.setContentPane(newContentPane);
- //显示窗体
- frame.pack();
- frame.setVisible(true);
- }
- }
- package test15;
- import javax.swing.JTabbedPane;
- import javax.swing.ImageIcon;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- import javax.swing.JFrame;
- /**
- * Title: 选项卡演示
- * Description: 这里是一个选项卡演示,点击不同的卡片,显示的内容不同
- * Filename: TabbedPaneDemo.java
- */
- import java.awt.*;
- public class TabbedPaneDemo extends JPanel {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public TabbedPaneDemo() {
- super(new GridLayout(1, 1));
- ImageIcon icon = createImageIcon("images/middle.gif");
- JTabbedPane tabbedPane = new JTabbedPane();
- Component panel1 = makeTextPanel("#第一个卡片#");
- tabbedPane.addTab("One", icon, panel1,
- "第一个卡片提示信息!");
- tabbedPane.setSelectedIndex(0);
- Component panel2 = makeTextPanel("##第二个卡片##");
- tabbedPane.addTab("Two", icon, panel2,
- "第二个卡片提示信息!");
- Component panel3 = makeTextPanel("###第三个卡片###");
- tabbedPane.addTab("Three", icon, panel3,
- "第三个卡片提示信息!");
- Component panel4 = makeTextPanel("####第四个卡片####");
- tabbedPane.addTab("Four", icon, panel4,
- "第四个卡片提示信息!");
- //将选项卡添加到panl中
- add(tabbedPane);
- }
- /**
- *方法说明:添加信息到选项卡中
- *输入参数:String text 显示的信息内容
- *返回类型:Component 成员对象
- */
- protected Component makeTextPanel(String text) {
- JPanel panel = new JPanel(false);
- JLabel filler = new JLabel(text);
- filler.setHorizontalAlignment(JLabel.CENTER);
- panel.setLayout(new GridLayout(1, 1));
- panel.add(filler);
- return panel;
- }
- /**
- *方法说明:获得图片
- *输入参数:String path 图片的路径
- *返回类型:ImageIcon 图片对象
- */
- protected static ImageIcon createImageIcon(String path) {
- java.net.URL imgURL = TabbedPaneDemo.class.getResource(path);
- if (imgURL != null) {
- return new ImageIcon(imgURL);
- } else {
- System.err.println("Couldn't find file: " + path);
- return null;
- }
- }
- public static void main(String[] args) {
- //使用Swing窗体描述
- JFrame.setDefaultLookAndFeelDecorated(true);
- //创建窗体
- JFrame frame = new JFrame("TabbedPaneDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.getContentPane().add(new TabbedPaneDemo(),
- BorderLayout.CENTER);
- //显示窗体
- frame.setSize(400, 200);
- frame.setVisible(true);
- }
- }
- package test16;
- import javax.swing.JOptionPane;
- import javax.swing.JDialog;
- import javax.swing.JTextField;
- import java.beans.*; //property change stuff
- import java.awt.*;
- import java.awt.event.*;
- /**
- * Title: 用户自定义对话框
- * Description: 自己定义对话框的风格。这使得对话框的样式更加多样化
- * Filename: CustomDialog.java
- */
- class CustomDialog extends JDialog
- implements ActionListener,
- PropertyChangeListener {
- private static final long serialVersionUID = 1L;
- private String typedText = null;
- private JTextField textField;
- private DialogDemo dd;
- private String magicWord;
- private JOptionPane optionPane;
- private String btnString1 = "确定";
- private String btnString2 = "取消";
- /**
- *方法说明:返回文本输入字符
- */
- public String getValidatedText() {
- return typedText;
- }
- /**
- *方法说明:创建一个结果对话框
- */
- public CustomDialog(Frame aFrame, String aWord, DialogDemo parent) {
- super(aFrame, true);
- dd = parent;
- magicWord = aWord.toUpperCase();
- setTitle("测试");
- textField = new JTextField(10);
- //定义显示信息
- String msgString1 = "李先生: jeck是你的英文名字吗?";
- String msgString2 = "(这个答案是: \"" + magicWord
- + "\"。)";
- Object[] array = {msgString1, msgString2, textField};
- Object[] options = {btnString1, btnString2};
- //创建对话框
- optionPane = new JOptionPane(array,
- JOptionPane.QUESTION_MESSAGE,
- JOptionPane.YES_NO_OPTION,
- null,
- options,
- options[0]);
- //显示对话框
- setContentPane(optionPane);
- //设置当关闭窗体动作模式
- setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
- addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent we) {
- optionPane.setValue(new Integer(
- JOptionPane.CLOSED_OPTION));
- }
- });
- //使的文本输入域得到焦点
- addComponentListener(new ComponentAdapter() {
- public void componentShown(ComponentEvent ce) {
- textField.requestFocusInWindow();
- }
- });
- //给文本域添加监听事件
- textField.addActionListener(this);
- //监听输入改变
- optionPane.addPropertyChangeListener(this);
- }
- /** 文本域监听处理 */
- public void actionPerformed(ActionEvent e) {
- optionPane.setValue(btnString1);
- }
- /** 监听输入的改变 */
- public void propertyChange(PropertyChangeEvent e) {
- String prop = e.getPropertyName();
- if (isVisible()
- && (e.getSource() == optionPane)
- && (JOptionPane.VALUE_PROPERTY.equals(prop) ||
- JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) {
- Object value = optionPane.getValue();
- if (value == JOptionPane.UNINITIALIZED_VALUE) {
- return;
- }
- optionPane.setValue(
- JOptionPane.UNINITIALIZED_VALUE);
- if (btnString1.equals(value)) {
- typedText = textField.getText();
- String ucText = typedText.toUpperCase();
- if (magicWord.equals(ucText)) {
- //如果输入有效,则清楚文本域并隐藏对话框
- clearAndHide();
- } else {
- //文本输入无效
- textField.selectAll();
- JOptionPane.showMessageDialog(
- CustomDialog.this,
- "对不起, \"" + typedText + "\" "
- + "是无效的输入。\n"
- + "请重新输入"
- + magicWord + ".",
- "再试一次",
- JOptionPane.ERROR_MESSAGE);
- typedText = null;
- textField.requestFocusInWindow();
- }
- } else { //用户关闭了对话框或点击了“cancel”
- dd.setLabel("好吧! "
- + "我们不能影响你的决定输入"
- + magicWord + "。");
- typedText = null;
- clearAndHide();
- }
- }
- }
- /**
- *方法说明:清楚文本域并隐藏痘翱蝌
- */
- public void clearAndHide() {
- textField.setText(null);
- setVisible(false);
- }
- }
- package test16;
- import javax.swing.JOptionPane;
- import javax.swing.JDialog;
- import javax.swing.JButton;
- import javax.swing.JRadioButton;
- import javax.swing.ButtonGroup;
- import javax.swing.JLabel;
- import javax.swing.ImageIcon;
- import javax.swing.BoxLayout;
- import javax.swing.Box;
- import javax.swing.BorderFactory;
- import javax.swing.border.Border;
- import javax.swing.JTabbedPane;
- import javax.swing.JPanel;
- import javax.swing.JFrame;
- import java.beans.*;
- import java.awt.*;
- import java.awt.event.*;
- /**
- *Title: 对话框演示
- *Description: 全面的演示各种类型的对话框的使用
- *Filename: DialogDemo.java
- */
- public class DialogDemo extends JPanel {
- private static final long serialVersionUID = 1L;
- JLabel label;
- ImageIcon icon = createImageIcon("images/middle.gif");
- JFrame frame;
- String simpleDialogDesc = "简单的信息提示对话窗";
- String iconDesc = "带有图标的对话窗";
- String moreDialogDesc = "复杂信息对话窗";
- CustomDialog customDialog;
- /**
- *方法说明:构造器,生成一个面板添加到JFrame中
- *输入参数:
- *返回类型:
- */
- public DialogDemo(JFrame frame) {
- super(new BorderLayout());
- this.frame = frame;
- customDialog = new CustomDialog(frame, "tom", this);
- customDialog.pack();
- //创建成员
- JPanel frequentPanel = createSimpleDialogBox();
- JPanel featurePanel = createFeatureDialogBox();
- JPanel iconPanel = createIconDialogBox();
- label = new JLabel("点击\"显示\" 按钮"
- + " 显示一个选择的对话框",
- JLabel.CENTER);
- //放置对象
- Border padding = BorderFactory.createEmptyBorder(20,20,5,20);
- frequentPanel.setBorder(padding);
- featurePanel.setBorder(padding);
- iconPanel.setBorder(padding);
- //创建选项卡
- JTabbedPane tabbedPane = new JTabbedPane();
- tabbedPane.addTab("简单对话窗", null,
- frequentPanel,
- simpleDialogDesc);
- tabbedPane.addTab("复杂对话窗", null,
- featurePanel,
- moreDialogDesc);
- tabbedPane.addTab("图标对话窗", null,
- iconPanel,
- iconDesc);
- add(tabbedPane, BorderLayout.CENTER);
- add(label, BorderLayout.PAGE_END);
- label.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
- }
- /**
- *方法说明:设置按钮上的文字
- *输入参数:String newText 添加的文字
- *返回类型:
- */
- void setLabel(String newText) {
- label.setText(newText);
- }
- /**
- *方法说明:获取图片
- *输入参数:String path 图片完整路径和名字
- *返回类型:ImageIcon 图片对象
- */
- protected static ImageIcon createImageIcon(String path) {
- java.net.URL imgURL = DialogDemo.class.getResource(path);
- if (imgURL != null) {
- return new ImageIcon(imgURL);
- } else {
- System.err.println("Couldn't find file: " + path);
- return null;
- }
- }
- /**
- *方法说明:创建一个JPanel,给第一个选项卡
- *输入参数:
- *返回类型:
- */
- private JPanel createSimpleDialogBox() {
- final int numButtons = 4;
- JRadioButton[] radioButtons = new JRadioButton[numButtons];
- final ButtonGroup group = new ButtonGroup();
- JButton showItButton = null;
- final String defaultMessageCommand = "default";
- final String yesNoCommand = "yesno";
- final String yeahNahCommand = "yeahnah";
- final String yncCommand = "ync";
- //添加单选到数字
- radioButtons[0] = new JRadioButton("只有“OK”按钮");
- radioButtons[0].setActionCommand(defaultMessageCommand);
- radioButtons[1] = new JRadioButton("有“Yes/No”二个按钮");
- radioButtons[1].setActionCommand(yesNoCommand);
- radioButtons[2] = new JRadioButton("有“Yes/No”两个按钮 "
- + "(程序添加文字)");
- radioButtons[2].setActionCommand(yeahNahCommand);
- radioButtons[3] = new JRadioButton("有“Yes/No/Cancel”三个按钮 "
- + "(程序添加文字)");
- radioButtons[3].setActionCommand(yncCommand);
- //将四个单选组成一个群
- for (int i = 0; i < numButtons; i++) {
- group.add(radioButtons[i]);
- }
- //设置第一个为默认选择
- radioButtons[0].setSelected(true);
- //定义“显示”按钮
- showItButton = new JButton("显示");
- //给“显示”按钮添加监听
- showItButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- String command = group.getSelection().getActionCommand();
- //ok对话窗
- if (command == defaultMessageCommand) {
- JOptionPane.showMessageDialog(frame,
- "鸡蛋不可能是绿色的!");
- //yes/no 对话窗
- } else if (command == yesNoCommand) {
- int n = JOptionPane.showConfirmDialog(
- frame, "你喜欢吃酸菜鱼吗?",
- "一个很无聊的问题!!",
- JOptionPane.YES_NO_OPTION);
- if (n == JOptionPane.YES_OPTION) {//选择yes
- setLabel("哇!我也是!");
- } else if (n == JOptionPane.NO_OPTION) {//选择no
- setLabel("唉!我喜欢吃!");
- } else {
- setLabel("快告诉我吧!");
- }
- //yes/no (自己输入选项)
- } else if (command == yeahNahCommand) {
- Object[] options = {"是的", "不喜欢"};
- int n = JOptionPane.showOptionDialog(frame,
- "你喜欢酸菜鱼吗?",
- "又一个无聊的问题!",
- JOptionPane.YES_NO_OPTION,
- JOptionPane.QUESTION_MESSAGE,
- null,
- options,
- options[0]);
- if (n == JOptionPane.YES_OPTION) {
- setLabel("你哄人的吧,我也喜欢。");
- } else if (n == JOptionPane.NO_OPTION) {
- setLabel("其实我也不喜欢!");
- } else {
- setLabel("这都不肯告诉我,小气鬼!");
- }
- //yes/no/cancel 对话框
- } else if (command == yncCommand) {
- Object[] options = {"是的,给我来一份。",
- "不,谢谢!",
- "不,我要水煮鱼!"};
- //构造对话框
- int n = JOptionPane.showOptionDialog(frame,
- "先生!我们这里有鲜美的酸菜鱼,您需要吗?",
- "服务生的问题。",
- JOptionPane.YES_NO_CANCEL_OPTION,
- JOptionPane.QUESTION_MESSAGE,
- null,
- options,
- options[2]);
- if (n == JOptionPane.YES_OPTION) {
- setLabel("你要的酸菜鱼来了!");
- } else if (n == JOptionPane.NO_OPTION) {
- setLabel("好的,你需要其它的。");
- } else if (n == JOptionPane.CANCEL_OPTION) {
- setLabel("好的,我们给你做水煮鱼!");
- } else {
- setLabel("对不起!你还没有点菜呢!");
- }
- }
- return;
- }
- });
- return createPane(simpleDialogDesc + ":",
- radioButtons,
- showItButton);
- }
- /**
- *方法说明:提供给createSimpleDialogBox和createFeatureDialogBox方法
- *方法说明:创建带提示信息、一列单选框和“显示”按钮
- *输入参数:String description 提示帮助信息
- *输入参数:JRadioButton[] radioButtons 单选框组
- *输入参数:JButton showButton “显示”按钮
- *返回类型:JPanel 添加好的面板
- */
- private JPanel createPane(String description,
- JRadioButton[] radioButtons,
- JButton showButton) {
- int numChoices = radioButtons.length;
- JPanel box = new JPanel();
- JLabel label = new JLabel(description);
- box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
- box.add(label);
- //添加radio
- for (int i = 0; i < numChoices; i++) {
- box.add(radioButtons[i]);
- }
- JPanel pane = new JPanel(new BorderLayout());
- pane.add(box, BorderLayout.PAGE_START);
- pane.add(showButton, BorderLayout.PAGE_END);
- return pane;
- }
- /**
- *方法说明:提供给createSimpleDialogBox和createFeatureDialogBox方法
- *方法说明:创建带提示信息、二列单选框和“显示”按钮
- *输入参数:String description 提示帮助信息
- *输入参数:JRadioButton[] radioButtons 单选框组
- *输入参数:JButton showButton “显示”按钮
- *返回类型:JPanel 添加好的面板
- */
- private JPanel create2ColPane(String description,
- JRadioButton[] radioButtons,
- JButton showButton) {
- JLabel label = new JLabel(description);
- int numPerColumn = radioButtons.length/2;
- JPanel grid = new JPanel(new GridLayout(0, 2));
- for (int i = 0; i < numPerColumn; i++) {
- grid.add(radioButtons[i]);
- grid.add(radioButtons[i + numPerColumn]);
- }
- JPanel box = new JPanel();
- box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
- box.add(label);
- grid.setAlignmentX(0.0f);
- box.add(grid);
- JPanel pane = new JPanel(new BorderLayout());
- pane.add(box, BorderLayout.PAGE_START);
- pane.add(showButton, BorderLayout.PAGE_END);
- return pane;
- }
- /**
- *方法说明:创建第三个选项卡的面板
- *方法说明:这里都是实现showMessageDialog类,但是也可以指定图标
- *输入参数:
- *返回类型:JPanel 构造好的面板
- */
- private JPanel createIconDialogBox() {
- JButton showItButton = null;
- final int numButtons = 6;
- JRadioButton[] radioButtons = new JRadioButton[numButtons];
- final ButtonGroup group = new ButtonGroup();
- final String plainCommand = "plain";
- final String infoCommand = "info";
- final String questionCommand = "question";
- final String errorCommand = "error";
- final String warningCommand = "warning";
- final String customCommand = "custom";
- radioButtons[0] = new JRadioButton("普通(没有图标)");
- radioButtons[0].setActionCommand(plainCommand);
- radioButtons[1] = new JRadioButton("信息图标");
- radioButtons[1].setActionCommand(infoCommand);
- radioButtons[2] = new JRadioButton("问题图标");
- radioButtons[2].setActionCommand(questionCommand);
- radioButtons[3] = new JRadioButton("错误图标");
- radioButtons[3].setActionCommand(errorCommand);
- radioButtons[4] = new JRadioButton("警告图标");
- radioButtons[4].setActionCommand(warningCommand);
- radioButtons[5] = new JRadioButton("自定义图标");
- radioButtons[5].setActionCommand(customCommand);
- for (int i = 0; i < numButtons; i++) {
- group.add(radioButtons[i]);
- }
- radioButtons[0].setSelected(true);
- showItButton = new JButton("显示");
- showItButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- String command = group.getSelection().getActionCommand();
- //没有图标
- if (command == plainCommand) {
- JOptionPane.showMessageDialog(frame,
- "水煮鱼里不要放酸菜!",
- "无图标",
- JOptionPane.PLAIN_MESSAGE);
- //信息图标
- } else if (command == infoCommand) {
- JOptionPane.showMessageDialog(frame,
- "水煮鱼里不要放酸菜!",
- "信息图标",
- JOptionPane.INFORMATION_MESSAGE);
- //问题图标
- } else if (command == questionCommand) {
- JOptionPane.showMessageDialog(frame,
- "请你吃饭前洗手,好吗?",
- "问题",
- JOptionPane.QUESTION_MESSAGE);
- //错误图标
- } else if (command == errorCommand) {
- JOptionPane.showMessageDialog(frame,
- "对不起,你的信用卡没有资金了!",
- "错误信息",
- JOptionPane.ERROR_MESSAGE);
- //警告图标
- } else if (command == warningCommand) {
- JOptionPane.showMessageDialog(frame,
- "警告!你严重透支信用卡,请尽快补齐金额!",
- "警告信息",
- JOptionPane.WARNING_MESSAGE);
- //自定义图标
- } else if (command == customCommand) {
- JOptionPane.showMessageDialog(frame,
- "哈哈。我想用什么图标都可以!",
- "自定义对话窗",
- JOptionPane.INFORMATION_MESSAGE,
- icon);
- }
- }
- });
- return create2ColPane(iconDesc + ":",
- radioButtons,
- showItButton);
- }
- /**
- *方法说明:创建一个JPanel,放在第二个选项卡上
- *输入参数:
- *返回类型:
- */
- private JPanel createFeatureDialogBox() {
- final int numButtons = 5;
- JRadioButton[] radioButtons = new JRadioButton[numButtons];
- final ButtonGroup group = new ButtonGroup();
- JButton showItButton = null;
- //定义操作命令
- final String pickOneCommand = "pickone";
- final String textEnteredCommand = "textfield";
- final String nonAutoCommand = "nonautooption";
- final String customOptionCommand = "customoption";
- final String nonModalCommand = "nonmodal";
- //定义radio数组
- radioButtons[0] = new JRadioButton("选择一个");
- radioButtons[0].setActionCommand(pickOneCommand);
- radioButtons[1] = new JRadioButton("输入信息");
- radioButtons[1].setActionCommand(textEnteredCommand);
- radioButtons[2] = new JRadioButton("关闭按钮无效");
- radioButtons[2].setActionCommand(nonAutoCommand);
- radioButtons[3] = new JRadioButton("输入校验"
- + "(用户输入信息)");
- radioButtons[3].setActionCommand(customOptionCommand);
- radioButtons[4] = new JRadioButton("没有模式");
- radioButtons[4].setActionCommand(nonModalCommand);
- //合成一个组群
- for (int i = 0; i < numButtons; i++) {
- group.add(radioButtons[i]);
- }
- //设置第一个为默认选择
- radioButtons[0].setSelected(true);
- showItButton = new JButton("显示");
- showItButton.addActionListener(new ActionListener() {
- @SuppressWarnings("static-access")
- public void actionPerformed(ActionEvent e) {
- String command = group.getSelection().getActionCommand();
- //选择一个
- if (command == pickOneCommand) {
- Object[] possibilities = {"辣椒", "西红柿", "洋葱"};
- //设置对话框
- String s = (String)JOptionPane.showInputDialog(
- frame, //所属窗体
- "请选择项目:\n"
- + "\"鸡蛋炒\"", //输出信息
- "客户选择",
- JOptionPane.PLAIN_MESSAGE, //对话框模式
- icon, //显示图标
- possibilities, //选项内容
- "辣椒"); //默认选项
- //如果有选择
- if ((s != null) && (s.length() > 0)) {
- setLabel("鸡蛋炒" + s + "!");
- return;
- }
- //如果客户没有选择
- setLabel("快点!");
- //文本输入
- } else if (command == textEnteredCommand) {
- String s = (String)JOptionPane.showInputDialog(
- frame,
- "选择一个配料\n"
- + "\"鸡蛋炒\"",
- "客户输入",
- JOptionPane.PLAIN_MESSAGE,
- icon,
- null,
- "辣椒");
- //如果用户有输入
- if ((s != null) && (s.length() > 0)) {
- setLabel("你要的是鸡蛋炒" + s + "!");
- return;
- }
- //如果返回的是空或者是null。
- setLabel("快些选择!");
- //关闭按钮无效
- } else if (command == nonAutoCommand) {
- //构造一个对话框面板
- final JOptionPane optionPane = new JOptionPane(
- "关闭这个对话框\n"
- + "请点击下面的按钮\n"
- + "明白吗?",
- JOptionPane.QUESTION_MESSAGE,
- JOptionPane.YES_NO_OPTION);
- JDialog.setDefaultLookAndFeelDecorated(false);
- //构造一个对话框
- final JDialog dialog = new JDialog(frame,
- "点击一个按钮",
- true);
- //将对话框面板添加到对话框中
- dialog.setContentPane(optionPane);
- //设置对话框关闭时的操作模式
- dialog.setDefaultCloseOperation(
- JDialog.DO_NOTHING_ON_CLOSE);
- dialog.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent we) { //当点击关闭按钮
- setLabel("阻碍用户视图关闭窗体!");
- }
- });
- JDialog.setDefaultLookAndFeelDecorated(true);
- optionPane.addPropertyChangeListener(
- new PropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent e) {
- String prop = e.getPropertyName();
- if (dialog.isVisible()
- && (e.getSource() == optionPane)
- && (JOptionPane.VALUE_PROPERTY.equals(prop))) {
- //如果你要阻止关闭按钮,可以在这里进行处理。
- dialog.setVisible(false);
- }
- }
- });
- dialog.pack();
- dialog.setLocationRelativeTo(frame);
- dialog.setVisible(true);
- int value = ((Integer)optionPane.getValue()).intValue();
- if (value == JOptionPane.YES_OPTION) {
- setLabel("好的");
- } else if (value == JOptionPane.NO_OPTION) {
- setLabel("试图点击关闭按钮来关闭一个不能关闭的对话框!"
- + "你不能!");
- } else {
- setLabel("窗体可以使用ESC键关闭。");
- }
- //自己定义版面
- } else if (command == customOptionCommand) {
- customDialog.setLocationRelativeTo(frame);
- customDialog.setVisible(true);
- String s = customDialog.getValidatedText();
- if (s != null) {
- //The text is valid.
- setLabel("欢迎你!"
- + "你已经进入了\""
- + s
- + "\"。");
- }
- //没有模式
- } else if (command == nonModalCommand) {
- //创建一个对话框
- final JDialog dialog = new JDialog(frame,
- "一个没有模式的对话框");
- //使用html语言来显示信息
- JLabel label = new JLabel("<html><p align=center>"
- + "这是一个没有模式的对话框"
- + "你可以使用更多的格式"
- + "甚至可以使用主窗体!");
- label.setHorizontalAlignment(JLabel.CENTER);
- Font font = label.getFont();
- label.setFont(label.getFont().deriveFont(font.PLAIN,
- 14.0f));
- JButton closeButton = new JButton("关闭");
- closeButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- dialog.setVisible(false);
- dialog.dispose();
- }
- });
- JPanel closePanel = new JPanel();
- closePanel.setLayout(new BoxLayout(closePanel,
- BoxLayout.LINE_AXIS));
- closePanel.add(Box.createHorizontalGlue());
- closePanel.add(closeButton);
- closePanel.setBorder(BorderFactory.
- createEmptyBorder(0,0,5,5));
- JPanel contentPane = new JPanel(new BorderLayout());
- contentPane.add(label, BorderLayout.CENTER);
- contentPane.add(closePanel, BorderLayout.PAGE_END);
- contentPane.setOpaque(true);
- dialog.setContentPane(contentPane);
- //显示窗体
- dialog.setSize(new Dimension(300, 150));
- dialog.setLocationRelativeTo(frame);
- dialog.setVisible(true);
- }
- }
- });
- return createPane(moreDialogDesc + ":",
- radioButtons,
- showItButton);
- }
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- JDialog.setDefaultLookAndFeelDecorated(true);
- //创建和设置一个窗体
- JFrame frame = new JFrame("DialogDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //设置一个面板
- Container contentPane = frame.getContentPane();
- contentPane.setLayout(new GridLayout(1,1));
- contentPane.add(new DialogDemo(frame));
- //显示窗体
- frame.pack();
- frame.setVisible(true);
- }
- }
- package test17;
- import java.io.*;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- /**
- * Title: 文件对话框演示
- * Description: 演示打开文件对话框和保存文件对话框,使用了文件过滤。
- * Filename: FileChooserDemo.java
- */
- public class FileChooserDemo extends JPanel
- implements ActionListener {
- private static final long serialVersionUID = 1L;
- static private final String newline = "\n";
- JButton openButton, saveButton;
- JTextArea log;
- JFileChooser fc;
- public FileChooserDemo() {
- super(new BorderLayout());
- log = new JTextArea(15,40);
- log.setMargin(new Insets(10,10,10,10));
- log.setEditable(false);
- JScrollPane logScrollPane = new JScrollPane(log);
- //创建一个文件过滤,使用当前目录
- fc = new JFileChooser(".");
- //过滤条件在MyFilter类中定义
- fc.addChoosableFileFilter(new MyFilter());
- openButton = new JButton("打开文件",
- createImageIcon("images/Open16.gif"));
- openButton.addActionListener(this);
- saveButton = new JButton("保存文件",
- createImageIcon("images/Save16.gif"));
- saveButton.addActionListener(this);
- //构建一个面板,添加“打开文件”和“保存文件”
- JPanel buttonPanel = new JPanel();
- buttonPanel.add(openButton);
- buttonPanel.add(saveButton);
- add(buttonPanel, BorderLayout.PAGE_START);
- add(logScrollPane, BorderLayout.CENTER);
- }
- /**
- *方法说明:事件处理
- *输入参数:
- *返回类型:
- */
- public void actionPerformed(ActionEvent e) {
- //当点击“打开文件”按钮
- if (e.getSource() == openButton) {
- int returnVal = fc.showOpenDialog(FileChooserDemo.this);
- if (returnVal == JFileChooser.APPROVE_OPTION) {
- File file = fc.getSelectedFile();
- //在这里添加一些对文件的处理
- log.append("打开文件: " + file.getName() + newline);
- } else {
- log.append("打开文件被用户取消!" + newline);
- }
- //点击“保存文件”按钮
- } else if (e.getSource() == saveButton) {
- int returnVal = fc.showSaveDialog(FileChooserDemo.this);
- if (returnVal == JFileChooser.APPROVE_OPTION) {
- File file = fc.getSelectedFile();
- //在这里添加一些对文件的处理
- log.append("保存文件: " + file.getName() + newline);
- } else {
- log.append("保存文件被用户取消!" + newline);
- }
- }
- }
- /**
- *方法说明:获取图像对象
- *输入参数:String path 图片路径
- *返回类型:ImageIcon 图片对象
- */
- protected static ImageIcon createImageIcon(String path) {
- java.net.URL imgURL = FileChooserDemo.class.getResource(path);
- if (imgURL != null) {
- return new ImageIcon(imgURL);
- } else {
- System.err.println("Couldn't find file: " + path);
- return null;
- }
- }
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- JDialog.setDefaultLookAndFeelDecorated(true);
- //创建窗体
- JFrame frame = new JFrame("FileChooserDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //创建一个面板
- JComponent newContentPane = new FileChooserDemo();
- newContentPane.setOpaque(true);
- frame.setContentPane(newContentPane);
- //显示窗体
- frame.pack();
- frame.setVisible(true);
- }
- }
- package test17;
- import java.io.File;
- import javax.swing.filechooser.*;
- /**
- * Title: 文件过滤器演示
- * Description: FileChooserDemo文件使用的文件过滤器
- * Filename: MyFilter.java
- */
- public class MyFilter extends FileFilter {
- @SuppressWarnings("unused")
- private String files;
- public boolean accept(File f) {
- if (f.isDirectory()) {
- return true;
- }
- String extension = getExtension(f);
- if (extension != null) {
- if (extension.equals("java")) {//定义过滤Java文件
- return true;
- } else {
- return false;
- }
- }
- return false;
- }
- //过滤器描述
- public String getDescription() {
- return "Java";
- }
- /**
- *方法说明:获取文件扩展名
- */
- public static String getExtension(File f) {
- String ext = null;
- String s = f.getName();
- int i = s.lastIndexOf('.');
- if (i > 0 && i < s.length() - 1) {
- ext = s.substring(i+1).toLowerCase();
- }
- return ext;
- }
- }
- package test18;
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- /**
- * Description: 这里演示使用html语言在swing面板上构造显示信息
- * Filename: HtmlDemo.java
- */
- public class HtmlDemo extends JPanel
- implements ActionListener {
- private static final long serialVersionUID = 1L;
- JLabel theLabel;
- JTextArea htmlTextArea;
- /**
- *方法说明:构造器,描述窗体中的成员
- *输入参数:
- *返回类型:
- */
- public HtmlDemo() {
- setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
- String initialText = "<html>\n" +
- "颜色和字体测试:\n" +
- "<ul>\n" +
- "<li><font color=red>red</font>\n" +
- "<li><font color=blue>blue</font>\n" +
- "<li><font color=green>green</font>\n" +
- "<li><font size=-2>small</font>\n" +
- "<li><font size=+2>large</font>\n" +
- "<li><i>italic</i>\n" +
- "<li><b>bold</b>\n" +
- "</ul>\n";
- //定义一个文本框
- htmlTextArea = new JTextArea(10, 20);
- htmlTextArea.setText(initialText);
- JScrollPane scrollPane = new JScrollPane(htmlTextArea);
- //定义按钮
- JButton changeTheLabel = new JButton("改变显示");
- changeTheLabel.setMnemonic(KeyEvent.VK_C);
- changeTheLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
- changeTheLabel.addActionListener(this);
- //定义标签
- theLabel = new JLabel(initialText) {
- private static final long serialVersionUID = 1L;
- public Dimension getPreferredSize() {
- return new Dimension(200, 200);
- }
- public Dimension getMinimumSize() {
- return new Dimension(200, 200);
- }
- public Dimension getMaximumSize() {
- return new Dimension(200, 200);
- }
- };
- //设置标签的对齐方式
- theLabel.setVerticalAlignment(SwingConstants.CENTER);
- theLabel.setHorizontalAlignment(SwingConstants.CENTER);
- //构造一个带边框的左边的编辑面板
- JPanel leftPanel = new JPanel();
- leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
- leftPanel.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder(
- "编辑HTML,点击按钮显示结果。"),
- BorderFactory.createEmptyBorder(10,10,10,10)));
- leftPanel.add(scrollPane);
- leftPanel.add(Box.createRigidArea(new Dimension(0,10)));
- leftPanel.add(changeTheLabel);
- //构造一个带边框的右边显示的面板
- JPanel rightPanel = new JPanel();
- rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));
- rightPanel.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder("这里使用标签显示HTML结果"),
- BorderFactory.createEmptyBorder(10,10,10,10)));
- rightPanel.add(theLabel);
- setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
- add(leftPanel);
- add(Box.createRigidArea(new Dimension(10,0)));
- add(rightPanel);
- }
- /**
- *方法说明:事件监听,当用户点击按钮触发
- *输入参数:
- *返回类型:
- */
- public void actionPerformed(ActionEvent e) {
- theLabel.setText(htmlTextArea.getText());
- }
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- //创建窗体
- JFrame frame = new JFrame("HtmlDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //创建面板
- JComponent newContentPane = new HtmlDemo();
- newContentPane.setOpaque(true);
- frame.setContentPane(newContentPane);
- //显示窗体
- frame.pack();
- frame.setVisible(true);
- }
- }
- package test19;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.JPopupMenu;
- import javax.swing.JMenu;
- import javax.swing.JMenuItem;
- import javax.swing.JCheckBoxMenuItem;
- import javax.swing.JRadioButtonMenuItem;
- import javax.swing.ButtonGroup;
- import javax.swing.JMenuBar;
- import javax.swing.KeyStroke;
- import javax.swing.ImageIcon;
- import javax.swing.JPanel;
- import javax.swing.JTextArea;
- import javax.swing.JScrollPane;
- import javax.swing.JFrame;
- /**
- * Title: 菜单演示
- * Description: 演示菜单的建立和快捷键的使用。
- * Filename: MenuDemo.java
- */
- public class MenuDemo implements ActionListener, ItemListener {
- JTextArea output;
- JScrollPane scrollPane;
- String newline = "\n";
- /**
- *方法说明:组建菜单栏
- *输入参数:
- *返回类型:
- */
- public JMenuBar createMenuBar() {
- JMenuBar menuBar;
- JMenu menu, submenu;
- JMenuItem menuItem;
- JRadioButtonMenuItem rbMenuItem;
- JCheckBoxMenuItem cbMenuItem;
- //定义菜单条
- menuBar = new JMenuBar();
- //定义第一个菜单
- menu = new JMenu("(A)菜单");
- menu.setMnemonic(KeyEvent.VK_A);
- menuBar.add(menu);
- //下面开始定义菜单项
- //只有文字
- menuItem = new JMenuItem("(O)只有文本的菜单",
- KeyEvent.VK_O);
- //设置快捷键
- menuItem.setAccelerator(KeyStroke.getKeyStroke(
- KeyEvent.VK_1, ActionEvent.ALT_MASK));
- //添加监听
- menuItem.addActionListener(this);
- menu.add(menuItem);
- //有图标还有文字
- ImageIcon icon = createImageIcon("images/middle.gif");
- menuItem = new JMenuItem("(B)有图标和文字的菜单", icon);
- menuItem.setMnemonic(KeyEvent.VK_B);
- menuItem.addActionListener(this);
- menu.add(menuItem);
- //只有图标
- menuItem = new JMenuItem(icon);
- menuItem.setMnemonic(KeyEvent.VK_D);
- menuItem.addActionListener(this);
- menu.add(menuItem);
- //定义一组radio button(单选按钮)菜单
- menu.addSeparator();
- ButtonGroup group = new ButtonGroup();
- rbMenuItem = new JRadioButtonMenuItem("(R)使用radio的菜单");
- rbMenuItem.setSelected(true);
- rbMenuItem.setMnemonic(KeyEvent.VK_R);
- group.add(rbMenuItem);
- rbMenuItem.addActionListener(this);
- menu.add(rbMenuItem);
- rbMenuItem = new JRadioButtonMenuItem("(d)另外一个radio菜单");
- rbMenuItem.setMnemonic(KeyEvent.VK_D);
- group.add(rbMenuItem);
- rbMenuItem.addActionListener(this);
- menu.add(rbMenuItem);
- //定义一组check box(检查盒)菜单
- menu.addSeparator();
- cbMenuItem = new JCheckBoxMenuItem("(C)使用检查盒的菜单");
- cbMenuItem.setMnemonic(KeyEvent.VK_C);
- cbMenuItem.addItemListener(this);
- menu.add(cbMenuItem);
- cbMenuItem = new JCheckBoxMenuItem("(H)另外一个检查盒");
- cbMenuItem.setMnemonic(KeyEvent.VK_H);
- cbMenuItem.addItemListener(this);
- menu.add(cbMenuItem);
- //定义一个带子菜单
- menu.addSeparator();
- submenu = new JMenu("(S)带有子菜单");
- submenu.setMnemonic(KeyEvent.VK_S);
- //定义子菜单
- menuItem = new JMenuItem("这是子菜单");
- //定义快捷键
- menuItem.setAccelerator(KeyStroke.getKeyStroke(
- KeyEvent.VK_2, ActionEvent.ALT_MASK));
- menuItem.addActionListener(this);
- submenu.add(menuItem);
- menuItem = new JMenuItem("子菜单项");
- menuItem.addActionListener(this);
- submenu.add(menuItem);
- menu.add(submenu);
- //定义第二个菜单
- menu = new JMenu("(N)第二个菜单");
- menu.setMnemonic(KeyEvent.VK_N);
- menuBar.add(menu);
- return menuBar;
- }
- /**
- *方法说明:构建面板
- *输入参数:
- *返回类型:
- */
- public Container createContentPane() {
- //构造一个面板
- JPanel contentPane = new JPanel(new BorderLayout());
- contentPane.setOpaque(true);
- //定义一个文本域
- output = new JTextArea(5, 30);
- output.setEditable(false);
- scrollPane = new JScrollPane(output);
- //将文本域添加到面板中
- contentPane.add(scrollPane, BorderLayout.CENTER);
- return contentPane;
- }
- /**
- *方法说明:构建弹出菜单
- *输入参数:
- *返回类型:
- */
- public void createPopupMenu() {
- JMenuItem menuItem;
- //构件弹出菜单
- JPopupMenu popup = new JPopupMenu();
- ImageIcon openicon = createImageIcon("images/Open16.gif");
- menuItem = new JMenuItem("打开文件",openicon);
- menuItem.addActionListener(this);
- popup.add(menuItem);
- ImageIcon saveicon = createImageIcon("images/Save16.gif");
- menuItem = new JMenuItem("保存文件",saveicon);
- menuItem.addActionListener(this);
- popup.add(menuItem);
- //添加一个监听给文本域,以便点击右键时响应
- MouseListener popupListener = new PopupListener(popup);
- output.addMouseListener(popupListener);
- }
- /**
- *方法说明:监听普通的菜单选择
- *输入参数:ActionEvent e 事件
- *返回类型:
- */
- public void actionPerformed(ActionEvent e) {
- JMenuItem source = (JMenuItem)(e.getSource());
- String s = "监测事件。"
- + newline
- + " 事件源: " + source.getText()
- + " (选择对象" + getClassName(source) + ")";
- output.append(s + newline);
- }
- /**
- *方法说明:监听检查盒菜单选择项
- *输入参数:ItemEvent e 检查盒触发的事件
- *返回类型:
- */
- public void itemStateChanged(ItemEvent e) {
- JMenuItem source = (JMenuItem)(e.getSource());
- String s = "菜单项监听"
- + newline
- + " 事件源: " + source.getText()
- + " (选择对象 " + getClassName(source) + ")"
- + newline
- + " 新的状态: "
- + ((e.getStateChange() == ItemEvent.SELECTED) ?
- "选择":"不选择");
- output.append(s + newline);
- }
- /**
- *方法说明:获得类的名字
- *输入参数:
- *返回类型:
- */
- protected String getClassName(Object o) {
- String classString = o.getClass().getName();
- int dotIndex = classString.lastIndexOf(".");
- return classString.substring(dotIndex+1);
- }
- /**
- *方法说明:根据路径查找图片
- *输入参数:String path 图片的路径
- *返回类型:ImageIcon 图片对象
- */
- protected static ImageIcon createImageIcon(String path) {
- java.net.URL imgURL = MenuDemo.class.getResource(path);
- if (imgURL != null) {
- return new ImageIcon(imgURL);
- } else {
- System.err.println("Couldn't find file: " + path);
- return null;
- }
- }
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- //创建一个窗体
- JFrame frame = new JFrame("MenuDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //创建菜单,并添加到面板中
- MenuDemo demo = new MenuDemo();
- frame.setJMenuBar(demo.createMenuBar());
- frame.setContentPane(demo.createContentPane());
- //生成弹出菜单
- demo.createPopupMenu();
- //显示窗体
- frame.setSize(450, 260);
- frame.setVisible(true);
- }
- //弹出菜单监听类
- class PopupListener extends MouseAdapter {
- JPopupMenu popup;
- PopupListener(JPopupMenu popupMenu) {
- popup = popupMenu;
- }
- public void mousePressed(MouseEvent e) {
- maybeShowPopup(e);
- }
- public void mouseReleased(MouseEvent e) {
- maybeShowPopup(e);
- }
- private void maybeShowPopup(MouseEvent e) {
- if (e.isPopupTrigger()) {
- popup.show(e.getComponent(),
- e.getX(), e.getY());
- }
- }
- }
- }
- package test20;
- import javax.swing.JToolBar;
- import javax.swing.JButton;
- import javax.swing.ImageIcon;
- import javax.swing.JFrame;
- import javax.swing.JTextArea;
- import javax.swing.JScrollPane;
- import javax.swing.JPanel;
- import java.net.URL;
- import java.awt.*;
- import java.awt.event.*;
- /**
- * Title: 工具栏演示
- * Description: 提供一个工具栏,包括“打开”、“保存”、“搜索”工具按钮
- * Filename: ToolBarDemo.java
- */
- public class ToolBarDemo extends JPanel
- implements ActionListener {
- private static final long serialVersionUID = 1L;
- protected JTextArea textArea;
- protected String newline = "\n";
- static final private String OPEN = "OPEN";
- static final private String SAVE = "SAVE";
- static final private String SEARCH = "SEARCH";
- /**
- *方法说明:构造器
- *输入参数:
- *返回类型:
- */
- public ToolBarDemo() {
- super(new BorderLayout());
- //创建工具栏
- JToolBar toolBar = new JToolBar();
- addButtons(toolBar);
- //创建一个文本域,用来输出一些信息
- textArea = new JTextArea(15, 30);
- textArea.setEditable(false);
- JScrollPane scrollPane = new JScrollPane(textArea);
- //安放成员
- setPreferredSize(new Dimension(450, 110));
- add(toolBar, BorderLayout.PAGE_START);
- add(scrollPane, BorderLayout.CENTER);
- }
- /**
- *方法说明:构建工具栏
- *输入参数:JToolBar toolBar 工具条
- *返回类型:
- */
- protected void addButtons(JToolBar toolBar) {
- JButton button = null;
- //第一个按钮,“打开”
- button = makeNavigationButton("Open16", OPEN,
- "打开一个文件!",
- "打开");
- toolBar.add(button);
- //第二个按钮,“保存”
- button = makeNavigationButton("Save16", SAVE,
- "保存当前文件!",
- "保存");
- toolBar.add(button);
- //第三个按钮,“搜索”
- button = makeNavigationButton("Search16", SEARCH,
- "搜索文件中的字符!",
- "搜索");
- toolBar.add(button);
- }
- /**
- *方法说明:构造工具栏上的按钮
- *输入参数:
- *返回类型:
- */
- protected JButton makeNavigationButton(String imageName,
- String actionCommand,
- String toolTipText,
- String altText) {
- //搜索图片
- String imgLocation = "images/"
- + imageName
- + ".gif";
- URL imageURL = ToolBarDemo.class.getResource(imgLocation);
- //初始化工具按钮
- JButton button = new JButton();
- //设置按钮的命令
- button.setActionCommand(actionCommand);
- //设置提示信息
- button.setToolTipText(toolTipText);
- button.addActionListener(this);
- if (imageURL != null) { //找到图像
- button.setIcon(new ImageIcon(imageURL));
- } else { //没有图像
- button.setText(altText);
- System.err.println("Resource not found: "
- + imgLocation);
- }
- return button;
- }
- /**
- *方法说明:事件监听
- *输入参数:
- *返回类型:
- */
- public void actionPerformed(ActionEvent e) {
- String cmd = e.getActionCommand();
- String description = null;
- if (OPEN.equals(cmd)) { //点击第一个按钮
- description = "打开一个文件操作!";
- } else if (SAVE.equals(cmd)) { //点击第二个按钮
- description = "保存文件操作";
- } else if (SEARCH.equals(cmd)) { //点击第三个按钮
- description = "搜索字符操作";
- }
- displayResult("如果这里是真正的程序,你将进入: "
- + description);
- }
- protected void displayResult(String actionDescription) {
- textArea.append(actionDescription + newline);
- }
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- //定义窗体
- JFrame frame = new JFrame("ToolBarDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //定义面板
- ToolBarDemo newContentPane = new ToolBarDemo();
- newContentPane.setOpaque(true);
- frame.setContentPane(newContentPane);
- //显示窗体
- frame.pack();
- frame.setVisible(true);
- }
- }
- package test21;
- import javax.swing.JDesktopPane;
- import javax.swing.JMenu;
- import javax.swing.JMenuItem;
- import javax.swing.JMenuBar;
- import javax.swing.JFrame;
- import javax.swing.KeyStroke;
- import java.awt.event.*;
- import java.awt.*;
- /**
- * Title: 内部窗体演示
- * Description: 这是演示一个内部窗体。可以选择“新文档”菜单不停的生成内部窗体。
- * Filename:
- */
- public class InternalFrameDemo extends JFrame
- implements ActionListener {
- private static final long serialVersionUID = 1L;
- JDesktopPane desktop;
- /**
- *方法说明:构造器,添加窗体成员
- *输入参数:
- *返回类型:
- */
- public InternalFrameDemo() {
- super("InternalFrameDemo");
- //这里设置了一个比较大的窗体,给四周只留了50px的边界
- int inset = 50;
- Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
- setBounds(inset, inset,
- screenSize.width - inset*2,
- screenSize.height - inset*2);
- //定义界面
- desktop = new JDesktopPane(); //桌面面板
- createFrame(); //创建第一个内部窗体
- setContentPane(desktop);//将桌面添加到窗体
- setJMenuBar(createMenuBar());
- //设置托拽模式
- desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
- }
- /**
- *方法说明:组建菜单
- *输入参数:
- *返回类型:
- */
- protected JMenuBar createMenuBar() {
- JMenuBar menuBar = new JMenuBar();
- //定义一个菜单
- JMenu menu = new JMenu("文件");
- menu.setMnemonic(KeyEvent.VK_D);
- menuBar.add(menu);
- //定义“新文档”菜单
- JMenuItem menuItem = new JMenuItem("新文档");
- menuItem.setMnemonic(KeyEvent.VK_N);
- menuItem.setAccelerator(KeyStroke.getKeyStroke(
- KeyEvent.VK_N, ActionEvent.ALT_MASK));
- menuItem.setActionCommand("new");
- menuItem.addActionListener(this);
- menu.add(menuItem);
- //定义“退出”菜单
- menuItem = new JMenuItem("退出");
- menuItem.setMnemonic(KeyEvent.VK_Q);
- menuItem.setAccelerator(KeyStroke.getKeyStroke(
- KeyEvent.VK_Q, ActionEvent.ALT_MASK));
- menuItem.setActionCommand("quit");
- menuItem.addActionListener(this);
- menu.add(menuItem);
- return menuBar;
- }
- /**
- *方法说明:事件监听,对选择的菜单做出反映
- *输入参数:ActionEvent e 事件
- *返回类型:
- */
- public void actionPerformed(ActionEvent e) {
- if ("new".equals(e.getActionCommand())) { //新文档
- createFrame();
- } else { //退出
- quit();
- }
- }
- /**
- *方法说明:调用MyInternalFrame类创建新的内部窗体,
- *输入参数:
- *返回类型:
- */
- protected void createFrame() {
- MyInternalFrame frame = new MyInternalFrame();
- frame.setVisible(true);
- desktop.add(frame);
- try {
- frame.setSelected(true);
- } catch (java.beans.PropertyVetoException e) {}
- }
- /**
- *方法说明:退出程序
- *输入参数:
- *返回类型:
- */
- protected void quit() {
- System.exit(0);
- }
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- //建立一个内部窗体
- InternalFrameDemo frame = new InternalFrameDemo();
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //显示窗体
- frame.setVisible(true);
- }
- }
- package test21;
- import javax.swing.JInternalFrame;
- import javax.swing.JTextArea;
- /**
- * Title: 内部窗体
- * Description: 生成一个内部窗体,提供InternalFrameDemo类使用
- * Filename: MyInternalFrame.java
- */
- public class MyInternalFrame extends JInternalFrame {
- private static final long serialVersionUID = 1L;
- static int openFrameCount = 0;
- static final int xOffset = 30, yOffset = 30;
- public MyInternalFrame() {
- super("文档 #" + (++openFrameCount),
- true, //可变尺寸
- true, //有关闭按钮
- true, //有最大化按钮
- true);//最小化按钮
- //给内部窗体添加一个文本域
- JTextArea j = new JTextArea(5,20);
- getContentPane().add(j);
- //设置内部窗体的大小
- setSize(300,300);
- //设置内部窗体的显示位置
- setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
- }
- }
- package test22;
- import java.awt.*;
- import javax.swing.*;
- import javax.swing.event.*;
- /**
- * Title: 分割面板
- * Description: 演示将面板分割成左右两部分
- * Fiename:SplitPaneDemo.java
- */
- public class SplitPaneDemo implements ListSelectionListener {
- private String[] imageNames={"Bird.gif","Cat.gif","Dog.gif","Pig.gif"};
- private JLabel picture;
- private JList list;
- private JSplitPane splitPane;
- /**
- *方法说明:构造器,定义了所有要使用的构件
- *输入参数:
- *返回类型:
- */
- public SplitPaneDemo() {
- //创建一个图像名称的列表,设置为单选方式
- list = new JList(imageNames);
- list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- list.setSelectedIndex(0);
- list.addListSelectionListener(this);
- JScrollPane listScrollPane = new JScrollPane(list);
- //获取默认的图片
- ImageIcon firstImage = createImageIcon("images/" +
- (String)imageNames[0]);
- if (firstImage != null) {
- picture = new JLabel(firstImage);
- picture.setPreferredSize(new Dimension(firstImage.getIconWidth(),
- firstImage.getIconHeight()));
- } else {
- picture = new JLabel((String)imageNames[0]);
- }
- JScrollPane pictureScrollPane = new JScrollPane(picture);
- //创建一个水平分割的面板,定义了两个面板的名字。
- splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,
- listScrollPane, pictureScrollPane);
- splitPane.setOneTouchExpandable(true);
- splitPane.setDividerLocation(150);
- //定义面板的最小尺寸
- Dimension minimumSize = new Dimension(100, 50);
- listScrollPane.setMinimumSize(minimumSize);
- pictureScrollPane.setMinimumSize(minimumSize);
- //定义初始尺寸
- splitPane.setPreferredSize(new Dimension(400, 200));
- }
- /**
- *方法说明:获得这个分割的面板
- *输入参数:
- *返回类型:JSplitPane 对象
- */
- public JSplitPane getSplitPane() {
- return splitPane;
- }
- /**
- *方法说明:列表监听事件处理
- *输入参数:ListSelectionEvent e 列表选择事件
- *返回类型:
- */
- public void valueChanged(ListSelectionEvent e) {
- if (e.getValueIsAdjusting())
- return;
- JList theList = (JList)e.getSource();
- if (theList.isSelectionEmpty()) {
- picture.setIcon(null);
- picture.setText(null);
- } else {
- int index = theList.getSelectedIndex();
- ImageIcon newImage = createImageIcon("images/" +
- (String)imageNames[index]);
- picture.setIcon(newImage);
- if (newImage != null) {
- picture.setText(null);
- picture.setPreferredSize(new Dimension(newImage.getIconWidth(),
- newImage.getIconHeight() ));
- } else {
- picture.setText("Image not found: "
- + (String)imageNames[index]);
- }
- picture.revalidate();
- }
- }
- /**
- *方法说明:根据路径获取图形对象
- *输入参数:String path 图片路径
- *返回类型:ImageIcon 图片对象
- */
- protected static ImageIcon createImageIcon(String path) {
- java.net.URL imgURL = SplitPaneDemo.class.getResource(path);
- if (imgURL != null) {
- return new ImageIcon(imgURL);
- } else {
- System.err.println("Couldn't find file: " + path);
- return null;
- }
- }
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- //定义窗体
- JFrame frame = new JFrame("SplitPaneDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
- frame.getContentPane().add(splitPaneDemo.getSplitPane());
- //显示窗体
- frame.pack();
- frame.setVisible(true);
- }
- }
- package test23;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import javax.swing.event.*;
- /**
- * Title: 滑动杆演示
- * Description: 使用滑动杆控制定时器,来控制图片的播放速度
- * Filename: SliderDemo.java
- */
- public class SliderDemo extends JPanel
- implements ActionListener,
- WindowListener,
- ChangeListener {
- private static final long serialVersionUID = 1L;
- //设置图片的参数
- static final int FPS_MIN = 0; //设置最小值
- static final int FPS_MAX = 30; //设置最大值
- static final int FPS_INIT = 15; //初始数值
- int frameNumber = 0;
- int NUM_FRAMES = 14;
- ImageIcon[] images = new ImageIcon[NUM_FRAMES];
- int delay;
- Timer timer;
- boolean frozen = false;
- //这个标签用来显示这只小狗
- JLabel picture;
- public SliderDemo() {
- setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
- delay = 1000 / FPS_INIT;
- //信息提示标签
- JLabel sliderLabel = new JLabel("调整滑动杆,改变播放速度!", JLabel.CENTER);
- sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
- //创建一个滑动杆,定义了最小值和最大值以及初始值
- JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,
- FPS_MIN, FPS_MAX, FPS_INIT);
- framesPerSecond.addChangeListener(this);
- //定义滑动杆参数
- framesPerSecond.setMajorTickSpacing(10);//每10刻度标注一次
- framesPerSecond.setMinorTickSpacing(1);//最小刻度为1
- framesPerSecond.setPaintTicks(true);//绘制滑动杆上的刻度
- framesPerSecond.setPaintLabels(true);//在滑动过程中绘制滑动块
- framesPerSecond.setBorder(
- BorderFactory.createEmptyBorder(0,0,10,0));
- //定义一个用来显示图片的标签
- picture = new JLabel();
- picture.setHorizontalAlignment(JLabel.CENTER);
- picture.setAlignmentX(Component.CENTER_ALIGNMENT);
- picture.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createLoweredBevelBorder(),
- BorderFactory.createEmptyBorder(10,10,10,10)));
- updatePicture(0); //显示第一张图
- //将成员添加到面板上
- add(sliderLabel);
- add(framesPerSecond);
- add(picture);
- setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
- //设置一个定时器来触发这个事件
- timer = new Timer(delay, this);
- timer.setInitialDelay(delay * 7); //在每轮循环停顿时间
- timer.setCoalesce(true);//设置重复循环
- }
- /**
- *方法说明:添加一个窗体监听
- *输入参数:
- *返回类型:
- */
- void addWindowListener(Window w) {
- w.addWindowListener(this);
- }
- public void windowIconified(WindowEvent e) {
- stopAnimation();
- }
- public void windowDeiconified(WindowEvent e) {
- startAnimation();
- }
- public void windowOpened(WindowEvent e) {}
- public void windowClosing(WindowEvent e) {}
- public void windowClosed(WindowEvent e) {}
- public void windowActivated(WindowEvent e) {}
- public void windowDeactivated(WindowEvent e) {}
- /**
- *方法说明:对滑动杆进行监听
- *输入参数:ChangeEvent e 滑动杆变动事件
- *返回类型:
- */
- public void stateChanged(ChangeEvent e) {
- JSlider source = (JSlider)e.getSource();
- if (!source.getValueIsAdjusting()) {
- int fps = (int)source.getValue();//获得滑动杆的值
- if (fps == 0) {
- if (!frozen) stopAnimation();
- } else {
- delay = 1000 / fps;
- timer.setDelay(delay);
- timer.setInitialDelay(delay * 10);
- if (frozen) startAnimation();
- }
- }
- }
- /**
- *方法说明:开始动画
- *输入参数:
- *返回类型:
- */
- public void startAnimation() {
- timer.start();
- frozen = false;
- }
- /**
- *方法说明:停止动画
- *输入参数:
- *返回类型:
- */
- public void stopAnimation() {
- timer.stop();
- frozen = true;
- }
- /**
- *方法说明:事件监听
- *输入参数:
- *返回类型:
- */
- public void actionPerformed(ActionEvent e) {
- //改变图片帧
- if (frameNumber == (NUM_FRAMES - 1)) {
- frameNumber = 0;
- } else {
- frameNumber++;
- }
- updatePicture(frameNumber); //显示下张图
- if ( frameNumber==(NUM_FRAMES - 1)
- || frameNumber==(NUM_FRAMES/2 - 1) ) {
- timer.restart();
- }
- }
- /**
- *方法说明:绘制当前帧
- *输入参数:int frameNum 图片帧数数
- *返回类型:
- */
- protected void updatePicture(int frameNum) {
- if (images[frameNumber] == null) {
- images[frameNumber] = createImageIcon("images/doggy/T"
- + frameNumber
- + ".gif");
- }
- //绘制图片
- if (images[frameNumber] != null) {
- picture.setIcon(images[frameNumber]);
- } else { //如果没有发现图片
- picture.setText("image #" + frameNumber + " not found");
- }
- }
- /**
- *方法说明:获取图片
- *输入参数:String path 图片路径
- *返回类型:ImageIcon 图片对象
- */
- protected static ImageIcon createImageIcon(String path) {
- java.net.URL imgURL = SliderDemo.class.getResource(path);
- if (imgURL != null) {
- return new ImageIcon(imgURL);
- } else {
- System.err.println("Couldn't find file: " + path);
- return null;
- }
- }
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- //定义窗体
- JFrame frame = new JFrame("SliderDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //实例化本类
- SliderDemo animator = new SliderDemo();
- animator.setOpaque(true);
- frame.setContentPane(animator);
- //显示窗体
- frame.pack();
- frame.setVisible(true);
- animator.startAnimation();
- }
- }
- package test24;
- import java.awt.*;
- import javax.swing.*;
- import javax.swing.event.*;
- /**
- * Title: 颜色选择器
- * Description: 演示一个颜色选择器,可以从样本中选择,可以使用HSB模式和RGB模式
- * Filename: ColorChooserDemo.java
- */
- public class ColorChooserDemo extends JPanel
- implements ChangeListener {
- private static final long serialVersionUID = 1L;
- protected JColorChooser tcc;
- protected JLabel banner;
- public ColorChooserDemo() {
- super(new BorderLayout());
- //设置一个标签,做广告的。也用来显示用户选择的颜色。
- banner = new JLabel("欢迎使用颜色选择器!",
- JLabel.CENTER);
- banner.setForeground(Color.yellow);
- banner.setBackground(Color.blue);
- banner.setOpaque(true);
- banner.setFont(new Font("SansSerif", Font.BOLD, 24));
- banner.setPreferredSize(new Dimension(100, 65));
- JPanel bannerPanel = new JPanel(new BorderLayout());
- bannerPanel.add(banner, BorderLayout.CENTER);
- bannerPanel.setBorder(BorderFactory.createTitledBorder("广告"));
- //设置选择颜色选择器
- tcc = new JColorChooser(banner.getForeground());//设置初始颜色
- tcc.getSelectionModel().addChangeListener(this);//给所有模式添加监听
- tcc.setBorder(BorderFactory.createTitledBorder("选择颜色"));
- add(bannerPanel, BorderLayout.CENTER);
- add(tcc, BorderLayout.PAGE_END);
- }
- /**
- *方法说明:事件监听。用户选择颜色触发
- *输入参数:ChangeEvent e 用户选择事件
- *返回类型:
- */
- public void stateChanged(ChangeEvent e) {
- Color newColor = tcc.getColor();//获取用户选择的颜色
- banner.setForeground(newColor);
- }
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- //创建窗体
- JFrame frame = new JFrame("ColorChooserDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //创建面板容器
- JComponent newContentPane = new ColorChooserDemo();
- newContentPane.setOpaque(true);
- frame.setContentPane(newContentPane);
- //显示窗体
- frame.pack();
- frame.setVisible(true);
- }
- }
- package test25;
- import javax.swing.JTable;
- import javax.swing.table.AbstractTableModel;
- import javax.swing.JScrollPane;
- import javax.swing.JFrame;
- import java.awt.*;
- import java.awt.event.*;
- /**
- * Title: 自己定义的表格
- * Description: 继承AbstractTableModel类,实现自己的表格
- * Flename: MyTableDemo.java
- */
- public class MyTableDemo extends JFrame {
- private static final long serialVersionUID = 1L;
- public MyTableDemo() {
- super("MyTableDemo");
- //声明自己的表格,并添加到JTable中
- MyTableModel myModel = new MyTableModel();
- JTable table = new JTable(myModel);
- table.setPreferredScrollableViewportSize(new Dimension(500, 70));
- //将表格添加到可滚动的面板
- JScrollPane scrollPane = new JScrollPane(table);
- //将滚动面板添加到窗体
- getContentPane().add(scrollPane, BorderLayout.CENTER);
- //添加监听
- addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- System.exit(0);
- }
- });
- }
- /**
- * Title: 定义自己的表格模式
- * Description: 通过继承AbstractTableModel类来定义自己的表格模式,
- * 这里使得第三个以后才可以编辑
- */
- class MyTableModel extends AbstractTableModel {
- private static final long serialVersionUID = 1L;
- //定义表头
- final String[] columnNames = {"姓名",
- "性别",
- "学历",
- "年龄",
- "是否已婚"};
- //初始化表数据
- final Object[][] data = {
- {"张三", "男",
- "大本", new Integer(25), new Boolean(false)},
- {"李四", "男",
- "大本", new Integer(33), new Boolean(true)},
- {"王五", "男",
- "高中", new Integer(20), new Boolean(false)},
- {"赵倩", "女",
- "大专", new Integer(26), new Boolean(true)},
- {"周大", "男",
- "大本", new Integer(24), new Boolean(false)}
- };
- /**
- *方法说明:继承AbstractTableModel必须实现的方法
- *输入参数:
- *返回类型:int 列数
- */
- public int getColumnCount() {
- return columnNames.length;
- }
- /**
- *方法说明:继承AbstractTableModel必须实现的方法
- *输入参数:
- *返回类型:int 列数
- */
- public int getRowCount() {
- return data.length;
- }
- /**
- *方法说明:继承AbstractTableModel必须实现的方法
- *输入参数:
- *返回类型:String 列名
- */
- public String getColumnName(int col) {
- return columnNames[col];
- }
- /**
- *方法说明:继承AbstractTableModel必须实现的方法,获取表格中的数据
- *输入参数:int row 行数
- *输入参数:int col 列数
- *返回类型:Object 数据对象
- */
- public Object getValueAt(int row, int col) {
- return data[row][col];
- }
- /**
- *方法说明:实现这个方法使得最后一列不是显示true和false。而是使用检查盒
- *输入参数:
- *返回类型:
- */
- @SuppressWarnings("unchecked")
- public Class getColumnClass(int c) {
- return getValueAt(0, c).getClass();
- }
- /**
- *方法说明:这个方法不一定需要实现。这里是为了定义可编辑的列
- *输入参数:
- *返回类型:boolean 是否可编辑
- */
- public boolean isCellEditable(int row, int col) {
- if (col < 2) {
- return false;
- } else {
- return true;
- }
- }
- /**
- *方法说明:实现此方法,获得编辑数据。
- *输入参数:
- *返回类型:
- */
- public void setValueAt(Object value, int row, int col) {
- System.out.println("修改数据位置: " + row + "," + col
- + " 新数据为: " + value);
- data[row][col] = value;
- fireTableCellUpdated(row, col);
- System.out.println("表格新数据:");
- printDebugData();
- }
- /**
- *方法说明:输出表格中的新数据
- *输入参数:
- *返回类型:
- */
- private void printDebugData() {
- int numRows = getRowCount();
- int numCols = getColumnCount();
- for (int i=0; i < numRows; i++) {
- System.out.print(" 行 " + i + ":");
- for (int j=0; j < numCols; j++) {
- System.out.print(" " + data[i][j]);
- }
- System.out.println();
- }
- System.out.println("--------------------------");
- }
- }
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- MyTableDemo frame = new MyTableDemo();
- frame.pack();
- frame.setVisible(true);
- }
- }
- package test26;
- import java.awt.*;
- import javax.swing.*;
- /**
- * Title: 基本图形的绘制
- * Description: 本实例演示绘制四边型、圆角矩形、椭圆等基本的图形。
- * Filename: Sample.java
- */
- public class Sample extends JFrame {
- private static final long serialVersionUID = 1L;
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args){
- Sample sl = new Sample();
- sl.update();
- }
- /**
- *方法说明:构造器,显示窗体
- *输入参数:
- *返回类型:
- */
- @SuppressWarnings("deprecation")
- Sample(){
- super("Sample");
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- setSize(310,160);
- show();
- }
- /**
- *方法说明:更新画面
- *输入参数:
- *返回类型:
- */
- public void update(){
- repaint();
- }
- /**
- *方法说明:绘制画面
- *输入参数:
- *返回类型:
- */
- public void paint(Graphics g) {
- int [] x={10,30,80,50,10};
- int [] y={90,140,120,100,90};
- g.setColor(Color.cyan);
- //绘制竖格线
- for (int i=0; i<=300; i+=10) {
- g.drawLine(i,0,i,150);
- }
- //绘制横格线
- for (int i=0; i<=150; i+=10) {
- g.drawLine(0,i,300,i);
- }
- g.setColor(Color.black);
- //有角矩形,起始点(10,30),宽80,高50
- g.drawRect(10,30,80,50);
- //圆角矩形,起始点(110,30),宽80,高50,角(a=20,b=10)
- g.drawRoundRect(110,30,80,50,20,10);
- //多角边
- g.drawPolygon(x,y,5);
- //椭圆,圆心(110,90)、a=80,b=50
- g.drawOval(110,90,80,50);
- //一条弧,圆心(219,30)、a=80,b=50 角度在0-90之间
- g.drawArc(210,30,80,50,0,90);
- //扇面,圆心(219,90)、a=80,b=50 角度在0-90之间
- g.fillArc(210,90,80,50,0,90);
- }
- }
- package test27;
- import java.awt.*;
- import javax.swing.*;
- public class Func extends JFrame{
- private static final long serialVersionUID = 1L;
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args){
- Func db = new Func();
- db.update();
- }
- /**
- *方法说明:构造器,显示窗体
- *输入参数:
- *返回类型:
- */
- @SuppressWarnings("deprecation")
- Func(){
- super("Function");
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- setSize(310,310);
- show();
- }
- /**
- *方法说明:更新画面
- *输入参数:
- *返回类型:
- */
- public void update(){
- repaint();
- }
- /**
- *方法说明:转换坐标点
- *输入参数:
- *返回类型:
- */
- double f(double x) {
- return (Math.sin(2*x)+Math.cos(3*x));
- }
- /**
- *方法说明:绘制坐标图
- *输入参数:
- *返回类型:
- */
- public void paint(Graphics g) {
- double x0,x1,y0,y1,xd,yd;
- double max=5.0;
- int w,h,hw,hh;
- //获取屏幕的尺寸
- w=getSize().width;
- h=getSize().height;
- hw=w/2; hh=h/2;
- //在屏幕上输出字符
- g.drawString("Sin[2x]+Cos[3x]",10,40);
- g.setColor(Color.red);
- g.drawString("0",hw+5,hh+12);
- g.drawString(""+max,hw-20,40);
- g.drawString(""+max,w-20,hh+12);
- //绘制X轴坐标
- g.drawLine(0,hh,w,hh);
- //绘制Y轴坐标
- g.drawLine(hw,0,hw,h);
- xd=2*max/w;//计算X增量
- yd=hh/max; //计算y增量
- g.setColor(Color.blue);
- //使用增量绘制一小段线,最终组成曲线图形。
- for (int x=0 ; x<w-1; x++) {
- x0=-max+x*xd; y0=f(x0)*yd;
- x1=x0+xd; y1=f(x1)*yd;
- g.drawLine(x,(int)(hh-y0),x+1,(int)(hh-y1));
- }
- }
- } //end
- package test28;
- import javax.swing.*;
- import java.awt.*;
- /**
- * Title: 图片的处理,
- * Description: 将图片放大和翻转显示
- * Filename: ImgDemo.java
- */
- class ImgDemo extends JFrame {
- private static final long serialVersionUID = 1L;
- Image image;
- /**
- *方法说明:构造器,显示窗体
- *输入参数:
- *返回类型:
- */
- @SuppressWarnings("deprecation")
- ImgDemo(String filename) {
- setTitle("drawImage Example");
- try {
- image = getToolkit().getImage(filename);
- setIconImage(image);
- } catch (Exception e) {
- e.printStackTrace();
- }
- setSize(600, 250);
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- show();
- }
- /**
- *方法说明:绘制图像
- *输入参数:
- *返回类型:
- */
- public void paint(Graphics g) {
- Insets insets = getInsets();
- int x = insets.left, y = insets.top;
- //获取图片尺寸
- int w = image.getWidth(this);
- int h = image.getHeight(this);
- //正常显示图片
- g.drawImage(image, x, y, this);
- //缩小图形
- g.drawRect(x, y, w/4+1, h/4+1);//画一个框
- g.drawImage(image, x+1, y+1, w/4, h/4, this);
- //水平翻转
- g.drawImage(image, x+w, y, x+2*w, y+h, w, 0, 0, h, this);
- }
- /**
- *方法说明:主方法,接受参数
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args) {
- if (args.length == 1) {
- new ImgDemo(args[0]);
- } else {
- System.err.println("usage: java ImgDemo images-name ");
- }
- }
- }
- package test29;
- import java.awt.*;
- import java.awt.event.*;
- import java.util.*;
- import javax.swing.*;
- import javax.swing.Timer;
- /**
- * Title: 时钟
- * Description: 本实例演示使用图形绘制一个图形时钟
- * Filename: Clock.java
- */
- public class Clock extends JFrame implements ActionListener{
- private static final long serialVersionUID = 1L;
- Timer timer;
- int x,y,old_X,old_Y, r,x0,y0,w,h,ang;
- int sdo,mdo,hdo,old_M,old_H;
- TimeZone tz =TimeZone.getTimeZone("JST");
- final double RAD=Math.PI/180.0;
- public static void main(String[] args){
- @SuppressWarnings("unused")
- Clock cl = new Clock();
- }
- /**
- *方法说明:实现ActionListener类必须过载的方法
- *输入参数:
- *返回类型:
- */
- public void actionPerformed(ActionEvent e) {
- timer.restart();
- }
- /**
- *方法说明:构造器,显示窗体,并添加了一个秒表
- *输入参数:
- *返回类型:
- */
- @SuppressWarnings("deprecation")
- Clock(){
- super("Clock");
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- setBackground(new Color(0,0,192));
- setSize(300,300);
- show();
- int delay = 1000;
- //窗体添加事件监听,监听秒表的触发
- ActionListener taskPerformer = new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- repaint();
- }
- };
- new Timer(delay, taskPerformer).start();
- }
- /**
- *方法说明:绘制图形
- *输入参数:
- *返回类型:
- */
- public void paint( Graphics g ) {
- Insets insets = getInsets();
- int L0 = (insets.left)/2, T0 = (insets.top)/2;
- int hh,mm,ss;
- String st;
- h=getSize().height;
- //绘制圆形
- g.setColor(Color.white);
- g.drawOval(L0+30,T0+30,h-60,h-60);
- g.drawOval(L0+32,T0+32,h-64,h-64);
- r=h/2-30;
- x0=30+r-5+L0;
- y0=30+r-5-T0;
- ang=60;
- for (int i=1; i<=12; i++) {
- x=(int)((r+10)*Math.cos(RAD*ang)+x0);
- y=(int)((r+10)*Math.sin(RAD*ang)+y0);
- g.drawString(""+i,x,h-y);
- ang-=30;
- }
- x0=30+r+L0; y0=30+r+T0;
- //获取时间
- Calendar now=Calendar.getInstance();
- hh=now.get(Calendar.HOUR_OF_DAY);//小时
- mm=now.get(Calendar.MINUTE);//分钟
- ss=now.get(Calendar.SECOND);// 秒
- g.setColor(Color.pink);
- g.fillRect(L0,T0,60,28);//填充的矩形
- g.setColor(Color.blue);
- if (hh < 10) st="0"+hh; else st=""+hh;
- if (mm < 10) st=st+":0"+mm; else st=st+":"+mm;
- if (ss < 10) st=st+":0"+ss; else st=st+":"+ss;
- g.drawString(st,L0,T0+25);
- //计算时间和图形的关系
- sdo=90-ss*6;
- mdo=90-mm*6;
- hdo=90-hh*30-mm/2;
- //擦除秒针
- if (old_X > 0) {
- g.setColor(getBackground());
- g.drawLine(x0,y0,old_X,(h-old_Y));
- } else {
- old_M=mdo;
- old_H=hdo;
- }
- //绘制秒针
- g.setColor(Color.yellow);
- x=(int)((r-8)*Math.cos(RAD*sdo)+x0);
- y=(int)((r-8)*Math.sin(RAD*sdo)+y0)-2*T0;
- g.drawLine(x0,y0,x,(h-y));
- old_X=x;
- old_Y=y;
- //擦除分针和时针
- if (mdo != old_M) {
- line(g,old_M,(int)(r*0.7),getBackground());
- old_M=mdo;
- }
- if (hdo != old_H) {
- line(g,old_H,(int)(r*0.5),getBackground());
- old_H=hdo;
- }
- //绘制分针
- line(g,mdo,(int)(r*0.7),Color.green);
- //绘制时针
- line(g,hdo,(int)(r*0.5),Color.red);
- } // end paint
- /**
- *方法说明:绘制线,用于绘制时针和分针
- *输入参数:
- *返回类型:
- */
- public void line(Graphics g, int t, int n, Color c) {
- int [] xp = new int[4];
- int [] yp = new int[4];
- xp[0]=x0;
- yp[0]=y0;
- xp[1]= (int)((n-10)*Math.cos(RAD*(t-4))+x0);
- yp[1]=h-(int)((n-10)*Math.sin(RAD*(t-4))+y0);
- xp[2]= (int)( n *Math.cos(RAD* t )+x0);
- yp[2]=h-(int)( n *Math.sin(RAD* t )+y0);
- xp[3]= (int)((n-10)*Math.cos(RAD*(t+4))+x0);
- yp[3]=h-(int)((n-10)*Math.sin(RAD*(t+4))+y0);
- g.setColor(c);
- g.fillPolygon(xp,yp,4);
- }
- }
- package test30;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- /**
- * Title: 正方体框图
- * Description: 绘制一个边框的正方体,获取鼠标事件根据鼠标的位置旋转方体。
- * Filename: Gr3d1m.java
- */
- public class Gr3d1m extends JFrame
- implements MouseListener,MouseMotionListener {
- int doX,doY;
- int angX=30,angY=30;
- Cube data = new Cube();
- Color [] Col={Color.gray,Color.cyan,Color.green,
- Color.red,Color.white,Color.orange,
- Color.magenta,Color.pink};
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args){
- Gr3d1m G3 = new Gr3d1m();
- }
- /**
- *方法说明:构造器
- *输入参数:
- *返回类型:
- */
- public Gr3d1m() {
- setTitle("3D cube Frame");
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- addMouseListener(this);
- addMouseMotionListener(this);
- setBackground(new Color(128,128,255));
- setSize(350,350);
- show();
- }
- /**
- *方法说明:鼠标按下事件,获取鼠标位置
- *输入参数:
- *返回类型:
- */
- public void mousePressed(MouseEvent e) {
- doX=e.getX();
- doY=e.getY();
- }
- /**
- *方法说明:鼠标托拽事件,改变鼠标位置,重画屏幕
- *输入参数:
- *返回类型:
- */
- public void mouseDragged(MouseEvent e) {
- angX=angX+e.getY()-doY;
- angY=angY+e.getX()-doX;
- doX=e.getX(); doY=e.getY();
- repaint();
- }
- /* 以下是实现MouseListener和MouseMotionListener必须重载的方法*/
- public void mouseReleased(MouseEvent e) { }
- public void mouseClicked(MouseEvent e) { }
- public void mouseEntered(MouseEvent e) { }
- public void mouseExited(MouseEvent e) { }
- public void mouseMoved(MouseEvent e) { }
- /**
- *方法说明:绘制图形
- *输入参数:
- *返回类型:
- */
- public void paint( Graphics g ) {
- delDeaw(g);
- for (int i=0; i<data.x.length; i++) {
- drawPG(g, data.x[i], data.y[i], data.z[i],
- 150,150,Col[i]);
- }
- g.setColor(Color.yellow);
- g.drawString("X="+angX%360+" Y="+angY%360,
- 10,getSize().height-30);
- }
- /**
- *方法说明:擦拭屏幕,使用背景色覆盖原来的图形
- *输入参数:
- *返回类型:
- */
- public void delDeaw(Graphics g){
- Insets insets = getInsets();
- int L0 = insets.left, T0 = insets.top;
- g.setColor(new Color(128,128,255));
- g.fillRect(L0,T0,L0+350,T0+350);
- }
- /**
- *方法说明:绘制方体
- *输入参数:
- *返回类型:
- */
- public void drawPG(Graphics g,double []x,double []y,
- double []z,int xp,int yp,Color co) {
- double x1,y1,z0;
- int len=x.length;
- int [] xx=new int [len];
- int [] yy=new int [len];
- final double RAD=Math.PI/180.0;
- double a=angX*RAD;
- double b=angY*RAD;
- double sinA=Math.sin(a),sinB=Math.sin(b);
- double cosA=Math.cos(a),cosB=Math.cos(b);
- for (int i=0; i<len; i++) {
- x1= x[i]*cosB+z[i]*sinB;
- z0=-x[i]*sinB+z[i]*cosB;
- y1= y[i]*cosA- z0*sinA;
- xx[i]=xp+(int)Math.rint(x1);
- yy[i]=yp-(int)Math.rint(y1);
- }
- g.setColor(co);
- g.drawPolygon(xx,yy,len);//绘制多边形
- }
- }
- package test31;
- import java.awt.*;
- import javax.swing.*;
- public class Gr3d4a extends Gr3d1m {
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args){
- Gr3d4a G3 = new Gr3d4a();
- }
- /**
- *方法说明:构造器
- *输入参数:
- *返回类型:
- */
- public Gr3d4a() {
- setTitle("3D cube box");
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- addMouseListener(this);
- addMouseMotionListener(this);
- setBackground(new Color(128,128,255));
- setSize(350,350);
- show();
- }
- /**
- *方法说明:绘制正方体盒子,过载Gr3d1m中的方法
- *输入参数:
- *返回类型:
- */
- public void drawPG(Graphics g,double []x,double []y,
- double []z,int xp,int yp,Color co) {
- double x1,y1,z0;
- int len=x.length;
- double [] xw=new double[len];
- double [] yw=new double[len];
- int [] xx=new int [len];
- int [] yy=new int [len];
- final double RAD=Math.PI/180.0;
- double a=angX*RAD;
- double b=angY*RAD;
- double sinA=Math.sin(a),sinB=Math.sin(b);
- double cosA=Math.cos(a),cosB=Math.cos(b);
- for (int i=0; i<len; i++) {
- x1= x[i]*cosB+z[i]*sinB;
- z0=-x[i]*sinB+z[i]*cosB;
- y1= y[i]*cosA- z0*sinA;
- xx[i]=xp+(int)Math.rint(x1);
- yy[i]=yp-(int)Math.rint(y1);
- xw[i]=x1; yw[i]=y1;
- }
- if (Hvec(xw,yw) > 0) {
- g.setColor(co);
- g.fillPolygon(xx,yy,len);//填充的多边形
- }
- }
- /**
- *方法说明:消影处理,如果平面被遮蔽将不被绘制
- *输入参数:
- *返回类型:
- */
- double Hvec(double []x,double []y) {
- return(x[0]*(y[1]-y[2])+x[1]*(y[2]-y[0])+x[2]*(y[0]-y[1]));
- }
- }
- package test32;
- import java.util.*;
- import java.io.*;
- /**
- * Title: 标注输入输出
- * Description: 接收标准的键盘输入,和输出到屏幕。
- * Filename: standerdIO.java
- */
- public class standerdIO{
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args){
- Vector<Object> vTemp = new Vector<Object>();
- boolean flag = true;
- while(flag){
- System.out.print("input>");
- String sTemp ="";
- //读取输入,System.in表示接收键盘输入流
- BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
- try{
- //读取一行输入
- sTemp = stdin.readLine();
- }catch(IOException ie){
- System.err.println("IO error!");
- }
- //解析输入命令
- String sCMD="";
- String sContext="";
- int point = sTemp.indexOf(":");
- if(point==-1){
- sCMD = sTemp.trim();
- }else{
- sCMD = sTemp.substring(0,point);
- sContext = sTemp.substring(point+1);
- }
- //添加数据
- if(sCMD.equalsIgnoreCase("in")){
- if(sContext.equals("")){
- System.err.println("this command format is errer!");
- }else{
- vTemp.addElement(sContext);
- }
- }//查看结果
- else if(sCMD.equalsIgnoreCase("out")){
- for(int i=0;i<vTemp.size();i++){
- System.out.println(i+":"+vTemp.elementAt(i));
- }
- }//结束
- else if(sCMD.equalsIgnoreCase("quit")){
- flag=false;
- }
- else{
- System.err.println("this command don't run!");
- System.out.print("use: in:command");
- System.out.print("use: out");
- }
- }
- }
- }
- package test33;
- import java.io.*;
- /**
- * Title: 读取和写入文件
- * Description: 使用字节流方式操作文件,读取和写入文件。
- * Filename: CopyBytes.java
- */
- public class BAKCopyBytes {
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args) throws IOException {
- String sFile;
- String oFile;
- if(args.length<2){
- System.out.println("USE:java CopyBytes source file | object file");
- return;
- }else{
- sFile = args[0];
- oFile = args[1];
- }
- try{
- File inputFile = new File(sFile);//定义读取源文件
- File outputFile = new File(oFile);//定义拷贝目标文件
- //定义输入文件流
- FileInputStream in = new FileInputStream(inputFile);
- //将文件输入流构造到缓存
- BufferedInputStream bin = new BufferedInputStream(in);
- //定义输出文件流
- FileOutputStream out = new FileOutputStream(outputFile);
- //将输出文件流构造到缓存
- BufferedOutputStream bout = new BufferedOutputStream(out);
- int c;
- //循环读取文件和写入文件
- while ((c = bin.read()) != -1)
- bout.write(c);
- //关闭输入输出流,释放资源
- bin.close();
- bout.close();
- }catch(IOException e){
- //文件操作,捕获IO异常。
- System.err.println(e);
- }
- }
- }
- package test33;
- import java.io.*;
- /**
- * Title: 读取和写入文件
- * Description: 使用字节流方式操作文件,读取和写入文件。
- * Filename: CopyBytes.java
- */
- public class CopyBytes {
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args) throws IOException {
- String sFile;
- String oFile;
- if(args.length<2){
- System.out.println("USE:java CopyBytes source file | object file");
- return;
- }else{
- sFile = args[0];
- oFile = args[1];
- }
- try{
- File inputFile = new File(sFile);//定义读取源文件
- File outputFile = new File(oFile);//定义拷贝目标文件
- //定义输入文件流
- FileInputStream in = new FileInputStream(inputFile);
- //将文件输入流构造到缓存
- BufferedInputStream bin = new BufferedInputStream(in);
- //定义输出文件流
- FileOutputStream out = new FileOutputStream(outputFile);
- //将输出文件流构造到缓存
- BufferedOutputStream bout = new BufferedOutputStream(out);
- int c;
- //循环读取文件和写入文件
- while ((c = bin.read()) != -1)
- bout.write(c);
- //关闭输入输出流,释放资源
- bin.close();
- bout.close();
- }catch(IOException e){
- //文件操作,捕获IO异常。
- System.err.println(e);
- }
- }
- }
- package test34;
- import java.io.*;
- /**
- * Title: 文件的读取和写入(字符)
- * Description: 使用FileReader和FileWriter类,采用字符文件访问方式操作文件。
- * Filename:
- */
- public class BAKCopyChar {
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args) throws IOException {
- String sFile;
- String oFile;
- if(args.length<2){
- System.out.println("USE:java CopyChar source file | object file");
- return;
- }else{
- sFile = args[0];
- oFile = args[1];
- }
- try{
- File inputFile = new File(sFile);//定义读取的文件源
- File outputFile = new File(oFile);//定义拷贝的目标文件
- //定义输入文件流
- FileReader in = new FileReader(inputFile);
- //将文件输入流构造到缓存
- BufferedReader bin = new BufferedReader(in);
- //定义输出文件流
- FileWriter out = new FileWriter(outputFile);
- //将输出文件流构造到缓存
- BufferedWriter bout = new BufferedWriter(out);
- int c;
- //循环读取和输入文件。
- while ((c = bin.read()) != -1)
- bout.write(c);
- bin.close();
- bout.close();
- }catch(IOException e){
- //文件操作,捕获IO异常。
- System.err.println(e);
- }
- }
- }
- package test34;
- import java.io.*;
- /**
- * Title: 文件的读取和写入(字符)
- * Description: 使用FileReader和FileWriter类,采用字符文件访问方式操作文件。
- * Filename:
- */
- public class CopyChar {
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args) throws IOException {
- String sFile;
- String oFile;
- if(args.length<2){
- System.out.println("USE:java CopyChar source file | object file");
- return;
- }else{
- sFile = args[0];
- oFile = args[1];
- }
- try{
- File inputFile = new File(sFile);//定义读取的文件源
- File outputFile = new File(oFile);//定义拷贝的目标文件
- //定义输入文件流
- FileReader in = new FileReader(inputFile);
- //将文件输入流构造到缓存
- BufferedReader bin = new BufferedReader(in);
- //定义输出文件流
- FileWriter out = new FileWriter(outputFile);
- //将输出文件流构造到缓存
- BufferedWriter bout = new BufferedWriter(out);
- int c;
- //循环读取和输入文件。
- while ((c = bin.read()) != -1)
- bout.write(c);
- bin.close();
- bout.close();
- }catch(IOException e){
- //文件操作,捕获IO异常。
- System.err.println(e);
- }
- }
- }
- package test35;
- import java.io.*;
- import java.util.*;
- /**
- * Title: 文件操作
- * Description: 演示文件的删除和获取文件的信息
- * Filename:
- */
- public class fileOperation{
- /**
- *方法说明:删除文件
- *输入参数:String fileName 要删除的文件名
- *返回类型:boolean 成功为true
- */
- public boolean delFile(String fileName){
- try{
- //删除文件
- boolean success = (new File(fileName)).delete();
- if (!success) {
- System.out.println("delete file error!");
- return false;
- }else{
- return true;
- }
- }catch(Exception e){
- System.out.println(e);
- return false;
- }
- }
- /**
- *方法说明:获取文件信息
- *输入参数:String Name 文件名
- *返回类型:String[] 文件信息数组
- */
- public String[] getFileInfo(String Name){
- try{
- File file = new File(Name);
- //获取文件修改日期(返回的是句)
- long modifiedTime = file.lastModified();
- //获取文件长度(单位:Bite)
- long filesize = file.length();
- //测试文件是否可读
- boolean cr = file.canRead();
- //测试文件是否可写
- boolean cw = file.canWrite();
- //测试文件是否隐藏
- boolean ih = file.isHidden();
- String[] sTemp = new String[6];
- sTemp[0] = String.valueOf(filesize);
- sTemp[1] = getDateString(modifiedTime);
- sTemp[2] = String.valueOf(cr);
- sTemp[3] = String.valueOf(cw);
- sTemp[4] = String.valueOf(ih);
- sTemp[5] = String.valueOf(file.getCanonicalPath());
- return sTemp;
- }catch(Exception e){
- System.out.println(e);
- return null;
- }
- }
- /**
- *方法说明:将毫秒数字转换为日期
- *输入参数:mill 毫秒数
- *返回类型:String 字符 格式为:yyyy-mm-dd hh:mm
- */
- public static String getDateString(long mill)
- {
- if(mill < 0) return "";
- Date date = new Date(mill);
- Calendar rightNow = Calendar.getInstance();
- rightNow.setTime(date);
- int year = rightNow.get(Calendar.YEAR);
- int month = rightNow.get(Calendar.MONTH);
- int day = rightNow.get(Calendar.DAY_OF_MONTH);
- int hour = rightNow.get(Calendar.HOUR_OF_DAY);
- int min = rightNow.get(Calendar.MINUTE);
- return year + "-" + (month <10 ? "0" + month : "" + month) + "-"
- + (day <10 ? "0" + day : "" + day)
- + (hour <10 ? "0" + hour : "" + hour)+":"
- + (min <10 ? "0" + min : "" + min);
- }
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args){
- try{
- fileOperation fo = new fileOperation();
- if(args.length==0){
- return;
- }else{
- String cmd = args[0];
- if(cmd.equals("del")){
- boolean bdel = fo.delFile(args[1]);
- System.out.println(bdel);
- }else if(cmd.equals("info")){
- String[] sTemp = fo.getFileInfo(args[1]);
- for(int i=0;i<sTemp.length;i++)
- System.out.println(sTemp[i]);
- }
- }
- }catch(Exception e){
- return;
- }
- }
- }
- package test36;
- /**
- * Title: 目录操作
- * Description: 演示列目录下的文件,和移动一个目录
- * Filename: Dir.java
- */
- import java.io.*;
- public class Dir{
- /**
- *方法说明:实现目录列表
- *输入参数:
- *返回类型:
- */
- public String[] DirList(String pathName){
- try{
- File path = null;
- String[] fileList;
- //如果没有指定目录,则列出当前目录。
- if(pathName.equals(""))
- path = new File(".");
- else
- path = new File(pathName);
- //获取目录文件列表
- if(path.isDirectory())
- fileList = path.list();
- else
- return null;
- return fileList;
- }catch(Exception e){
- System.err.println(e);
- return null;
- }
- }
- /**
- *方法说明:移动一个目录
- *输入参数:String sou 源目录, String obj 新目录
- *返回类型:
- */
- public boolean DirMove(String sou, String obj){
- try{
- //检查源文件是否存在
- boolean sexists = (new File(sou)).isDirectory();
- if(!sexists) return false;
- boolean oexists = (new File(obj)).isDirectory();
- //目标目录不存在,建立一个
- if(!oexists){
- (new File(obj)).mkdirs();
- }
- File file = new File(sou);
- File dir = new File(obj);
- //移动目录
- boolean success = file.renameTo(new File(dir, file.getName()));
- if (!success) {
- System.out.println("copy error!");
- return false;
- }
- else return true;
- }catch(Exception e){
- System.out.println(e);
- return false;
- }
- }
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args){
- Dir d = new Dir();
- if(args.length==0){
- return;
- }else{
- String cmd = args[0];
- if(cmd.equals("list")){
- if(args.length!=2) return;
- String[] sTemp = d.DirList(args[1]);
- for(int i=0;i<sTemp.length;i++)
- System.out.println(sTemp[i]);
- }else if(cmd.equals("move")){
- if(args.length!=3) return;
- d.DirMove(args[1],args[2]);
- }
- }
- }
- }
- package test37;
- import java.io.*;
- /**
- * Title: 读取随机文件
- * Description: 演示使用RandomAccessFile类读取文件。
- * Filename: RandFile.java
- */
- public class RandFile{
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args){
- String sFile;
- if(args.length<1){
- System.out.println("USE:java RandFile fileName");
- return;
- }else{
- sFile = args[0];
- }
- //接受IOException异常
- try{
- //构造随机访问文件,使用可读写方式。
- RandomAccessFile rf = new RandomAccessFile(sFile, "rw");
- for(int i = 0; i < 10; i++)
- rf.writeDouble(i*1.414);
- rf.close();
- //构造一个随机访问文件,使用只读方式
- rf = new RandomAccessFile(sFile, "rw");
- rf.seek(5*8);
- rf.writeDouble(47.0001);
- rf.close();
- //构造一个随机文件访问文件,使用只读方式。
- rf = new RandomAccessFile(sFile, "r");
- for(int i = 0; i < 10; i++)
- System.out.println("Value " + i + ": " + rf.readDouble());
- rf.close();
- }catch(IOException e){
- System.out.println(e);
- }
- }
- }
- package test38;
- import java.io.File;
- import jxl.*;
- import jxl.write.*;
- /**
- * Title: 操作EXCEL文件
- * Description: 本实例演示使用jxl包实现对excel文件的操作
- * Filename: myExcel.java
- */
- public class myExcel{
- Workbook workbook;
- Sheet sheet;
- /**
- *方法说明:写入文件操作
- *输入参数:
- *返回类型:
- */
- public void write(){
- try{
- //创建一个可写入的excel文件对象
- WritableWorkbook workbook = Workbook.createWorkbook(new File("myfile.xls"));
- //使用第一张工作表,将其命名为“午餐记录”
- WritableSheet sheet = workbook.createSheet("午餐记录", 0);
- //表头
- Label label0 = new Label(0, 0, "时间");
- sheet.addCell(label0);
- Label label1 = new Label(1, 0, "姓名");
- sheet.addCell(label1);
- Label label2 = new Label(2, 0, "午餐标准");
- sheet.addCell(label2);
- Label label3 = new Label(3, 0, "实际费用");
- sheet.addCell(label3);
- //格式化日期
- jxl.write.DateFormat df = new jxl.write.DateFormat("yyyy-dd-MM hh:mm:ss");
- jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(df);
- jxl.write.DateTime labelDTF = new jxl.write.DateTime(0, 1, new java.util.Date(), wcfDF);
- sheet.addCell(labelDTF);
- //普通字符
- Label labelCFC = new Label(1, 1, "riverwind");
- sheet.addCell(labelCFC);
- //格式化数字
- jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
- WritableCellFormat wcfN = new WritableCellFormat(nf);
- jxl.write.Number labelNF = new jxl.write.Number(2, 1, 13.1415926, wcfN);
- sheet.addCell(labelNF);
- jxl.write.Number labelNNF = new jxl.write.Number(3, 1, 10.50001, wcfN);
- sheet.addCell(labelNNF);
- //关闭对象,释放资源
- workbook.write();
- workbook.close();
- }catch(Exception e){
- System.out.println(e);
- }
- }
- /**
- *方法说明:读取excel文件一行数据
- *输入参数:int row指定的行数
- *返回类型:String〔〕结果数组
- */
- public String[] readLine(int row){
- try{
- //获取数据表列数
- int colnum = sheet.getColumns();
- String[] rest = new String[colnum];
- for(int i = 0; i < colnum; i++){
- String sTemp = read(i,row);
- if(sTemp!=null)
- rest[i] = sTemp;
- }
- return rest;
- }catch(Exception e){
- System.out.println("readLine err:"+e);
- workbook.close();
- return null;
- }
- }
- /**
- *方法说明:读取excel的指定单元数据
- *输入参数:
- *返回类型:
- */
- public String read(int col, int row){
- try{
- //获得单元数据
- Cell a2 = sheet.getCell(col,row);
- String rest = a2.getContents();
- return rest;
- }catch(Exception e){
- System.out.println("read err:"+e);
- workbook.close();
- return null;
- }
- }
- /**
- *方法说明:主方法,演示程序用
- *输入参数:
- *返回类型:
- */
- public static void main(String[] arges){
- try{
- myExcel me = new myExcel();
- //生成一个可读取的excel文件对象
- me.workbook = Workbook.getWorkbook(new File("myfile.xls"));
- //使用第一个工作表
- me.sheet = me.workbook.getSheet(0);
- //读一行记录,并显示出来
- String[] ssTemp = me.readLine(1);
- for(int i=0;i<ssTemp.length;i++)
- System.out.println(ssTemp[i]);
- //写入数据
- me.write();
- me.workbook.close();
- }catch(Exception e){
- System.out.println(e);
- }
- }
- }
- package test39;
- import com.lowagie.text.*;
- import com.lowagie.text.pdf.*;
- import java.io.*;
- import java.awt.Color;
- /**
- * Title: 生成PDF文件
- * Description: 本实例通过使用iText包生成一个表格的PDF文件
- * Filename: myPDF.java
- */
- public class myPDF{
- /**
- *方法说明:写PDF文件
- *输入参数:
- *返回类型:
- */
- public void write(){
- try{
- Document document=new Document(PageSize.A4, 50, 50, 100, 50);
- Rectangle pageRect=document.getPageSize();
- PdfWriter.getInstance(document, new FileOutputStream("tables.pdf"));
- //创建汉字字体
- BaseFont bfSong = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
- Font fontSong = new Font(bfSong, 10, Font.NORMAL);
- // 增加一个水印
- try {
- Watermark watermark = new Watermark(Image.getInstance("test.jpg"), pageRect.left()+50,pageRect.top()-85);
- watermark.scalePercent(50);
- document.add(watermark);
- }catch(Exception e) {
- System.err.println("请查看文件“test.jpg”是否在正确的位置?");
- }
- // 为页增加页头信息
- HeaderFooter header = new HeaderFooter(new Phrase("Java实例一百例",fontSong), false);
- header.setBorder(2);
- header.setAlignment(Element.ALIGN_RIGHT);
- document.setHeader(header);
- // 为页增加页脚信息
- HeaderFooter footer = new HeaderFooter(new Phrase("第 ",fontSong),new Phrase(" 页",fontSong));
- footer.setAlignment(Element.ALIGN_CENTER);
- footer.setBorder(1);
- document.setFooter(footer);
- // 打开文档
- document.open();
- //构造表格
- Table table = new Table(4);
- table.setDefaultVerticalAlignment(Element.ALIGN_MIDDLE);
- table.setBorder(Rectangle.NO_BORDER);
- int hws[] = {10, 20, 10, 20,};
- table.setWidths(hws);
- table.setWidth(100);
- //表头信息
- Cell cellmain = new Cell(new Phrase("用户信息",new Font(bfSong, 10, Font.BOLD,new Color(0,0,255))));
- cellmain.setHorizontalAlignment(Element.ALIGN_CENTER);
- cellmain.setColspan(4);
- cellmain.setBorder(Rectangle.NO_BORDER);
- cellmain.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
- table.addCell(cellmain);
- //分表头信息
- Cell cellleft= new Cell(new Phrase("收货人信息",new Font(bfSong, 10, Font.ITALIC,new Color(0,0,255))));
- cellleft.setColspan(2);
- cellleft.setHorizontalAlignment(Element.ALIGN_CENTER);
- table.addCell(cellleft);
- Cell cellright= new Cell(new Phrase("订货人信息",new Font(bfSong, 10, Font.ITALIC,new Color(0,0,255))));
- cellright.setColspan(2);
- cellright.setHorizontalAlignment(Element.ALIGN_CENTER);
- table.addCell(cellright);
- //收货和订货人信息,表体内容
- table.addCell(new Phrase("姓名",fontSong));
- table.addCell(new Phrase("张三",fontSong));
- table.addCell(new Phrase("姓名",fontSong));
- table.addCell(new Phrase("李四",fontSong));
- table.addCell(new Phrase("电话",fontSong));
- table.addCell(new Phrase("23456789",fontSong));
- table.addCell(new Phrase("电话",fontSong));
- table.addCell(new Phrase("9876543",fontSong));
- table.addCell(new Phrase("邮编",fontSong));
- table.addCell(new Phrase("100002",fontSong));
- table.addCell(new Phrase("邮编",fontSong));
- table.addCell(new Phrase("200001",fontSong));
- table.addCell(new Phrase("地址",fontSong));
- table.addCell(new Phrase("北京西城区XX路XX号",fontSong));
- table.addCell(new Phrase("地址",fontSong));
- table.addCell(new Phrase("上海陆家嘴区XX路XX号",fontSong));
- table.addCell(new Phrase("电子邮件",fontSong));
- table.addCell(new Phrase("zh_san@hotmail.com",fontSong));
- table.addCell(new Phrase("电子邮件",fontSong));
- table.addCell(new Phrase("li_si@hotmail.com",fontSong));
- //将表格添加到文本中
- document.add(table);
- //关闭文本,释放资源
- document.close();
- }catch(Exception e){
- System.out.println(e);
- }
- }
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] arg){
- myPDF p = new myPDF();
- p.write();
- }
- }
- package test40;
- //文件名:myZip.java
- import java.io.*;
- import java.util.*;
- import java.util.zip.*;
- /**
- * Title: 文件压缩和解压
- * Description: 使用ZipInputStream和ZipOutputStream对文件
- * 和目录进行压缩和解压处理
- * Filename: myZip.java
- */
- public class myZip{
- /**
- *方法说明:实现文件的压缩处理
- *输入参数:String[] fs 压缩的文件数组
- *返回类型:
- */
- public void ZipFiles(String[] fs){
- try{
- String fileName = fs[0];
- FileOutputStream f =
- new FileOutputStream(fileName+".zip");
- //使用输出流检查
- CheckedOutputStream cs =
- new CheckedOutputStream(f,new Adler32());
- //声明输出zip流
- ZipOutputStream out =
- new ZipOutputStream(new BufferedOutputStream(cs));
- //写一个注释
- out.setComment("A test of Java Zipping");
- //对多文件进行压缩
- for(int i=1;i<fs.length;i++){
- System.out.println("Write file "+fs[i]);
- BufferedReader in =
- new BufferedReader(
- new FileReader(fs[i]));
- out.putNextEntry(new ZipEntry(fs[i]));
- int c;
- while((c=in.read())!=-1)
- out.write(c);
- in.close();
- }
- //关闭输出流
- out.close();
- System.out.println("Checksum::"+cs.getChecksum().getValue());
- }catch(Exception e){
- System.err.println(e);
- }
- }
- /**
- *方法说明:解压缩Zip文件
- *输入参数:String fileName 解压zip文件名
- *返回类型:
- */
- public void unZipFile(String fileName){
- try{
- System.out.println("读取ZIP文件........");
- //文件输入流
- FileInputStream fi =
- new FileInputStream(fileName+".zip");
- //输入流检查
- CheckedInputStream csi = new CheckedInputStream(fi,new Adler32());
- //输入流压缩
- ZipInputStream in2 =
- new ZipInputStream(
- new BufferedInputStream(csi));
- ZipEntry ze;
- System.out.println("Checksum::"+csi.getChecksum().getValue());
- //解压全部文件
- while((ze = in2.getNextEntry())!=null){
- System.out.println("Reading file "+ze);
- int x;
- while((x= in2.read())!=-1)
- //这里是写文件,write是以byte方式输出。
- System.out.write(x);
- }
- in2.close();
- }catch(Exception e){
- System.err.println(e);
- }
- }
- /**
- *方法说明:读取Zip文件列表
- *输入参数:String fileName zip文件名
- *返回类型:Vector 文件列表
- */
- @SuppressWarnings("unchecked")
- public Vector<Object> listFile(String fileName){
- try{
- @SuppressWarnings("unused")
- String[] aRst=null;
- Vector<Object> vTemp = new Vector<Object>();
- //zip文件对象
- ZipFile zf = new ZipFile(fileName+".zip");
- Enumeration e = zf.entries();
- while(e.hasMoreElements()){
- ZipEntry ze2 = (ZipEntry)e.nextElement();
- System.out.println("File: "+ze2);
- vTemp.addElement(ze2);
- }
- return vTemp;
- }catch(Exception e){
- System.err.println(e);
- return null;
- }
- }
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String[] args){
- try{
- String fileName = args[0];
- myZip myZip = new myZip();
- myZip.ZipFiles(args);
- myZip.unZipFile(fileName);
- Vector<Object> dd = myZip.listFile(fileName);
- System.out.println("File List: "+dd);
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
转自http://blog.csdn.net/fljxzxb
- java--100个Java经典例子(11-20)初学者的利器高手的宝典JavaSE
- java--100个Java经典例子(21-30)初学者的利器高手的宝典JavaSE
- java--100个Java经典例子(1-10)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(1-10)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(11-20)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(21-30)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(31-40)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(41-50)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(1-10)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(11-20)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(21-30)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(31-40)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(41-50)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(1-10)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(41-50)初学者的利器高手的宝典JavaSE
- 100个Java经典例子(51-60)初学者的利器高手的宝典JavaSE
- 100个Java经典例子--初学者的利器高手的宝典JavaSE
- 100个Java经典例子(1-10)初学者的利器高手的宝典JavaSE
- HP(惠普)大中华区总裁孙振耀退休感言
- 同步加载数据岛数据
- MySQL日期时间函数大全
- 数据库的操作
- 多线程的实现
- 100个Java经典例子--初学者的利器高手的宝典JavaSE
- 编写简单DLL及CL编译链接
- oracle: ocp题解与实验(5/205)
- JavaScript 动态增加行~
- VC命令行编译
- 中国制造之痛:一部iPhone只赚4美元
- mysq中的l数据类型
- DOS遍历文件夹命令
- 赫夫曼树编码