开发十年,就只剩下这套架构体系了! >>>
<!--包装数据类型 ->//javalangInteger——整数类 //bitCount方法——获取二进制补码中位的数量 int i = 10;int count = Integer.bitCount(i);System.out.print(i + "的二进制补码表示形式的1位的数量");System.out.println(count);//byteValue方法——获取byte类型的值 Integer tobyte = new Integer("125");byte byte1 = tobyte.byteValue();System.out.println(byte1);//compareTo方法——比较整数 Integer int1 = new Integer("100");Integer int2 = new Integer("100");int str = int1.compareTo(int2);System.out.println(str);//decode方法——将字符串解码为int类型 String str = new String("100");Integer a = Integer.decode(str);System.out.println(a);//doubleValue方法——返回double数值 Integer todouble = new Integer(123);double str = todouble.doubleValue();System.out.println(str);//equals方法——比较整数对象是否相等 Integer i = new Integer(123);Integer j = new Integer(123);boolean b = i.equals(j);System.out.println(b);//floatValue方法——返回float值 Integer floats = new Integer(123);float str = floats.floatValue();System.out.println(str);//getInteger方法——获取整数的系统属性值 String nm = "sun.arch.data.model";Integer i = Integer.getInteger(nm);System.out.println(i);//hashCode方法——生成整数的哈希码 Integer i = new Integer(10);int j = i.hashCode();System.out.println(j);//highestOneBit方法——获取整数二进制最高位的索引 for (int i = 0; i < 10; i++) {int j = Integer.highestOneBit(i);System.out.println(j);//intValue方法——获取int值 Integer ints = new Integer("12");int str = ints.intValue();System.out.println(str);//longValue方法——获取long值 Integer longs = new Integer("12");long str = longs.longValue();System.out.println(str);//lowestOneBit方法——获取整数二进制最低位的索引 for (int i = 0; i < 10; i++) {int j = Integer.lowestOneBit(i);System.out.println(j);}//parseInt方法——将字符串解析为int值 String stri = new String("100");int str = Integer.parseInt(stri);System.out.println(str);//reverse方法—反转整数二进制补码的位顺序 int i;int j = 10;i = Integer.reverse(j);System.out.println(i);//reverseBytes方法—反转整数字节的顺序 int i;int j = 10;i = Integer.reverseBytes(j);System.out.println(i);//shortValue方法—获取short值 int i = 10;Integer shorts = new Integer(i);short str = shorts.shortValue();System.out.println(str);//signum方法—获取整数符号 int i = 10;System.out.println(Integer.signum(i));//toBinaryString方法—生成整数的二进制字符串 int i = 10;Integer stri = new Integer(i);String str = Integer.toBinaryString(stri);System.out.println(str);//toHexString方法—生成整数的十六进制字符串 Integer stri = new Integer(10);String str = Integer.toHexString(stri);System.out.println(str);//toOctalString方法—生成整数的八进制字符串 Integer stri = new Integer(10);String str = Integer.toOctalString(stri);System.out.println(str);//toString方法—生成整数的十进制字符串 Integer stri = new Integer(10);String str = Integer.toString(stri);System.out.println(str);//valueOf方法—创建Integer对象 Integer stri = new Integer(10);Integer str = Integer.valueOf(stri);System.out.println(str);
//javalangString——字符串 //charAt方法——提取指定字符 String strCom = "I LIKE JAVA";char strLower = strCom.charAt(4);System.out.println(strLower);//codePointAt方法—提取索引字符代码点 String strCom = "I LIKE JAVA";int strLower = strCom.codePointAt(8);System.out.println(strLower);//codePointBefore方法——获取索引前一个字符的代码点 String strCom = "I LIKE JAVA";int strLower = strCom.codePointBefore(8);System.out.println(strLower);//codePointCount方法——获取指定范围文本代码点数 String strCom = "I LIKE JAVA";int strLower = strCom.codePointCount(2, 3);System.out.println(strLower);//compareTo方法——比较两个字符串 String strCom = "I LIKE JAVA";String strCom1 = "I LIKE PHP";int strLower = strCom.compareTo(strCom1);System.out.println(strLower);//compareToIgnoreCase方法——忽略大小写比较字符串 String strCom = "I LIKE JAVA";String strCom1 = "I LIKE PHP";int strLower = strCom.compareToIgnoreCase(strCom1);System.out.println(strLower);//concat方法——字符串结尾连接 String strCom = "I LIKE JAVA";String strCom1 = "I LIKE PHP";String str = strCom.concat(strCom1);System.out.println(str);//contains方法——判断是否包含指定字符 String strCom = "I LIKE JAVA";boolean str = strCom.contains("JAVA");System.out.println(str);//copyValueOf方法——字符数组生成字符串 char[] array = {'科','技'};String str = String.copyValueOf(array);System.out.println(str);//endsWith方法——判断后缀字符串 String strCom = "string.java";boolean str = strCom.endsWith(".java");System.out.println(str);//equals方法——判断字符串相等 String strCom1 = "MN";String strCom2 = "mn";boolean strB = strCom1.equals(strCom2);System.out.println(strB);//equalsIgnoreCase方法——忽略大小写判断字符串相等 String strCom1 = "MN";String strCom2 = "mn";boolean strB = strCom1.equalsIgnoreCase(strCom2);System.out.println(strB);//format方法——格式化字符串 String str = String.format("%d", 400/2);System.out.println(str);//getBytes方法——获取字符串的字节数组 String strCom = "java";byte[] str = strCom.getBytes();for (int i = 0; i < str.length; i++) {System.out.println(str[i]);}//getChars方法——获取字符数组 String str = "HELLO WORLD";char[] ch = new char[10];str.getChars(0, 10, ch, 0);for (int i = 0; i < ch.length; i++) {System.out.println(ch[i]);}//hashCode方法——生成字符串哈希表 String str = "I LIKE JAVA";System.out.println(str.hashCode());//indexOf方法——获取字符第一个索引 String str = "Hello World";int index = str.indexOf(5);System.out.println(index);//intern方法——获取规范化字符串 String str1 = new String("helloworld");String str2 = new String("helloworld");System.out.println(str1.equals(str2));System.out.println(str1 == str2);System.out.println(str1.intern() == str2.intern());//isEmpty方法——判断字符串是否为空 String str = "hello world";boolean b = str.isEmpty();System.out.println(b);//lastIndexOf方法——获取字符最后的索引 String strCom = "abcdefg gfdecba";int index = strCom.lastIndexOf("a");System.out.println(index);//length方法——获取字符串的长度 String str = "I like Java";int length = str.length();System.out.println(length);//matches方法——匹配正则表达式 String regex = "1234";System.out.println(regex.matches("\\d{4}"));//offsetByCodePoints方法——获取索引偏移后指定代码点的索引 String strCom = "I LIKE JAVA";int i = strCom.offsetByCodePoints(2, 3);System.out.println(i);//regionMatches方法——测试两个字符串区域是否相等 String strCom = "ABLIKE";String subStr = "CDLIKE";boolean b = subStr.regionMatches(true, 2, strCom, 2, 3);System.out.println(b);//replace方法——替换字符序列 String str = "图书";str.replace("图书", "参考");System.out.println(str);//replaceAll方法——正则表达式匹配替换所有字符串 String str = "成功者找方法,";str = str.replaceAll(",", "失败者找理由");System.out.println(str);//replaceFirst方法——正则表达式替换第一个匹配的字符串 String str = "1词典,1图书,1软件";str = str.replaceFirst("1", "JAVA");System.out.println(str);//split方法——字符串分割成数组 String str = "公司名称:xxx科技!公司所在地:XXX市。公司电话:11122";String[] info = null;info = str.split("!|。");for (int i = 0; i < info.length; i++) {System.out.println(info[i]);}//startsWith方法——判断前缀字符串 String strCom1 = "I like Java";boolean strB = strCom1.startsWith("I l",0);System.out.println(strB);//subSequence方法——获取子字符串序列 String strCom = "I IIKE JAVA";System.out.println(strCom.subSequence(2, 6));//subString方法——获取子字符串 String strCom = "I IIKE JAVA";String strResult = strCom.substring(3);System.out.println(strResult);//toCharArray方法——字符串变字符数组 String strCom = "JAVA参考大全";char[] str = strCom.toCharArray();for (int i = 0; i < str.length; i++) {System.out.println(str[i]);}//toLowerCase方法——转换成小写字符串 String strCom = "I LIKE JAVA";String strLower = strCom.toLowerCase();System.out.println(strLower);//toUpperCase方法——转换成大写字符串 String strCom = "i like java";String strLower = strCom.toUpperCase();System.out.println(strLower);//trim方法——去除空格 String strCom = " JAVA参考大全 ";String str = strCom.trim();System.out.println(str);//valueOf方法——基本数据类型转成字符串 boolean strCom = true;String str = String.valueOf(strCom);System.out.println(str);
//javalangLong——长整型类 //bitCount方法——获取二进制补码中的数量 for (int i = 0; i < 10; i++) {int count = Long.bitCount(i);System.out.println(count);}//byteValue方法——获取byte值 Long bytes = new Long("125");byte str = bytes.byteValue();System.out.println(str);//compareTo方法——比较长整数 Long l1 = new Long("125");Long l2 = new Long("125");int str = l1.compareTo(l2);System.out.println(str);//decode方法——字符串解码为long类型 String stri = new String("100");Long str = Long.decode(stri);System.out.println(str);//doubleValue方法——返回double数值 Long doubles = new Long(123);double str = doubles.doubleValue();System.out.println(str);//equals方法——判断长整数对象相等 Long i = new Long(123);Long j = new Long(123);boolean b = i.equals(j);System.out.println(b);//floatValue方法——获取float数值 Long floats = new Long(123);float str = floats.floatValue();System.out.println(str);//getLong方法——获取长整数的系统属性值 String nm = "sun.arch.data.mode1";Long i = Long.getLong(nm);System.out.println(i);//hashCode方法——生成长整数的哈希码 Long i = new Long(10);int j = i.hashCode();System.out.println(j);//highestOneBit方法——获取长整数二进制最高位的索引 Long l = new Long(10);long j = Long.highestOneBit(l);System.out.println(j);//intValue方法——获取int值 Long ints = new Long(22456L);int str = ints.intValue();System.out.println(str);//longValue方法——获取long值 Long longs = new Long("12");long str = longs.longValue();System.out.println(str);//lowestOneBit方法——获取长整数二进制最低位的索引 Long l = new Long(10);long j = Long.lowestOneBit(l);System.out.println(j);//parseLong方法——将字符串解析为long值 String str[] = {"15","20","45","35"};long sum = 0;for (int i = 0; i < str.length; i++) {long mylong = Long.parseLong(str[i]);sum += mylong;}System.out.println("数组求和为:"+sum);//reverse方法——反转长整数二进制补码的位顺序 long i;i = Long.reverse(10);System.out.println(i);//reverseBytes方法——反转长整数字节的顺序 long i;i = Long.reverseBytes(10);System.out.println(i);//shortValue方法——获取short值 Long shorts = new Long(12L);short str = shorts.shortValue();System.out.println(str);//signum方法——获取长整数符号 long i = 10;System.out.println(Long.signum(i));//toBinaryString方法——生成长整数的二进制字符串 Long stri = new Long(10L);String str = Long.toBinaryString(stri);System.out.println(str);//toHexString方法——生成长整数的十六进制字符串 Long stri = new Long(456);String str = Long.toHexString(stri);System.out.println(str);//toOctalString方法——生成长整数的八进制字符串 Long stri = new Long(456);String str = Long.toOctalString(stri);System.out.println(str);//toString方法——生成长整数的十进制字符串 Long stri = new Long(10);String str = Long.toString(stri);System.out.println(str);//valueOf方法——创建Long对象 Long stri = new Long(10L);long str = Long.valueOf(stri);System.out.println(str);
//javalangShort——短整型类 //compareTo方法——比较短整数 Short com = new Short("125");Short com1 = new Short("125");int str = com.compareTo(com1);System.out.println(str);//decode方法——字符串解码为short类型 String stri = new String("100");Short str = Short.decode(stri);System.out.println(str);//doubleValue方法——返回double数值 short shor = 125;Short doubles = new Short(shor);double str = doubles.doubleValue();System.out.println(str);//equals方法——判断短整数对象相等 Short i = new Short("123");Short j = new Short("123");boolean b = i.equals(j);System.out.println(b);//floatValue方法——获取float数值 Short shor = 125;Short floats = new Short(shor);float str = floats.floatValue();System.out.println(str);//hashCode方法——生成短整数的哈希码 Short i = new Short("10");int j = i.hashCode();System.out.println(j);//intValue方法——获取int值 short shor = 125;Short ints = new Short(shor);int str = ints.intValue();System.out.println(str);//longValue方法——获取long值 Short Shorts = new Short("12345");long str = Shorts.longValue();System.out.println(str);//parseShort方法——将字符串解析为十进制short值 String str[] = {"15","20","45","35"};short sum = 0;for (int i = 0; i < str.length; i++) {Short mylong = Short.parseShort(str[i]);sum += mylong;}System.out.println("数组求和为:"+sum);//reverseBytes方法——反转短整数字节的顺序 short i = 10;short j = Short.reverseBytes(i);System.out.println(j);//shortValue方法——获取short值 Short i = 10;short j = i.shortValue();System.out.println(j);//toString方法——生成短整数的十进制字符串 Short stri = new Short("10");String str = Short.toString(stri);System.out.println(str);//valueOf方法——创建Short对象 Short stri = new Short("100");Short str = Short.valueOf(stri);System.out.println(str);
//javalangBoolean——布尔类 //booleanValue方法——获取boolean值 Boolean bool = new Boolean("true");boolean b = bool.booleanValue();System.out.println(b);//compareTo方法——比较布尔值 Boolean b1 = true;Boolean b2 = true;int i;i = b1.compareTo(b2);System.out.println(i);//equals方法——判断相等 Boolean b1 = true;Boolean b2 = false;boolean b;b = b1.equals(b2);System.out.println(b);//getBoolean方法——获取布尔类型的系统属性值 String nm = "sun.arch.date.model";boolean b = Boolean.getBoolean(nm);System.out.println(b);//hashCode方法——生成布尔对象的哈希码 Boolean b = true;int i = b.hashCode();System.out.println(i);//parseBoolean方法——将字符串解析成boolean值 String s = "true";boolean b = Boolean.parseBoolean(s);System.out.println(b);//toString方法——生成布尔值的字符串 Boolean b = false;String s = b.toString();System.out.println(s);//valueOf方法——创建布尔对象 Boolean i = true;Boolean b = Boolean.valueOf(i);System.out.println(b);
//javalangByte——字节对象 //compareTo方法——比较字节对象 Byte b1 = new Byte("10");Byte b2 = new Byte("20");int i;i = b1.compareTo(b2);System.out.println(i);//decode方法——将字符串解码为byte值 String s = "0x64";Byte b = Byte.decode(s);System.out.println(b);//doubleValue方法——获取double值 Byte b = 100;double d = b.doubleValue();System.out.println(d);//equals方法——判断字节相等 Byte b1 = 10;Byte b2 = 20;boolean b;b = b1.equals(b2);System.out.println(b);//floatValue方法——获取float值 Byte b1 = 10;float f = b1.floatValue();System.out.println(f);//hashCode方法——生成字节对象的哈希码 Byte b1 = 10;int i = b1.hashCode();System.out.println(i);//intValue方法——获取int值 byte by = 123;Byte b = new Byte(by);int it = b.intValue();System.out.println(it);//longValue方法——获取long值 Byte b1 = 100;long i = b1.longValue();System.out.println(i);//parseByte方法——将字符串解析为byte值 String str = new String("12");byte it = Byte.parseByte(str);System.out.println(it);//shortValue方法——获取short值 Byte b1 = 10;short i = b1.shortValue();System.out.println(i);//toString方法——生成字节值的十进制字符串 Byte str = new Byte("125");String it = Byte.toString(str);System.out.println(it);//valueOf方法——创建Byte对象 Byte b1 = 10;Byte b = Byte.valueOf(b1);System.out.println(b);
//javalangCharacter——字符类 //charCount方法——计算指定字符代码点的数量 int c1 = 0x10000;int cha = Character.charCount(c1);System.out.println(cha);//charValue方法——获取char值 Character c1 = new Character('a');char cha = c1.charValue();System.out.println(cha);//codePointAt方法——获取字符数组元素的代码点 char[] c1 = {'科','技'};int cha = Character.codePointAt(c1, 1);System.out.println(cha);//codePointBefore方法——获取字符数组索引前一个元素的代码点 char[] c1 = {'科','技'};int cha = Character.codePointBefore(c1, 1);System.out.println(cha);//codePointCount方法——返回字符数组的子数组中代码点的数量 char[] c1 = {'科','技'};int cha = Character.codePointCount(c1,0,1);System.out.println(cha);//compareTo方法——比较字符对象 Character c1 = new Character('2');Character c2 = new Character('1');int cha = c1.compareTo(c2);System.out.println(cha);//equals方法——判断字符对象相等 Character c = new Character('a');boolean b = c.equals(new Character('a'));System.out.println(b);//getNumericValue方法——返回字符表示的int值 char c = '\u216C';int i = Character.getNumericValue(c);System.out.println(i);//getType方法——返回一个指示字符的常规类别的值 char ch = 'a';System.out.println(Character.getType(ch));//hashCode方法——生成字符对象的哈希码 Character c = new Character('a');int i = c.hashCode();System.out.println(i);//isDefined方法——判断是否为Unicode字符 boolean b = Character.isDefined(11);System.out.println(b);//isDigit方法——判断是否为数字字符 char c2 = '科';boolean cha = Character.isDigit(c2);System.out.println(cha);//isLetter方法——判断是否为字母字符 boolean bool = Character.isLetter('*');System.out.println(bool);//isLowerCase方法——判断是否为小写字符 char c1 = 'a';boolean bool = Character.isLowerCase(c1);System.out.println(bool);//isUpperCase方法——判断是否为大写字符 char c1 = 'L';boolean bool = Character.isUpperCase(c1);System.out.println(bool);//toLowerCase方法——转换为小写字符 char c1 = 'L';char cha = Character.toLowerCase(c1);System.out.println(cha);//toUpperCase方法——转换为大写字符 char c1 = 'a';char cha = Character.toUpperCase(c1);System.out.println(cha);
//javalangDouble——双精度数字类 //byteValue方法——获取byte值 Double d1 = new Double(58.78);byte dou = d1.byteValue();System.out.println(dou);//compare方法——比较双精度数字对象 double d1 = 45.23;double d2 = 45.22;int dou = Double.compare(d1, d2);System.out.println(dou);//compareTo方法——比较两个Double对象 Double d1 = 45.23;Double d2 = 45.22;int dou = d1.compareTo(d2);System.out.println(dou);//intValue方法——将double值以int形式返回 Double d1 = new Double(45.23F);int dou = d1.intValue();System.out.println(dou);//doubleToLongBits方法——返回指定浮点值的表示形式 double d = 123.456;long l = Double.doubleToLongBits(d);System.out.println(l);//doubleToRawLongBits方法——保留NaN值返回指定浮点值的表示形式 double d = 123.456;long l = Double.doubleToRawLongBits(d);System.out.println(l);//doubleValue方法——获取double值 Double d1 = new Double(123.456);double d2 = d1.doubleValue();System.out.println(d2);//equals方法——判断Double对象是否相等 Double d1 = new Double(123.456);Double d2 = new Double(123.456);boolean b = d1.equals(d2);System.out.println(b);//floatValue方法——获取float值 Double d1 = new Double(123.456);float f = d1.floatValue();System.out.println(f);//hashCode方法——生成Double对象的哈希码 Double d1 = new Double(123.456);int i = d1.hashCode();System.out.println(i);//isInfinite方法——判断double值的大小是否是无穷大 Double d1 = new Double(45.23F);boolean dou = d1.isInfinite();System.out.println(dou);//isNaN方法——判断double值是否是一个非数字值 Double d1 = new Double(45.23F);boolean dou = d1.isNaN();System.out.println(dou);//longBitsToDouble方法——返回给定位表示形式的double值 double d1 = 123.456;long l = Double.doubleToLongBits(d1);System.out.println(l);//longValue方法——获取long值 Double d1 = new Double(45.23F);long dou = d1.longValue();System.out.println(dou);//parseDouble方法——将字符串解析为double值 String d1 = new String("124");double dou = Double.parseDouble(d1);System.out.println(dou);//shortValue方法——获取short值 Double d1 = new Double(45.23F);short dou = d1.shortValue();System.out.println(dou);//toHexString方法——生成双精度数字的十六进制字符串 Double d1 = new Double(0.25);String dou = Double.toHexString(d1);System.out.println(dou);//toString方法——生成双精度数字的十进制字符串 Double d1 = new Double(0.25F);String dou = Double.toString(d1);System.out.println(dou);//valueOf方法——创建Double对象 Double d1 = new Double(0.25F);Double dou = Double.valueOf(d1);System.out.println(dou);
//javalangFloat——浮点类 //byteValue方法——获取byte值 Float f = new Float(123.456f);byte b = f.byteValue();System.out.println(b);//compare方法——比较Float对象 float f1 = 456.23F;float f2 = 456.22F;int f = Float.compare(f1, f2);System.out.println(f);//compareTo方法——比较两个Float对象所表示的数值 Float f1 = 456.23F;Float f2 = 456.22F;int f = f1.compareTo(f2);System.out.println(f);//doubleValue方法——获取double值 Float f = new Float(123.456F);double d = f.doubleValue();System.out.println(d);//equals方法——判断Float对象相等 Float f1 = new Float(123.456f);Float f2 = new Float(123.456f);boolean b = f1.equals(f2);System.out.println(b);//floatToIntBits方法——返回浮点值的表示形式 float f = 123.456f;int i = Float.floatToIntBits(f);System.out.println(i);//floatToRawIntBits方法——保留非数字值返回指定浮点值的表示形式 float f = 123.456f;int i = Float.floatToRawIntBits(f);System.out.println(i);//floatValue方法——获取float值 Float f = new Float(123.456f);float ff = f.floatValue();System.out.println(ff);//hashCode方法——返回Float对象的哈希码 Float f = new Float(123.456f);int i = f.hashCode();System.out.println(i);//intBitsToFloat方法——返回指定位表示形式的float值 float f = 123.456f;int i = Float.floatToIntBits(f);System.out.println(i);//intValue方法——获取int值 Float f1 = new Float(456.23F);int fol = f1.intValue();System.out.println(fol);//isInfinite方法——判断float值的大小是否是无穷大 Float f1 = new Float(456.23F);boolean b = f1.isInfinite();System.out.println(b);//isNaN方法——判断float值是否是一个非数字值 Float f = new Float(11.23F);boolean b = f.isNaN();System.out.println(b);//longValue方法——获取long值 Float f = new Float(456.23F);long l = f.longValue();System.out.println(l);//parseFloat方法——将字符串解析成float值 String s = new String("124");float f = Float.parseFloat(s);System.out.println(f);//shortValue方法——获取short值 Float f = new Float(35.23F);short sh = f.shortValue();System.out.println(sh);//toHexString方法——生成浮点数的十六进制字符串 Float f = new Float(0.25);String s = Float.toHexString(f);System.out.println(s);//toString方法——生成浮点数的十进制字符串 Float f = new Float(0.25F);String s = Float.toString(f);System.out.println(s);//valueOf方法——创建浮点数对象 Float f1 = new Float(0.25F);Float f2 = Float.valueOf(f1);System.out.println(f2);
<!--集合操作 ->
//javautilList——有序集合类 //add方法——向列表中插入元素 ArrayList<String> list = new ArrayList<String>();list.add("学生");list.add(null);list.add("老师");for (int i = 0; i < list.size(); i++) {System.out.println(i+":"+list.get(i));}//addAll方法——将指定collection添加到列表中 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");List<String> list_ad = new ArrayList<String>();list_ad.add("公益广告");boolean flag = list.addAll(list_ad);System.out.println(flag);System.out.println(list);//clear方法——从列表中移除所有元素 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");System.out.println(list);list.clear();System.out.println(list);//contains方法——判断列表中是否包含指定元素 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");String o = "保护环境";System.out.println(list.contains(o));//containsAll方法——判断列表中是否包含指定collection的所有元素 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");String o = "保护环境";List<String> list_ad = new ArrayList<String>();list_ad.addAll(list);list_ad.add(0,"公益广告");System.out.println(list_ad.containsAll(list));//equals方法——比较指定的对象与列表是否相等 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");List<String> list_ad = new ArrayList<String>();list_ad.add("保护环境");list_ad.add("爱护地球");list_ad.add("从我做起");boolean ret = list_ad.equals(list);if(ret){System.out.println("两个相同");}else{System.out.println("两个不同");}//get方法——获取列表指定位置的元素 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");String ret = list.get(1);System.out.println(ret);//set方法——替换列表中指定位置的元素 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");String ret = list.set(1, "少用塑料袋");System.out.println(ret);;System.out.println(list);//hashCode方法——返回列表的哈希码值 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");int ret = list.hashCode();System.out.println(ret);//indexOf方法——返回第一次出现指定元素的位置 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");int index = list.indexOf("从我做起");System.out.println(index);//lastIndexOf方法——返回最后一次出现指定元素的位置 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");int index = list.lastIndexOf("从我做起");System.out.println(index);//isEmpty方法——判断集合是否为空 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");boolean empty = list.isEmpty();System.out.println(empty);//iterator方法——返回迭代器 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");Iterator<String> it = list.iterator();while (it.hasNext()) {System.out.println(it.next());}//listIterator方法——返回列表迭代器 ArrayList list = new ArrayList();for (int i = 0; i < 5; i++) {list.add("JAVA参考大全"+i);}ListIterator li = list.listIterator();while (li.hasNext()) {System.out.println(li.next());}//remove方法——移出列表中的指定元素 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");String str = list.remove(1);System.out.println(str);Iterator<String> it = list.iterator();while (it.hasNext()) {System.out.println(it.next());}//removeAll方法——从列表中移除指定collection中包含的所有元素 List<String> list = new ArrayList<String>();list.add("保护环境");list.add("爱护地球");list.add("从我做起");List<String> list1 = new ArrayList<String>();list1.add("保护环境");list1.add("爱护地球");boolean ret = list1.removeAll(list);System.out.println(ret);//retainAll方法——保留指定collection中包含的所有元素 List<String> list = new ArrayList<String>();list.add("第一个");list.add("第二个");list.add("第三个");List<String> list1 = new ArrayList<String>();list1.add("第一个");list1.add("第三个");boolean ret = list.retainAll(list1);System.out.println(ret);//size方法——返回列表中元素的个数List<String> list = new ArrayList<String>();list.add("第一个");list.add("第二个");list.add("第三个");int listSize = list.size();System.out.println(listSize);//subList方法——获取列表中指定范围的子列表 List<String> list = new ArrayList<String>();list.add("第一个");list.add("第二个");list.add("第三个");list.add("第四个");list.add("第五个");List<String> subList = list.subList(3, 5);Iterator<String> iterator = subList.iterator();while (iterator.hasNext()) {System.out.println(iterator.next());}//toArray方法——返回所有元素的数组 List<String> list = new ArrayList<String>();list.add("第一个");list.add("第二个");list.add("第三个");list.add("第四个");list.add("第五个");Object[] arr = list.toArray();for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}
//javautilMap——映射集合类//clear方法——移除所有映射关系 Map map = new HashMap();map.put("昨天", "定制目录");map.put("今天", "开始写作");map.put("明天", "当然继续写作");System.out.println(map.size());map.clear();System.out.println(map.size());//containsKey方法——判断是否包含指定的键名 Map map = new HashMap();map.put("apple", "新鲜苹果");map.put("compiter", "配置优良的计算机");map.put("book", "推挤成山的图书");String key = "book";boolean contains = map.containsKey(key);System.out.println(contains);//containsValue方法——判断是否包含指定的键值 Map map = new HashMap();map.put("apple", "新鲜苹果");map.put("compiter", "配置优良的计算机");map.put("book", "推挤成山的图书");String value = "新鲜苹果";boolean contains = map.containsValue(value);System.out.println(contains);//equals方法——判断是否与指定的对象相同 Map map = new HashMap();map.put("apple", "新鲜苹果");map.put("compiter", "配置优良的计算机");map.put("book", "推挤成山的图书");Map map2 = new HashMap();map2.put("apple", "新鲜苹果");map2.put("compiter", "配置优良的计算机");map2.put("book", "推挤成山的图书");boolean contains = map.equals(map2);System.out.println(contains);//get方法——返回指定键所映射的值 Map map = new HashMap();map.put("apple", "新鲜苹果");map.put("compiter", "配置优良的计算机");map.put("book", "推挤成山的图书");Object get = map.get("apple");System.out.println(get);//isEmpty方法——判断是否为空 Map map = new HashMap();System.out.println("是否为空"+map.isEmpty());map.put("apple", "新鲜苹果");map.put("compiter", "配置优良的计算机");map.put("book", "推挤成山的图书");System.out.println("是否为空"+map.isEmpty());//keySet方法——获取Map集合的所有key Map map = new HashMap();map.put("apple", "新鲜苹果");map.put("compiter", "配置优良的计算机");map.put("book", "推挤成山的图书");Set keySet = map.keySet();for (Object object : keySet) {System.out.println(object);}//put方法——向指定索引位置添加对象 Map map = new HashMap();map.put("apple", "新鲜苹果");map.put("compiter", "配置优良的计算机");map.put("book", "推挤成山的图书");int size = map.size();System.out.println(size);//putAll方法——追加另一个Map对象到当前Map集合 Map map = new HashMap();map.put("apple", "新鲜苹果");map.put("compiter", "配置优良的计算机");map.put("book", "推挤成山的图书");Map map1 = new HashMap();map1.put("apple1", "新鲜苹果");map1.put("compiter1", "配置优良的计算机");map1.put("book1", "推挤成山的图书");map1.putAll(map);System.out.println(map1);//remove方法——移除Map集合中指定键名的内容 Map map = new HashMap();map.put("apple", "新鲜苹果");map.put("compiter", "配置优良的计算机");map.put("book", "推挤成山的图书");map.remove("apple");System.out.println(map);//size方法——获取Map集合类的大小 Map map = new HashMap();map.put("apple", "新鲜苹果");map.put("compiter", "配置优良的计算机");map.put("book", "推挤成山的图书");System.out.println(map.size());//values方法——获取Map集合中的所有键值对象 Map map = new HashMap();map.put("apple", "新鲜苹果");map.put("compiter", "配置优良的计算机");map.put("book", "推挤成山的图书");Collection values = map.values();for (Object object : values) {System.out.println(object);}
//javautilSet——无重复元素集合类 //add方法——向Set集合中添加对象 HashSet set = new HashSet();set.add("a");set.add("b");set.add("c");int size = set.size();System.out.println(size);//addAll方法——向Set集合添加另一个集合的所有内容 HashSet set = new HashSet();set.add("a");set.add("b");set.add("c");HashSet set1 = new HashSet();set1.add("a1");set1.add("b1");set1.add("c1");set1.addAll(set);System.out.println(set1);//clear方法——从Set集合中移除所有内容 HashSet set = new HashSet();set.add("a");set.add("b");set.add("c");int size = set.size();System.out.println(size);set.clear();size = set.size();System.out.println(size);//contains方法——判断Set集合是否包含指定对象 HashSet set = new HashSet();set.add("a");set.add("b");set.add("c");boolean contains = set.contains("a");System.out.println(contains);//containsAll方法——判断Set集合是否包含另一个集合中的全部对象 HashSet set = new HashSet();set.add("a");set.add("b");set.add("c");ArrayList list = new ArrayList();list.add("a");list.add("b");boolean contains = set.containsAll(list);System.out.println(contains);//equals方法——比较指定对象与Set集合对象是否相等 HashSet set = new HashSet();set.add("a");set.add("b");set.add("c");HashSet set1 = new HashSet();set1.add("a");set1.add("b");set1.add("c");boolean contains = set1.equals(set);System.out.println(contains);//isEmpty方法——判断Set集合是否为空 HashSet set = new HashSet();System.out.println("是否为空"+set.isEmpty());set.add("a");set.add("b");set.add("c");System.out.println("是否为空"+set.isEmpty());//iterator方法——获取Set集合的迭代器 HashSet set = new HashSet();set.add("a");set.add("b");set.add("c");Iterator iterator = set.iterator();while (iterator.hasNext()) {System.out.println(iterator.next());}//remove方法——移除Set集合中的指定对象 HashSet set = new HashSet();set.add("a");set.add("b");set.add("c");System.out.println(set.size());set.remove("a");System.out.println(set.size());//removeAll方法——移除另一个集合所包含的所有内容 HashSet set = new HashSet();set.add("a");set.add("b");set.add("c");System.out.println(set.size());set.removeAll(set);System.out.println(set.size());//retainAll方法——保留另一个集合所包含的所有内容 HashSet set = new HashSet();set.add("a");set.add("b");set.add("c");System.out.println(set.size());set.retainAll(set);System.out.println(set.size());//size方法——获取Set集合类的大小 HashSet set = new HashSet();set.add("a");set.add("b");set.add("c");System.out.println(set.size());//toArray方法——用Set集合的所有对象创建数组 HashSet set = new HashSet();set.add("a");set.add("b");set.add("c");Object[] toArray = set.toArray();System.out.println(toArray.length);
<!--日期与时间 ->
//javautilDate——日期/时间类 //after方法——测试当前日期是否在指定的日期之后 Date beforeDate = new Date(302672606563L);Date nowDate = new Date();boolean flag = nowDate.after(beforeDate);System.out.println(flag);//before方法——测试当前日期是否在指定的日期之前 Date beforeDate = new Date(302672606563L);Date nowDate = new Date();boolean flag = nowDate.before(beforeDate);System.out.println(flag);//getTime方法——获得毫秒数 Date date = new Date();long value = date.getTime();System.out.println(value);//setTime方法——设置当前Date对象所表示的日期/时间值 Date date = new Date();date.setTime(302676633308L);System.out.println(date);
//javautilLocale——语言环境相关类 //getAvailableLocales方法——获得所有已安装语言环境的数组 Locale[] locales = Locale.getAvailableLocales();for (int i = 0; i < locales.length; i++) {System.out.println(locales[i]);}//getCountry方法——获得当前语言环境的国家/地区代码 Locale[] locales = Locale.getAvailableLocales();for (int i = 0; i < locales.length; i++) {System.out.println(locales[i]+":"+locales[i].getCountry());}//getDefault方法——获得默认语言环境 Locale locale = Locale.getDefault();System.out.println(locale);//getDisplayCountry方法——获得语言环境国家/地区名 Locale locale = Locale.getDefault();String displayCountry = locale.getDisplayCountry();System.out.println(displayCountry);//getDisplayLanguage方法——获取语言环境的语言名 Locale locale = Locale.getDefault();String displayLanguage = locale.getDisplayLanguage();System.out.println(displayLanguage);//getDisplayName方法——获取语言环境名 Locale locale = Locale.getDefault();String displayName = locale.getDisplayName();System.out.println(displayName);
//javatextDateFormat——格式化时间类//getDateInstance方法——获取日期格式器 Date date = new Date();DateFormat df = DateFormat.getDateInstance();String formatDate = df.format(date);System.out.println(formatDate);//getDateTimeInstance方法——获取日期/时间格式器 Date date = new Date();DateFormat df = DateFormat.getDateTimeInstance();String formatDate = df.format(date);System.out.println(formatDate);//getInstance方法——获取默认日期/时间格式器 Date date = new Date();DateFormat df = DateFormat.getInstance();String formatDate = df.format(date);System.out.println(formatDate);//parse方法——将字符串类型的日期/时间解析为Date类型 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String stringDate = "2011-3-14 9:6:20";Date date = df.parse(stringDate);System.out.println(date);
<!--文件处理 ->
//javaioFile——文件类 //File构造方法 File file = new File("c:/test.txt");File folder = new File("c:/test1");//canExecute方法——判断文件是否可以运行 File file = new File("c:/test.txt");System.out.println(file.canExecute());//canRead方法——判断文件是否可以读取 File file = new File("c:/test.txt");System.out.println(file.canRead());//canWrite方法——判断文件是否可以写入 File file = new File("c:/test.txt");System.out.println(file.canWrite());//compareTo方法——比较文件或文件夹名称的关系 File file = new File("c:/test.txt");File file1 = new File("c:/test1.txt");System.out.println(file.compareTo(file1));//createNewFile方法——创建空文件或者空文件夹 File file = new File("c:/test.txt");file.createNewFile();//createTempFile方法——创建临时文件 File tempFile = File.createTempFile("abc", null);System.out.println(tempFile);//delete方法——删除文件或者空文件夹 File tempFile = File.createTempFile("abc", null);tempFile.delete();//deleteOnExit方法——虚拟机正常终止时逆序删除文件 File tempFile = File.createTempFile("abc", null);tempFile.deleteOnExit();//equals方法——判断两个文件的路径名是否相同 File file = new File("c:/test.txt");File file1 = new File("c:/test.txt");System.out.println(file.equals(file1));//exists方法——测试文件或者文件夹是否存在 File file = new File("c:/test.txt");System.out.println(file.exists());//getAbsoluteFile方法——获得使用绝对路径创建的文件对象 File file = new File("c:/test.txt");System.out.println(file.getAbsoluteFile());//getAbsolutePath方法——获得表示文件绝对路径的字符串 File file = new File("c:/test.txt");System.out.println(file.getAbsolutePath());//getCanonicalFile方法——获得使用规范形式的文件路径创建的文件对象 File file = new File("c:/test.txt");System.out.println(file.getCanonicalFile());//getCanonicalPath方法——获得表示文件规范路径的字符串 File file = new File("c:/test.txt");System.out.println(file.getCanonicalPath());//getFreeSpace方法——获取指定的分区中未分配的字节数 File file = new File("c:");long freeSize = file.getFreeSpace();long gb = freeSize / 1000000000;long mb = (freeSize-gb*1000000000)/1000000;System.out.println(gb+"GB"+mb+"MB");//getName方法——获得文件或者文件夹的名称 File file = new File("c:/test.txt");System.out.println(file.getName());//getParent方法——获取父文件夹的路径名字符串 File file = new File("c:/test.txt");System.out.println(file.getParent());//getParentFile方法——获取父文件夹的抽象路径名 File file = new File("c:/test.txt");System.out.println(file.getParentFile());//getPath方法——获取文件路径 File file = new File("c:/test.txt");System.out.println(file.getPath());//getTotalSpace方法——获取路径名指定的分区大小 File file = new File("c:/test.txt");System.out.println(file.getTotalSpace());//getUsableSpace方法——获取分区上的可用字节数 File file = new File("c:/test.txt");System.out.println(file.getUsableSpace());//hashCode方法——获取路径名的哈希码 File file = new File("c:/test.txt");System.out.println(file.hashCode());//isAbsolute方法——判断路径名是否为绝对路径名 File file = new File("c:/test.txt");System.out.println(file.isAbsolute());//isDirectory方法——判断是否为文件夹 File file = new File("c:/test.txt");System.out.println(file.isDirectory());//isFile方法——判断是否是一个标准文件 File file = new File("c:/test.txt");System.out.println(file.isFile());//isHidden方法——判断是否是隐藏文件 File file = new File("c:/test.txt");System.out.println(file.isHidden());//lastModified方法——获取文件的最后修改时间 File file = new File("c:/test.txt");long time = file.lastModified();Date date = new Date(time);System.out.println(date);//length方法——获取文件的长度 File file = new File("c:/test.txt");System.out.println(file.length());//list方法——返回字符串数组 File root = new File("c:");String[] files = root.list();for (String string : files) {System.out.println(string);}//listFiles方法——获取路径名数组 File root = new File("c:");File[] files = root.listFiles(new FileFilter() {@Overridepublic boolean accept(File pathname) {if(pathname.isHidden()){return true;}return false;}});for (File file : files) {System.out.println(file);}//listRoots方法——列出可用的文件系统根 File[] roots = File.listRoots();for (File file : roots) {System.out.println(file);}//mkdir方法——创建文件夹 File file = new File("c:/test");file.mkdir();//mkdirs方法——创建文件夹 File file = new File("c:/test/test");file.mkdirs();//renameTo方法——重新命名文件 File file = new File("c:/test");file.renameTo(new File("c:/test1"));//setExecutable方法——设置执行权限 File file = new File("c:/test.txt");file.setExecutable(false);//setLastModified方法——设置文件或者文件夹的最后修改时间 File file = new File("c:/test.txt");GregorianCalendar calendar = new GregorianCalendar(2000,0,1);Date date = calendar.getTime();file.setLastModified(date.getTime());//setReadable方法——设置读权限 File file = new File("c:/test.txt");file.setReadable(true,true);//setReadOnly方法——设置文件或文件夹为只读 File file = new File("c:/test.txt");file.setReadOnly();//setWritable方法——设置文件的可写属性 File file = new File("c:/test.txt");file.setWritable(true);//toString方法——返回路径名的字符串形式 File file = new File("c:/test.txt");System.out.println(file.toString());//toURI方法——获取文件的URI File file = new File("c:/test.txt");System.out.println(file.toURI());
//javaioFileInputStream类——文件输入流//available方法——估计剩余的字节数 File file = new File("C:/test.txt");FileInputStream in = new FileInputStream(file);System.out.println(in.available());//close方法——关闭文件输入流 File file = new File("C:/test.txt");FileInputStream in = new FileInputStream(file);for (int i = 0; i < file.length(); i++) {System.out.println(in.read());}in.close();//getChannel方法——返回FileChannel对象 File file = new File("C:/test.txt");FileInputStream in = new FileInputStream(file);FileChannel channel = in.getChannel();in.close();//getFD方法——返回FileDescriptor对象 File file = new File("C:/test.txt");FileInputStream in = new FileInputStream(file);FileDescriptor fd = in.getFD();in.close();//read方法——从文件字节输入流中读取数据 File file = new File("C:/test.txt");FileInputStream in = new FileInputStream(file);int temp = 0;while((temp=in.read())!=-1){System.out.println(temp);}in.close();//skip方法——从输入流中跳过并丢弃n字节的数据 File file = new File("C:/test.txt");FileInputStream in = new FileInputStream(file);in.skip(10);int length = 0;while((length = in.read())!=-1){System.out.println(length);}in.close();
//javaioFileOutputStream类——文件输出流 //close方法——关闭文件输出流 File file = new File("C:/test.txt");FileOutputStream out = new FileOutputStream(file);out.write("JAVA参考手册".getBytes());out.close();//getChannel方法——返回FileChannel对象 File file = new File("C:/test.txt");FileOutputStream out = new FileOutputStream(file);FileChannel channel = out.getChannel();out.close();//getFD方法——返回FileDescriptor对象 File file = new File("C:/test.txt");FileOutputStream out = new FileOutputStream(file);out.getFD();out.close();//write方法——向文件中写入数据 File inputfile = new File("C:/test.txt");File outputfile = new File("C:/test1.txt");FileInputStream in = new FileInputStream(inputfile);FileOutputStream out = new FileOutputStream(outputfile);byte[] b = new byte[1024];in.read(b);out.write(b);out.close();in.close();
//javaioFileReader类——文件的字符输入流 //close方法——关闭字符输入流 File file = new File("C:/test.txt");FileReader reader = new FileReader(file);char[] data = new char[512];int rs = 0;while((rs = reader.read(data))>0){System.out.println(new String(data,0,rs));}reader.close();//read方法——读取字符数据 File file = new File("C:/test.txt");FileReader reader = new FileReader(file);char[] data = new char[512];int rs = 0;while((rs = reader.read(data))>0){System.out.println(new String(data,0,rs));}reader.close();
//javaioFileWriter类——文件的字符输出流 //close方法——关闭字符输出流 File file = new File("C:/test.txt");FileWriter writer = new FileWriter(file);writer.write("JAVA参考手册");writer.close();//flush方法——刷新缓冲区 File file = new File("C:/test.txt");String[] contents = {"JAVA","PHP","C"};FileWriter writer = new FileWriter(file);for (String string : contents) {writer.write(string);}writer.flush();writer.close();//write方法——向字符输出流写数据 File file = new File("C:/test.txt");FileWriter writer = new FileWriter(file);writer.write("JAVA".toCharArray());writer.flush();writer.close();
<!--图片处理 ->
//javaximageioImageIO——图像输入/输出类 //createImageInputStream方法——创建一个ImageInputStream对象 File file = new File("src/img.gif");ImageInputStream iis = ImageIO.createImageInputStream(file);JOptionPane.showMessageDialog(null, "创建成功");iis.close();//getImageReaders方法——获得包含ImageReader的迭代器对象 File file = new File("src/img.gif");ImageInputStream iis = ImageIO.createImageInputStream(file);Iterator<ImageReader> it = ImageIO.getImageReaders(file);if(it.hasNext()){JOptionPane.showMessageDialog(null, "成功");}else{JOptionPane.showMessageDialog(null, "失败"); }iis.close();//getImageReadersByMIMEType方法——获得可以解码MIME类型的迭代器 Iterator<ImageReader> it = ImageIO.getImageReadersByMIMEType("image/jpg");boolean isRead = it.hasNext();System.out.println(isRead);//getImageReadersBySuffix方法——获得可以解码指定文件后缀的迭代器 String suffix = "gif";Iterator<ImageReader> it = ImageIO.getImageReadersBySuffix(suffix);JOptionPane.showMessageDialog(null, "后缀"+ suffix + "解码成功");//getImageWritersByFormatName方法——获得可以解码指定格式的迭代器 String formatName = "jpeg";Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName(formatName);ImageWriter imageWriter = (ImageWriter)it.next();JOptionPane.showMessageDialog(null, "格式"+formatName+"解码成功");//read方法——读取数据到BufferedImage对象 //从指定文件对象读取数据获得一个BufferedImage对象//write方法——将图像以文件的形式写入磁盘 //用于将图像以文件的形式写入磁盘
//javaximageioImageReader——图像的字符输入流 //getFormatName方法——获得文件的格式名称 File file = new File("src/img.gif");ImageInputStream iis = ImageIO.createImageInputStream(file);Iterator<ImageReader> it = ImageIO.getImageReaders(iis);if(it.hasNext()){ImageReader reader = (ImageReader)it.next();System.out.println("格式"+reader.getFormatName());}iis.close();//getNumImages方法——获得当前输入源中可用的图像数 String fileName = "src/img.gif";FileInputStream fin = new FileInputStream(fileName);Iterator<ImageReader> readers = ImageIO.getImageReadersBySuffix("gif");ImageReader imageReader = readers.next();ImageInputStream iis = ImageIO.createImageInputStream(fin);imageReader.setInput(iis,false);int num = imageReader.getNumImages(true);JOptionPane.showMessageDialog(null, "当前输入源"+num+"有可用图像");iis.close();fin.close();//read方法——获得一个BufferedImage对象 String fileName = "src/img.gif";FileInputStream fin = new FileInputStream(fileName);Iterator<ImageReader> readers = ImageIO.getImageReadersBySuffix("gif");ImageReader imageReader = readers.next();ImageInputStream iis = ImageIO.createImageInputStream(fin);imageReader.setInput(iis,false);BufferedImage bufferedImage = imageReader.read(0);iis.close();fin.close();//setInput方法——设置ImageReader的输入源 String fileName = "src/img.gif";FileInputStream fin = new FileInputStream(fileName);Iterator<ImageReader> readers = ImageIO.getImageReadersBySuffix("gif");ImageReader imageReader = readers.next();ImageInputStream iis = ImageIO.createImageInputStream(fin);imageReader.setInput(iis,false);BufferedImage bufferedImage = imageReader.read(0);iis.close();fin.close();
//javaximageioImageWriter——图像输出流 //setOutput方法——设置输出目标 Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("jpg");ImageWriter imageWriter = it.next();File file = new File("src/img.jpg");ImageOutputStream ios = ImageIO.createImageOutputStream(file);imageWriter.setOutput(ios);Object obj = imageWriter.getOutput();if(obj!=null){JOptionPane.showMessageDialog(null, "成功");}//write方法——将完整图像流添加到输出流中 BufferedImage image = new BufferedImage(200,200,BufferedImage.TYPE_INT_RGB);Graphics2D g2 = image.createGraphics();g2.setColor(Color.BLUE);g2.fillRect(20, 20, 90, 90);g2.setColor(Color.RED);g2.fillOval(95, 95, 90, 90);Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("jpg");ImageWriter imageWriter = it.next();File file = new File("src/img.jpg");ImageOutputStream ios = ImageIO.createImageOutputStream(file);imageWriter.setOutput(ios);imageWriter.write(image);ios.close();
<!--窗体和桌面面板 ->
//javaxswingJFrame窗体 //JFrame构造方法 JFrame frame = new JFrame();frame.setBounds(400,320,300,200);frame.setVisible(true);//getContentPane方法——获得JFrame窗体的内容窗格 JFrame frame = new JFrame("使用getContentPane");Container c = frame.getContentPane();c.setLayout(new FlowLayout());JButton btn_1 = new JButton("按钮一");JButton btn_2 = new JButton("按钮二");c.add(btn_1);c.add(btn_2);frame.setBounds(400,320,300,200);frame.setVisible(true);//getDefaultCloseOperation方法——获得指示窗体关闭操作的整数 JFrame frame = new JFrame("窗体默认关闭操作");System.out.println("DO_NOTHING_ON_CLOSE的值 \t"+WindowConstants.DO_NOTHING_ON_CLOSE);System.out.println("HIDE_ON_CLOSE的值 \t"+WindowConstants.HIDE_ON_CLOSE);System.out.println("DISPOSE_ON_CLOSE的值\t"+WindowConstants.DISPOSE_ON_CLOSE);System.out.println("EXIT_ON_CLOSE的值 \t"+WindowConstants.EXIT_ON_CLOSE);System.out.println();System.out.println("默认关闭操作整数\t"+frame.getDefaultCloseOperation());frame.dispose();//getGlassPane方法——返回当前窗体的玻璃窗格对象 JFrame frame = new JFrame("在玻璃面板上添加控件");frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);JPanel glassPanel = new JPanel();glassPanel.setLayout(new FlowLayout());JButton btn_1 = new JButton("按钮一");JButton btn_2 = new JButton("按钮二");glassPanel.add(btn_1);glassPanel.add(btn_2);frame.setGlassPane(glassPanel);Component c = frame.getGlassPane();c.setVisible(true);frame.setBounds(400,320,300,200);frame.setVisible(true);//getGraphics方法——创建绘图上下文对象 JFrame frame = new JFrame("绘制文本和图形");frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,300,200);frame.setVisible(true);Thread.sleep(1000);Graphics g = frame.getGraphics();g.drawString("graphics对象绘制文本", 70, 70);g.drawOval(100, 100, 80, 80);//getRootPane方法——获得当前窗体的根窗格对象 JFrame frame = new JFrame("设置窗体的默认按钮");frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);JButton ok = new JButton("确定");JButton cancel = new JButton("退出");JPanel panel = new JPanel();panel.add(ok);panel.add(cancel);cancel.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {System.exit(0);}});JRootPane root = frame.getRootPane();root.setDefaultButton(cancel);Container content = frame.getContentPane();content.add(panel);frame.setBounds(400,320,300,220);frame.setVisible(true);//remove方法——从当前窗体中移除指定的控件 final JFrame frame = new JFrame("移除窗体上的指定控件");frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);JButton centerButton = new JButton("移除面板的设置按钮");JButton removeButton = new JButton("移除窗体上方的控件");final JPanel centerPanel = new JPanel();JPanel southPanel = new JPanel();centerPanel.add(centerButton);southPanel.add(removeButton);removeButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {frame.remove(centerPanel);frame.pack();}});Container content = frame.getContentPane();content.add(centerPanel);content.add(southPanel,BorderLayout.SOUTH);frame.setBounds(400,320,300,220);frame.setVisible(true);//setContentPane方法——将指定容器设置为当前窗体的内容窗格 final JFrame frame = new JFrame("指定船体的内容窗格");frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);JLabel label = new JLabel("内容");JTextField text = new JTextField(20);JButton btn_1 = new JButton("确定");JButton btn_2 = new JButton("取消");JPanel panel = new JPanel();panel.add(label);panel.add(text);panel.add(btn_1);panel.add(btn_2);frame.setContentPane(panel);frame.setBounds(400,320,300,220);frame.setVisible(true);//setDefaultCloseOperation方法——设置close事件默认执行的操作 JFrame frame = new JFrame("设置窗体默认的关闭方式");frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);frame.setBounds(400,320,300,220);frame.setVisible(true);//setGlassPane方法——设置当前窗体的玻璃窗格 JPanel glassPanel = new JPanel();glassPanel.setLayout(new FlowLayout());JLabel label = new JLabel("设置窗体玻璃窗格");label.setFont(new Font("宋体", Font.BOLD, 26));JButton btn_1 = new JButton("测 试");JButton btn_2 = new JButton("退出");glassPanel.add(label);glassPanel.add(btn_1);glassPanel.add(btn_2);glassPanel.setVisible(true);glassPanel.setBounds(400, 320, 300, 200);//setJMenuBar方法——设置当前窗体的菜单栏 JFrame frame = new JFrame("设置窗体的菜单栏");frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);JMenuBar menubar = new JMenuBar();JMenu menu = new JMenu("系统");JMenuItem menuItem = new JMenuItem("退出");menu.add(menuItem);menubar.add(menu);frame.setJMenuBar(menubar);frame.setBounds(400,320,300,200);frame.setVisible(true);//setLayout方法——设置当前窗体的布局管理器 JFrame frame = new JFrame("使用setLayout方法");frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);Container c = frame.getContentPane();frame.setLayout(new FlowLayout());JButton btn_1 = new JButton("按钮一");JButton btn_2 = new JButton("按钮二");c.add(btn_1);c.add(btn_2);frame.setBounds(400,320,300,200);frame.setVisible(true);
//javaxswingJDialog对话框窗体 //JDialog构造方法——创建对话框窗体 JDialog dialog = new JDialog();dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);dialog.setBounds(400,320,300,200);dialog.setVisible(true);//getContentPane方法——获得JDialog对话框窗体的内容窗格 JDialog dialog = new JDialog();dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);Container c = dialog.getContentPane();c.setLayout(new FlowLayout());JButton btn_ok = new JButton("OK");JButton btn_canel = new JButton("Cancel");c.add(btn_ok);c.add(btn_canel);dialog.setBounds(400,320,300,200);dialog.setVisible(true);//getDefaultCloseOperation方法——获得发起close事件时执行的操作 JDialog dialog = new JDialog();System.out.println("DO_NOTHING_ON_CLOSE的值 \t"+WindowConstants.DO_NOTHING_ON_CLOSE);System.out.println("HIDE_ON_CLOSE的值 \t"+WindowConstants.HIDE_ON_CLOSE);System.out.println("DISPOSE_ON_CLOSE的值 \t"+WindowConstants.DISPOSE_ON_CLOSE);System.out.println();System.out.println("对话框默认关闭操作的整数 \t"+dialog.getDefaultCloseOperation());dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);System.out.println("对话框默认关闭操作的整数 \t"+dialog.getDefaultCloseOperation());dialog.setBounds(400,260,300,200);dialog.setVisible(true);//getGlassPane方法——返回当前对话框窗体的玻璃窗格对象 JDialog dialog = new JDialog();dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);URL url = javaTest.class.getResource("src/img.gif");ImageIcon icon = new ImageIcon(url);JLabel label_icon = new JLabel(icon);JPanel glassPanel = new JPanel();glassPanel.setLayout(new BorderLayout());glassPanel.add(label_icon);dialog.setGlassPane(glassPanel);Component c = dialog.getGlassPane();c.setVisible(true);JLabel label_finish = new JLabel("已完成");label_finish.setFont(new Font("宋体",Font.BOLD,50));dialog.getContentPane().add(label_finish);dialog.setBounds(400,320,300,200);dialog.setVisible(true);Thread.sleep(1000);c.setVisible(false);//getGraphics方法——创建一个绘图上下文对象 JDialog dialog = new JDialog();dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);dialog.setBounds(400,320,300,200);dialog.setVisible(true);Thread.sleep(1000);Graphics g = dialog.getGraphics();g.drawOval(40, 50, 80, 80);g.drawOval(110, 50, 80, 80);g.drawOval(180, 50, 80, 80);g.drawOval(80, 110, 80, 80);g.drawOval(150, 110, 80, 80);//remove方法——从当前对话框窗体中移除指定的控件 final JDialog dialog = new JDialog();dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);final JButton centerButton = new JButton("将要被移除放到对话框中心的按钮");JButton southButton = new JButton("单击我可以移除对话框中心的按钮");southButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {dialog.remove(centerButton);dialog.repaint();}});Container c = dialog.getContentPane();c.add(centerButton,BorderLayout.CENTER);c.add(southButton,BorderLayout.SOUTH);dialog.setBounds(400,320,300,220);dialog.setVisible(true);dialog.setBounds(400,320,300,200);dialog.setVisible(true);//setContentPane方法——将指定容器设置为当前窗体的内容窗格 final JDialog dialog = new JDialog();dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);final JButton centerButton = new JButton("将要被移除放到对话框中心的按钮");JButton southButton = new JButton("单击我可以移除对话框中心的按钮");southButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {dialog.remove(centerButton);dialog.repaint();}});Container c = dialog.getContentPane();c.add(centerButton,BorderLayout.CENTER);c.add(southButton,BorderLayout.SOUTH);dialog.setBounds(400,320,300,220);dialog.setVisible(true);dialog.setBounds(400,320,300,200);dialog.setVisible(true);//setDefaultCloseOperation方法——设置发起close事件时默认执行的操作 final JDialog dialog = new JDialog();dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);dialog.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {System.exit(0);}});dialog.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER,10,30));dialog.getContentPane().add(new JButton("确定"));dialog.getContentPane().add(new JButton("退出"));dialog.setBounds(400,320,300,220);dialog.setVisible(true);dialog.setBounds(400,320,300,200);dialog.setVisible(true);//setGlassPane方法——设置当前对话框窗体的玻璃窗格 //设置当前对话框的玻璃窗格//setJMenuBar方法——设置当前对话框窗体的菜单栏 //设置当前对话框窗体的菜单栏
//javaxswingJDesktopPane桌面面板 //JDesktopPane构造方法 //创建桌面面板对象,对象是内部窗体的容器//getAllFrames方法——返回桌面中显示的所有JInternalFrame //以数组的形式返回桌面中当前显示的所有JInternalFrame//getSelectedFrame方法——获得当前被选择的内部窗体 //用于获得桌面面板中当前活动的JInternalFrame,当前被选中的内部窗体//remove方法——移除指定的JInternalFrame //用于从桌面面板中移除位于指定索引位置处的JInternalFrame//removeAll方法——移除所有的JInternalFrame //用于从桌面面板中移除所有的JInternalFrame//selectFrame方法——选择下一个JInternalFrame //用于选择此桌面面板中的下一个JInternalFrame//setSelectedFrame方法——设置当前活动的JInternalFrame //用于设置桌面面板当前获得JInternalFrame//javaxswingJInternalFrame内部窗体 //JInternalFrame构造方法 //用于创建内部窗体,该窗体不能移除其所在桌面面板//dispose方法——关闭内部窗体 //用于是内部窗体不可见、取消选定并关闭该内部窗体//getContentPane方法——获得JInternalFrame窗体的内容窗格 //用于获得JInternalFrame窗体的内容窗格//getFrameIcon方法——获取JInternalFrame标题栏上显示的图标 //用于获取JInternalFrame标题栏上显示的图标//getTitle方法——获得内部窗体标题栏上显示的文本 //用于获得内部窗体标题了上显示的文本//setClosable方法——设置是否可以关闭内部窗体 //用于设置是否可以通过某个操作关闭内部的窗体//setFrameIcon方法——设置窗体标题栏上显示的图像 //用于设置要在此内部窗体标题栏上显示的图像//setIconifiable方法——设置是否可以使内部窗体图标化 //用于设置是否可以通过某个操作使内部窗体图标化//setMaximizable方法——设置是否可以使内部窗体最大化 //设置是否可以使内部窗体最大化//setResizable方法——设置是否可以改变内部窗体的大小 //用于设置是否可以通过某个操作改变内部窗体的大小//setSelected方法——选定或取消选定内部窗体 //用于选定或取消选定内部窗体//setTitle方法——设置内部窗体标题栏上显示的文本 //用于设置内部窗体标题栏上显示的文本//toBack方法——将内部窗体发送到后台 //用于将内部窗体发送到后台//toFront方法——将内部窗体置于前端 //用于将内部窗体发送到后台
<!--常用面板 ->
//javaxswingJPanel面板 //JPanel构造方法 JFrame frame = new JFrame("使用JPanel面板");frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);JPanel panel = new JPanel();panel.setBackground(Color.ORANGE);frame.getContentPane().add(panel);frame.setBounds(400,320,300,200);frame.setVisible(true);//add方法——在面板容器中添加控件 JPanel panel = new JPanel();panel.add(new JLabel("编号:"));JTextField tf_id = new JTextField(15);panel.add(tf_id);panel.add(new JLabel("姓名:"));JTextField tf_name = new JTextField(15);panel.add(tf_name);JButton btn_exit = new JButton("退 出");panel.add(btn_exit);JFrame frame = new JFrame("使用JPanel面板");frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.getContentPane().add(panel);frame.setBounds(400,320,300,200);frame.setVisible(true);//paintComponent方法——在面板容器中绘制内容 public static void main(String[] args) throws Throwable {JFrame frame = new JFrame("在面板上绘制");frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JPanel panel = new PanelBack();frame.getContentPane().add(panel);frame.setVisible(true);}static class PanelBack extends JPanel{protected void paintComponet(Graphics g){g.setFont(new Font("宋体",Font.BOLD,26));g.drawString("重写方法", 20, 70);g.drawString("面板绘制文本内容", 20, 120);}}//setLayout方法——设置面板容器所使用的布局管理器 //设置布局管理器
//javaxswingJScrollPane滚动面板 //JScrollPane构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JScrollPane scrollPane = new JScrollPane();JTextArea ta = new JTextArea();scrollPane.setViewportView(ta);frame.getContentPane().add(scrollPane);frame.setVisible(true);//setViewportView方法——设置滚动面板上显示的视图控件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JScrollPane scrollPane = new JScrollPane();JTextArea ta = new JTextArea();scrollPane.setViewportView(ta);frame.getContentPane().add(scrollPane);frame.setVisible(true);
//javaxswingJSplitPane分割面板 //JSplitPane构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JSplitPane splitPane = new JSplitPane();frame.getContentPane().add(splitPane);frame.setVisible(true);//setBottomComponent方法——将组件设置到分隔条的下方或右侧 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);splitPane.setDividerLocation(60);splitPane.setBottomComponent(new JButton("下方的按钮"));frame.getContentPane().add(splitPane,BorderLayout.CENTER);frame.setVisible(true);//setContinuousLayout方法——设置分割面板的重绘方式 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JSplitPane splitPane = new JSplitPane();splitPane.setContinuousLayout(true);frame.getContentPane().add(splitPane,BorderLayout.CENTER);frame.setVisible(true);//setDividerLocation方法——设置分隔条的绝对位置 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JSplitPane splitPane = new JSplitPane();splitPane.setDividerLocation(120);frame.getContentPane().add(splitPane,BorderLayout.CENTER);frame.setVisible(true);//setDividerSize方法——设置分隔条的大小 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JSplitPane splitPane = new JSplitPane();splitPane.setDividerLocation(120);splitPane.setDividerSize(25);frame.getContentPane().add(splitPane,BorderLayout.CENTER);frame.setVisible(true);//setLeftComponent方法——将组件添加到分隔条的左侧或上方 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JSplitPane splitPane = new JSplitPane();splitPane.setDividerLocation(120);splitPane.setLeftComponent(new JButton("左侧的按钮"));frame.getContentPane().add(splitPane,BorderLayout.CENTER);frame.setVisible(true);//setOneTouchExpandable方法——设置分割面板是否提供UI小部件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JSplitPane splitPane = new JSplitPane();splitPane.setDividerLocation(90);splitPane.setLeftComponent(new JButton("左侧的按钮"));splitPane.setBottomComponent(new JButton("右侧的按钮"));splitPane.setOneTouchExpandable(true);frame.getContentPane().add(splitPane,BorderLayout.CENTER);frame.setVisible(true);//setOrientation方法——设置分割面板的分割方向 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JSplitPane splitPane = new JSplitPane();splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);splitPane.setDividerLocation(90);splitPane.setLeftComponent(new JButton("上方的按钮"));splitPane.setBottomComponent(new JButton("下方的按钮"));splitPane.setOneTouchExpandable(true);frame.getContentPane().add(splitPane,BorderLayout.CENTER);frame.setVisible(true);//setRightComponent方法——将组件添加到分隔条的右侧或下方 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JSplitPane splitPane = new JSplitPane();splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);splitPane.setDividerLocation(100);splitPane.setRightComponent(new JButton("右侧按钮"));splitPane.setOneTouchExpandable(true);frame.getContentPane().add(splitPane,BorderLayout.CENTER);frame.setVisible(true);//setTopComponent方法——将组件添加到分隔条的上方或左侧 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JSplitPane splitPane = new JSplitPane();splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);splitPane.setDividerLocation(100);splitPane.setTopComponent(new JButton("上方的按钮"));frame.getContentPane().add(splitPane,BorderLayout.CENTER);frame.setVisible(true);
//javaxswingJTabbedPane选项卡面板 //JTabbedPane构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JTabbedPane tabbedPane = new JTabbedPane();JPanel panel = new JPanel();panel.setLayout(null);tabbedPane.addTab("标签一", null,panel,null);JButton button = new JButton();button.setBounds(77,51,155,28);button.setText("标签一中的按钮");panel.add(button);frame.getContentPane().add(tabbedPane,BorderLayout.CENTER);frame.setVisible(true);//addChangeListener方法——将ChangeListener添加到选项卡面板中 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTabbedPane tabbedPane = new JTabbedPane();tabbedPane.addChangeListener(new ChangeListener() {@Overridepublic void stateChanged(ChangeEvent e) {if(true){int index = tabbedPane.getSelectedIndex();String title = tabbedPane.getTitleAt(index);JOptionPane.showMessageDialog(null, title);}}});frame.getContentPane().add(tabbedPane,BorderLayout.CENTER);frame.setVisible(true);//addTab方法——为选项卡面板添加选项卡 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTabbedPane tabbedPane = new JTabbedPane();JPanel panel = new JPanel();JPanel panel1 = new JPanel();tabbedPane.addTab("第一", panel);tabbedPane.addTab("第二", panel1);frame.getContentPane().add(tabbedPane,BorderLayout.CENTER);frame.setVisible(true);//getSelectedIndex方法——返回选择的选项卡标签索引 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTabbedPane tabbedPane = new JTabbedPane();JButton btn_showIndex = new JButton();btn_showIndex.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {int index = tabbedPane.getSelectedIndex();JOptionPane.showMessageDialog(null, "索引值"+index);}});btn_showIndex.setText("显示索引值");frame.getContentPane().add(tabbedPane,BorderLayout.CENTER);frame.setVisible(true);//getTabCount方法——获得选项卡面板拥有选项卡的数量 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTabbedPane tabbedPane = new JTabbedPane();JButton btn_showNum = new JButton();btn_showNum.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {int count = tabbedPane.getTabCount();JOptionPane.showMessageDialog(null, "选项卡面板共有"+count);}});btn_showNum.setText("选项卡数量");tabbedPane.add(btn_showNum);frame.getContentPane().add(tabbedPane,BorderLayout.CENTER);frame.setVisible(true);//getTitleAt方法——获得选项卡标签的标题文本 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTabbedPane tabbedPane = new JTabbedPane();JButton btn_showTitle = new JButton();btn_showTitle.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {int count = tabbedPane.getTabCount();JOptionPane.showMessageDialog(null, "共有"+count+"个");}});btn_showTitle.setText("选项卡数量");tabbedPane.add(btn_showTitle);frame.getContentPane().add(tabbedPane,BorderLayout.CENTER);frame.setVisible(true);//insertTab方法——在指定索引位置处插入选项卡标签 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTabbedPane tabbedPane = new JTabbedPane();JButton btn_insertTitle = new JButton();btn_insertTitle.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {tabbedPane.insertTab("aaa", null, new JButton("测试"), "测试", 1);}});btn_insertTitle.setText("插入选项卡标签");tabbedPane.add(btn_insertTitle);frame.getContentPane().add(tabbedPane,BorderLayout.CENTER);frame.setVisible(true);//setDisabledIconAt方法——设置选项卡标签禁用时显示的图标 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTabbedPane tabbedPane = new JTabbedPane();JPanel panel = new JPanel();tabbedPane.addTab("A", panel);frame.getContentPane().add(tabbedPane,BorderLayout.CENTER);frame.setVisible(true);//setEnabledAt方法——设置指定选项卡标签是否可用 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTabbedPane tabbedPane = new JTabbedPane();JButton btn_enabled = new JButton();btn_enabled.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {tabbedPane.setEnabledAt(0, true);}});btn_enabled.setText("启用A");tabbedPane.add(btn_enabled);frame.getContentPane().add(tabbedPane,BorderLayout.CENTER);frame.setVisible(true);//setSelectedIndex方法——使指定的选项卡标签被选中 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTabbedPane tabbedPane = new JTabbedPane();JPanel panel = new JPanel();tabbedPane.addTab("选项卡A", panel);JPanel panel_1 = new JPanel();tabbedPane.addTab("选项卡B", panel_1);tabbedPane.setSelectedIndex(1);frame.getContentPane().add(tabbedPane,BorderLayout.CENTER);frame.setVisible(true);//setTabLayoutPolicy方法——设置选项卡标签的布局方式 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTabbedPane tabbedPane = new JTabbedPane();JButton btn_wrap = new JButton();btn_wrap.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {tabbedPane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);}});btn_wrap.setText("限制布局");tabbedPane.add(btn_wrap);frame.getContentPane().add(tabbedPane,BorderLayout.CENTER);frame.setVisible(true);//setTabPlacement方法——设置选项卡标签的显示位置 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTabbedPane tabbedPane = new JTabbedPane();JButton btn_top = new JButton();btn_top.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {tabbedPane.setTabPlacement(JTabbedPane.TOP);}});btn_top.setText("上方");tabbedPane.add(btn_top);frame.getContentPane().add(tabbedPane,BorderLayout.CENTER);frame.setVisible(true);
<!--基本布局管理器 ->
//javaawtFlowLayout流布局 //FlowLayout构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);frame.getContentPane().setLayout(new FlowLayout());frame.getContentPane().add(new JButton("按钮A"));frame.getContentPane().add(new JButton("按钮B"));frame.getContentPane().add(new JButton("按钮C"));frame.getContentPane().add(new JButton("按钮D"));frame.setVisible(true);//setAlignment方法——设置流布局管理器使用的对齐方式 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);FlowLayout flowLayout = new FlowLayout();flowLayout.setAlignment(FlowLayout.LEFT);frame.getContentPane().setLayout(flowLayout);frame.getContentPane().add(new JButton("按钮A"));frame.getContentPane().add(new JButton("按钮B"));frame.getContentPane().add(new JButton("按钮C"));frame.getContentPane().add(new JButton("按钮D"));frame.setVisible(true);//setHgap方法——设置水平间隙 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);FlowLayout flowLayout = new FlowLayout();flowLayout.setHgap(25);frame.getContentPane().setLayout(flowLayout);frame.getContentPane().add(new JButton("按钮A"));frame.getContentPane().add(new JButton("按钮B"));frame.getContentPane().add(new JButton("按钮C"));frame.getContentPane().add(new JButton("按钮D"));frame.setVisible(true);//setVgap方法——设置垂直间隙 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);FlowLayout flowLayout = new FlowLayout();flowLayout.setVgap(20);frame.getContentPane().setLayout(flowLayout);frame.getContentPane().add(new JButton("按钮A"));frame.getContentPane().add(new JButton("按钮B"));frame.getContentPane().add(new JButton("按钮C"));frame.getContentPane().add(new JButton("按钮D"));frame.setVisible(true);
//javaawtBorderLayout边界布局 //BorderLayout构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JPanel panel = new JPanel();panel.setLayout(new BorderLayout());frame.getContentPane().add(panel,BorderLayout.CENTER);JButton button = new JButton("中");panel.add(button,BorderLayout.CENTER);JButton button1 = new JButton("北");panel.add(button1,BorderLayout.NORTH);JButton button2 = new JButton("西");panel.add(button2,BorderLayout.WEST);JButton button3 = new JButton("南");panel.add(button3,BorderLayout.SOUTH);JButton button4 = new JButton("东");panel.add(button4,BorderLayout.EAST);frame.setVisible(true);//setHgap方法——设置水平间距 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JPanel panel = new JPanel();BorderLayout borderLayout = new BorderLayout();panel.setLayout(borderLayout);borderLayout.setHgap(20);frame.getContentPane().add(panel,BorderLayout.CENTER);JButton button = new JButton("中");panel.add(button,BorderLayout.CENTER);JButton button1 = new JButton("北");panel.add(button1,BorderLayout.NORTH);JButton button2 = new JButton("西");panel.add(button2,BorderLayout.WEST);JButton button3 = new JButton("南");panel.add(button3,BorderLayout.SOUTH);JButton button4 = new JButton("东");panel.add(button4,BorderLayout.EAST);frame.setVisible(true);//setVgap方法——设置垂直间距 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JPanel panel = new JPanel();BorderLayout borderLayout = new BorderLayout();panel.setLayout(borderLayout);borderLayout.setVgap(15);frame.getContentPane().add(panel,BorderLayout.CENTER);JButton button = new JButton("中");panel.add(button,BorderLayout.CENTER);JButton button1 = new JButton("北");panel.add(button1,BorderLayout.NORTH);JButton button2 = new JButton("西");panel.add(button2,BorderLayout.WEST);JButton button3 = new JButton("南");panel.add(button3,BorderLayout.SOUTH);JButton button4 = new JButton("东");panel.add(button4,BorderLayout.EAST);frame.setVisible(true);
//javaawtGridLayout网格布局 //GridLayout构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);GridLayout gridLayout = new GridLayout(2, 3);frame.getContentPane().setLayout(gridLayout);JButton button = new JButton("1");frame.getContentPane().add(button);JButton button1 = new JButton("2");frame.getContentPane().add(button1);JButton button2 = new JButton("3");frame.getContentPane().add(button2);JButton button3 = new JButton("4");frame.getContentPane().add(button3);JButton button4 = new JButton("5");frame.getContentPane().add(button4);frame.setVisible(true);//setColumns方法——设置网格布局管理器的网格列数 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);GridLayout gridLayout = new GridLayout(0, 4);gridLayout.setColumns(2);frame.getContentPane().setLayout(gridLayout);JButton button = new JButton("1");frame.getContentPane().add(button);JButton button1 = new JButton("2");frame.getContentPane().add(button1);JButton button2 = new JButton("3");frame.getContentPane().add(button2);JButton button3 = new JButton("4");frame.getContentPane().add(button3);JButton button4 = new JButton("5");frame.getContentPane().add(button4);frame.setVisible(true);//setHgap方法——设置水平间距 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);GridLayout gridLayout = new GridLayout(0, 4);gridLayout.setHgap(10);frame.getContentPane().setLayout(gridLayout);JButton button = new JButton("1");frame.getContentPane().add(button);JButton button1 = new JButton("2");frame.getContentPane().add(button1);JButton button2 = new JButton("3");frame.getContentPane().add(button2);JButton button3 = new JButton("4");frame.getContentPane().add(button3);JButton button4 = new JButton("5");frame.getContentPane().add(button4);frame.setVisible(true);//setRows方法——设置网格布局管理器的网格行数 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);GridLayout gridLayout = new GridLayout(0, 4);gridLayout.setRows(2);frame.getContentPane().setLayout(gridLayout);JButton button = new JButton("1");frame.getContentPane().add(button);JButton button1 = new JButton("2");frame.getContentPane().add(button1);JButton button2 = new JButton("3");frame.getContentPane().add(button2);JButton button3 = new JButton("4");frame.getContentPane().add(button3);JButton button4 = new JButton("5");frame.getContentPane().add(button4);frame.setVisible(true);//setVgap方法——设置垂直间距 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);GridLayout gridLayout = new GridLayout(0, 4);gridLayout.setVgap(20);frame.getContentPane().setLayout(gridLayout);JButton button = new JButton("1");frame.getContentPane().add(button);JButton button1 = new JButton("2");frame.getContentPane().add(button1);JButton button2 = new JButton("3");frame.getContentPane().add(button2);JButton button3 = new JButton("4");frame.getContentPane().add(button3);JButton button4 = new JButton("5");frame.getContentPane().add(button4);frame.setVisible(true);
//javaawtCardLayout卡片布局 //CardLayout构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);CardLayout cardLayout = new CardLayout(10,15);frame.getContentPane().setLayout(cardLayout);frame.getContentPane().add("one",new JButton("第一个"));frame.getContentPane().add("two",new JButton("第二个"));frame.setVisible(true);//first方法——显示容器中的第一张卡片 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final CardLayout cardLayout = new CardLayout(10,15);frame.getContentPane().setLayout(cardLayout);final JPanel cardPanel = new JPanel();JButton button = new JButton();button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {cardLayout.first(cardPanel);}});cardPanel.add(button);button.setText("第一张");frame.setVisible(true);//last方法——显示容器中的最后一张卡片 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final CardLayout cardLayout = new CardLayout(10,15);frame.getContentPane().setLayout(cardLayout);final JPanel cardPanel = new JPanel();JButton button = new JButton();button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {cardLayout.last(cardPanel);}});cardPanel.add(button);button.setText("第一张");frame.setVisible(true);//next方法——显示容器中当前卡片的下一张卡片 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final CardLayout cardLayout = new CardLayout(10,15);frame.getContentPane().setLayout(cardLayout);final JPanel cardPanel = new JPanel();JButton button = new JButton();button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {cardLayout.next(cardPanel);}});cardPanel.add(button);button.setText("第一张");frame.setVisible(true);//previous方法——显示容器中当前卡片的前一张卡片 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final CardLayout cardLayout = new CardLayout(10,15);frame.getContentPane().setLayout(cardLayout);final JPanel cardPanel = new JPanel();JButton button = new JButton();button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {cardLayout.previous(cardPanel);}});cardPanel.add(button);button.setText("第一张");frame.setVisible(true);//show方法——显示容器中用户指定的卡片 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final CardLayout cardLayout = new CardLayout(10,15);frame.getContentPane().setLayout(cardLayout);final JPanel cardPanel = new JPanel();JButton button = new JButton();button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {cardLayout.show(cardPanel,"test");}});cardPanel.add(button);button.setText("第一张");frame.setVisible(true);
<!--文本输入控件 ->
//javaxswingJLabel类 //JLabel构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JLabel label = new JLabel("aa");frame.getContentPane().add(label);frame.setVisible(true);//setFont方法——设置标签上文本的字体 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JLabel label = new JLabel("aa");label.setFont(new Font("微软雅黑",Font.BOLD,20));frame.getContentPane().add(label);frame.setVisible(true);//setHorizontalTextPosition方法——设置标签中文本相对于图标的水平位置 ImageIcon icon = new ImageIcon("src/1.jpg");JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JLabel label = new JLabel("aa");label.setIcon(icon);label.setHorizontalTextPosition(SwingConstants.RIGHT);frame.getContentPane().add(label);frame.setVisible(true);//setText方法——设置标签上显示的文本信息 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JLabel label = new JLabel();label.setText("Left");frame.getContentPane().add(label);frame.setVisible(true);//setVerticalTextPosition方法——设置文本相对于图标的垂直位置 ImageIcon icon = new ImageIcon("src/1.jpg");JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JLabel label = new JLabel();label.setIcon(icon);label.setText("aa");label.setVerticalTextPosition(SwingConstants.BOTTOM);label.setHorizontalTextPosition(SwingConstants.CENTER);frame.getContentPane().add(label);frame.setVisible(true);
//javaxswingJTextField类 //JTextField构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JTextField textField = new JTextField("科技");frame.getContentPane().add(textField);frame.setVisible(true);//addActionListener方法——响应用户在文本域中按Enter键时的操作 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTextField textField = new JTextField();textField.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {textField.getText();}});frame.getContentPane().add(textField);frame.setVisible(true);//addFocusListener方法——响应文本域焦点事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTextField textField = new JTextField();textField.addFocusListener(new FocusAdapter() {@Overridepublic void focusGained(FocusEvent e) {textField.setText("文本焦点");}});frame.getContentPane().add(textField);frame.setVisible(true);//getText方法——获得文本域中输入的文本 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTextField textField = new JTextField();textField.getText();frame.getContentPane().add(textField);frame.setVisible(true);//setColumns方法——设置文本框的列数 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTextField textField = new JTextField();textField.setColumns(10);frame.getContentPane().add(textField);frame.setVisible(true);//setFont方法——设置文本域中的字体 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JTextField textField = new JTextField();textField.setFont(new Font("微软雅黑",Font.BOLD,15));frame.getContentPane().add(textField);frame.setVisible(true);
//javaxswingJPasswordField类 //JPasswordField构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JPasswordField passwordField = new JPasswordField(10);frame.getContentPane().add(passwordField);frame.setVisible(true);//addActionListener方法——响应在密码域中按Enter键时的操作 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JPasswordField passwordField = new JPasswordField(10);passwordField.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {passwordField.setText(new String(passwordField.getPassword()));}});frame.getContentPane().add(passwordField);frame.setVisible(true);//getPassword方法——获得输入的密码 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JPasswordField passwordField = new JPasswordField(10);passwordField.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {passwordField.getPassword();}});frame.getContentPane().add(passwordField);frame.setVisible(true);//setEchoChar方法——修改密码域的回显字符 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final JPasswordField passwordField = new JPasswordField(10);passwordField.setEchoChar('&');frame.getContentPane().add(passwordField);frame.setVisible(true);
//javaxswingJTextArea类 //JTextArea构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JTextArea textArea = new JTextArea(5,10);frame.getContentPane().add(textArea);frame.setVisible(true);//addCaretListener方法——监听光标位置在文本区中的变化事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final Label label = new Label();final JTextArea textArea = new JTextArea(5,10);textArea.addCaretListener(new CaretListener() {@Overridepublic void caretUpdate(CaretEvent e) {label.setText(""+e.getDot());}});frame.getContentPane().add(textArea);frame.setVisible(true);//append方法——在文本区中文本末尾增加字符串 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final TextArea textArea = new TextArea();JButton button = new JButton("单击按钮");button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {textArea.append("单击一次按钮");}});frame.getContentPane().add(textArea);frame.setVisible(true);//getText方法——获得文本区中输入的内容 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final TextArea textArea = new TextArea();JButton button = new JButton();button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {textArea.getText();}});frame.getContentPane().add(textArea);frame.setVisible(true);//setFont方法——设置文本区字体 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);final TextArea textArea = new TextArea();textArea.setFont(new Font("微软雅黑",Font.BOLD,15));frame.getContentPane().add(textArea);frame.setVisible(true);//setLineWrap方法——设置是否自动换行 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JTextArea textArea = new JTextArea();textArea.setLineWrap(true);frame.getContentPane().add(textArea);frame.setVisible(true);
<!--选择控件 ->
//javaxswingJButton类 //JButton构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);JButton button = new JButton("这是一个按钮");frame.getContentPane().add(button);frame.setVisible(true);//addActionListener方法——向按钮控件增加动作事件监听器 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JButton button = new JButton("这是一个按钮");final Label label = new Label();button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {label.setText("用户单击");}});frame.getContentPane().add(label);frame.getContentPane().add(button);frame.setVisible(true);//setActionCommand方法——设置按钮的动作命令 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JButton button = new JButton("单击按钮");final JLabel label = new JLabel();button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {label.setText("单击");}});button.setActionCommand("alter");frame.getContentPane().add(label);frame.getContentPane().add(button);frame.setVisible(true);//setEnabled方法——设置按钮是否可用 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JButton button = new JButton("按钮");button.setEnabled(false);frame.getContentPane().add(button);frame.setVisible(true);//setHorizontalTextPosition方法——设置文本相对于图标的水平位置 ImageIcon icon = new ImageIcon("src/1.jpg");JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JButton button = new JButton("按钮",icon);button.setHorizontalTextPosition(SwingConstants.LEFT);frame.getContentPane().add(button);frame.setVisible(true);//setMnemonic方法——为按钮添加助记符 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JButton button = new JButton("按钮");button.setMnemonic(KeyEvent.VK_0);frame.getContentPane().add(button);frame.setVisible(true);//setVerticalTextPosition方法——设置文本相对于图标的垂直位置 ImageIcon icon = new ImageIcon("src/1.jpg");JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JButton button = new JButton("按钮",icon);button.setVerticalTextPosition(SwingConstants.TOP);frame.getContentPane().add(button);frame.setVisible(true);//isDefaultButton方法——判断是否为默认按钮 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JButton button = new JButton("按钮");frame.getRootPane().setDefaultButton(button);System.out.println(button.isDefaultButton());frame.getContentPane().add(button);frame.setVisible(true);
//javaxswingJCheckBox类 //JCheckBox构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JCheckBox checkBox = new JCheckBox("复选框");frame.getContentPane().add(checkBox);frame.setVisible(true);//addActionListener方法——向复选框控件增加动作事件监听器 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final Label label = new Label();JCheckBox checkBox = new JCheckBox("复选框");checkBox.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {label.setText("这是一个复选框");}});frame.getContentPane().add(label);frame.getContentPane().add(checkBox);frame.setVisible(true);//addItemListener方法——为复选框增加选择状态变化事件监听 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final Label label = new Label();JCheckBox checkBox = new JCheckBox("复选框");checkBox.addItemListener(new ItemListener() {@Overridepublic void itemStateChanged(ItemEvent e) {label.setText("复选框已选择");}});frame.getContentPane().add(label);frame.getContentPane().add(checkBox);frame.setVisible(true);//isSelected方法——判断复选框是否被用户选择 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final Label label = new Label();JCheckBox checkBox = new JCheckBox("复选框");label.setText(""+checkBox.isSelected());frame.getContentPane().add(label);frame.getContentPane().add(checkBox);frame.setVisible(true);//setSelected方法——将复选框设置成选择状态 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JCheckBox checkBox = new JCheckBox("复选框");checkBox.setSelected(true);frame.getContentPane().add(checkBox);frame.setVisible(true);
//javaxswingJRadioButton类 //JRadioButton构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JRadioButton radioButton = new JRadioButton("单选");frame.getContentPane().add(radioButton);frame.setVisible(true);//addActionListener方法——向单选按钮控件增加动作事件监听器 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final JLabel label = new JLabel();JRadioButton radioButton = new JRadioButton("单选");radioButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {label.setText("选择");}});frame.getContentPane().add(label);frame.getContentPane().add(radioButton);frame.setVisible(true);//isSelected方法——判断单选按钮是否被用户选择 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final JLabel label = new JLabel();JRadioButton radioButton = new JRadioButton("单选");label.setText(radioButton.isSelected()+"");frame.getContentPane().add(label);frame.getContentPane().add(radioButton);frame.setVisible(true);//setSelected方法——将单选按钮设置成选择状态 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final JLabel label = new JLabel();JRadioButton radioButton = new JRadioButton("单选");radioButton.setSelected(true);frame.getContentPane().add(label);frame.getContentPane().add(radioButton);frame.setVisible(true);
//javaxswingButtonGroup类 //add方法——将按钮添加到按钮组中 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);ButtonGroup group = new ButtonGroup();JRadioButton radioButton1 = new JRadioButton("按钮1");JRadioButton radioButton2 = new JRadioButton("按钮2");group.add(radioButton1);group.add(radioButton2);frame.getContentPane().add(radioButton1);frame.getContentPane().add(radioButton2);frame.setVisible(true);//remove方法——删除已经添加到按钮组中的按钮 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);ButtonGroup group = new ButtonGroup();JRadioButton radioButton1 = new JRadioButton("按钮1");JRadioButton radioButton2 = new JRadioButton("按钮2");JRadioButton radioButton3 = new JRadioButton("按钮3");group.add(radioButton1);group.add(radioButton2);group.add(radioButton3);group.remove(radioButton3);frame.getContentPane().add(radioButton1);frame.getContentPane().add(radioButton2);frame.getContentPane().add(radioButton3);frame.setVisible(true);
//javaxswingBorderFactory类 //createBevelBorder方法——创建指定类型的斜面边框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JPanel panel = new JPanel();panel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));frame.getContentPane().add(panel);frame.setVisible(true);//createCompoundBorder方法——指定复合边框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JPanel panel = new JPanel();Border outside = BorderFactory.createBevelBorder(BevelBorder.LOWERED);Border inside = BorderFactory.createBevelBorder(BevelBorder.RAISED);panel.setBorder(new CompoundBorder(outside,inside));frame.getContentPane().add(panel);frame.setVisible(true);//createEmptyBorder方法——创建一个空白的边框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JPanel panel = new JPanel();panel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));frame.getContentPane().add(panel,BorderLayout.CENTER);frame.setVisible(true);//createEtchedBorder方法——创建浮雕效果的边框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JPanel panel = new JPanel();panel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));frame.getContentPane().add(panel);frame.setVisible(true);//createLineBorder方法——创建直线边框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JPanel panel = new JPanel();panel.setBorder(BorderFactory.createLineBorder(Color.RED,5));frame.getContentPane().add(panel);frame.setVisible(true);//createMatteBorder方法——创建纯色或者指定图片的边框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JPanel panel = new JPanel();panel.setBorder(BorderFactory.createMatteBorder(1, 2, 3, 4, Color.RED));frame.getContentPane().add(panel);frame.setVisible(true);//createTitledBorder方法——创建带有标题的边框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JPanel panel = new JPanel();panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"标题边框"));frame.getContentPane().add(panel);frame.setVisible(true);
//javaxswingJComboBox类 //JComboBox构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultComboBoxModel model = new DefaultComboBoxModel();model.addElement("JAVA");model.addElement("PHP");JComboBox comboBox = new JComboBox(model);frame.getContentPane().add(comboBox);frame.setVisible(true);//addActionListener方法——监听组合框的选择事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultComboBoxModel model = new DefaultComboBoxModel();model.addElement("JAVA");model.addElement("PHP");JComboBox comboBox = new JComboBox(model);comboBox.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(null, "选择");return;}});frame.getContentPane().add(comboBox);frame.setVisible(true);//addItem方法——给组合框增加元素 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultComboBoxModel model = new DefaultComboBoxModel();model.addElement("JAVA");model.addElement("PHP");JComboBox comboBox = new JComboBox(model);comboBox.addItem("JAVA1");frame.getContentPane().add(comboBox);frame.setVisible(true);//getSelectedItem方法——获得用户选择的元素 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultComboBoxModel model = new DefaultComboBoxModel();model.addElement("JAVA");model.addElement("PHP");final JComboBox comboBox = new JComboBox(model);comboBox.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(null, ""+comboBox.getSelectedItem());return;}});frame.getContentPane().add(comboBox);frame.setVisible(true);//setEditable方法——设置组合框中的文本框是否处于编辑状态 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultComboBoxModel model = new DefaultComboBoxModel();model.addElement("JAVA");model.addElement("PHP");final JComboBox comboBox = new JComboBox(model);comboBox.setEditable(true);frame.getContentPane().add(comboBox);frame.setVisible(true);//setMaximumRowCount方法——设置组合框中可以显示的列表项个数 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultComboBoxModel model = new DefaultComboBoxModel();model.addElement("JAVA");model.addElement("PHP");final JComboBox comboBox = new JComboBox(model);comboBox.setMaximumRowCount(1);frame.getContentPane().add(comboBox);frame.setVisible(true);//setSelectedIndex方法——设置当前组合框中选择的元素 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultComboBoxModel model = new DefaultComboBoxModel();model.addElement("JAVA");model.addElement("PHP");final JComboBox comboBox = new JComboBox(model);comboBox.setSelectedIndex(1);frame.getContentPane().add(comboBox);frame.setVisible(true);
//javaxswingJSlider类 //JSlider构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JSlider slider = new JSlider(JSlider.HORIZONTAL);frame.getContentPane().add(slider);frame.setVisible(true);//addChangeListener方法——监听滑块滑动事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final Label label = new Label("未滑动");JSlider slider = new JSlider(JSlider.HORIZONTAL);slider.addChangeListener(new ChangeListener() {@Overridepublic void stateChanged(ChangeEvent e) {label.setText("已滑动");}});frame.getContentPane().add(label);frame.getContentPane().add(slider);frame.setVisible(true);//getValue方法——获得滑块的当前值 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final Label label = new Label("未滑动");final JSlider slider = new JSlider(JSlider.HORIZONTAL);slider.addChangeListener(new ChangeListener() {@Overridepublic void stateChanged(ChangeEvent e) {label.setText(""+slider.getValue());}});frame.getContentPane().add(label);frame.getContentPane().add(slider);frame.setVisible(true);//setFont方法——设置滑块上显示的标签的字体 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final Label label = new Label("未滑动");final JSlider slider = new JSlider(0,100,50);slider.addChangeListener(new ChangeListener() {@Overridepublic void stateChanged(ChangeEvent e) {label.setText(""+slider.getValue());}});slider.setMajorTickSpacing(20);slider.setMinorTickSpacing(1);slider.setPaintTicks(true);slider.setPaintLabels(true);slider.setFont(new Font("微软雅黑",Font.BOLD,15));frame.getContentPane().add(label);frame.getContentPane().add(slider);frame.setVisible(true);//setLabelTable方法——给滑块设置标签 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final JSlider slider = new JSlider(0,100,50);Hashtable<Integer, Component> labels = new Hashtable<Integer, Component>();labels.put(0, new JLabel("0"));labels.put(0, new JLabel("50"));labels.put(0, new JLabel("100"));slider.setLabelTable(labels);slider.setPaintLabels(true);frame.getContentPane().add(slider);frame.setVisible(true);//setMajorTickSpacing方法——设置主刻度间的距离 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final JSlider slider = new JSlider(0,100,50);slider.setMajorTickSpacing(10);slider.setPaintTicks(true);frame.getContentPane().add(slider);frame.setVisible(true);//setMaximum方法——设置滑块的最大值 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final JSlider slider = new JSlider(0,100,50);slider.setMaximum(100);frame.getContentPane().add(slider);frame.setVisible(true);//setMinimum方法——设置滑块的最小值 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final JSlider slider = new JSlider(0,100,50);slider.setMinimum(50);frame.getContentPane().add(slider);frame.setVisible(true);//setMinorTickSpacing方法——设置副刻度间的距离 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JSlider slider = new JSlider(0,50,25);slider.setMinorTickSpacing(1);slider.setPaintTicks(true);frame.getContentPane().add(slider);frame.setVisible(true);
//javaxswingJSpinner类 //JSpinner构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] months = {"周一","周二","周三","周四","周五"};SpinnerListModel model = new SpinnerListModel(months);JSpinner spinner = new JSpinner(model);frame.getContentPane().add(spinner);frame.setVisible(true);//addChangeListener方法——监听微调按钮变化事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] months = {"周一","周二","周三","周四","周五"};SpinnerListModel model = new SpinnerListModel(months);JSpinner spinner = new JSpinner(model);spinner.addChangeListener(new ChangeListener() {@Overridepublic void stateChanged(ChangeEvent e) {JOptionPane.showMessageDialog(null, "变化");return;}});frame.getContentPane().add(spinner);frame.setVisible(true);//getValue方法——获得微调按钮当前的值 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] months = {"周一","周二","周三","周四","周五"};SpinnerListModel model = new SpinnerListModel(months);final JSpinner spinner = new JSpinner(model);spinner.addChangeListener(new ChangeListener() {@Overridepublic void stateChanged(ChangeEvent e) {JOptionPane.showMessageDialog(null, spinner.getValue()+"");return;}});frame.getContentPane().add(spinner);frame.setVisible(true);//setEditor方法——设置编辑微调按钮值的控件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final JSpinner spinner = new JSpinner(new SpinnerDateModel());spinner.setEditor(new JSpinner.DateEditor(spinner,"yyyy-MM-dd"));frame.getContentPane().add(spinner);frame.setVisible(true);
<!--菜单和工具栏控件 ->
//javaxswingJMenuBar类 //JMenuBar构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");menuBar.add(menu1);frame.setVisible(true);//add方法——向菜单条中增加菜单 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");menuBar.add(menu1);frame.setVisible(true);//setLayout方法——设置控件的布局 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.Y_AXIS));frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");menuBar.add(menu1);frame.setVisible(true);
//javaxswingJMenu类 //JMenu构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");menuBar.add(menu1);frame.setVisible(true);//add方法——给菜单增加菜单项 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");menuBar.add(menu1);frame.setVisible(true);//addSeparator方法——给菜单项增加分隔符 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");JMenu menu2 = new JMenu("菜单2");menuBar.add(menu1);menuBar.add(menu2);menu2.addSeparator();frame.setVisible(true);//setFont方法——设置菜单字体 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");JMenu menu2 = new JMenu("菜单2");menu2.setFont(new Font("微软雅黑",Font.BOLD,15));menuBar.add(menu1);menuBar.add(menu2);frame.setVisible(true);//setMnemonic方法——给菜单设置助记符 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");JMenu menu2 = new JMenu("菜单2");menu1.setMnemonic(KeyEvent.VK_A);menuBar.add(menu1);menuBar.add(menu2);frame.setVisible(true);//setPopupMenuVisible方法——设置弹出菜单是否可见 //设置弹出菜单是否可见
//javaxswingJMenuItem类 //JMenuItem构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");JMenuItem menuItem1 = new JMenuItem("打开");menu1.add(menuItem1);menuBar.add(menu1);frame.setVisible(true);//addActionListener方法——处理菜单项动作事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");JMenuItem menuItem1 = new JMenuItem("打开");menuItem1.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {System.out.println("+");return;}});menu1.add(menuItem1);menuBar.add(menu1);frame.setVisible(true);//setAccelerator方法——给菜单项设置快捷键 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");JMenuItem menuItem1 = new JMenuItem("打开");menuItem1.setAccelerator(KeyStroke.getKeyStroke("ctrl 2"));menu1.add(menuItem1);menuBar.add(menu1);frame.setVisible(true);//setEnabled方法——启用或禁用菜单项 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");JMenuItem menuItem1 = new JMenuItem("打开");menuItem1.setEnabled(false);menu1.add(menuItem1);menuBar.add(menu1);frame.setVisible(true);//setFont方法——为菜单项设置字体 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenuBar menuBar = new JMenuBar();frame.setJMenuBar(menuBar);JMenu menu1 = new JMenu("菜单");JMenuItem menuItem1 = new JMenuItem("打开");menuItem1.setFont(new Font("微软雅黑",Font.BOLD,15));menu1.add(menuItem1);menuBar.add(menu1);frame.setVisible(true);
//javaxswingJPopupMenu类 //JPopupMenu构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());JPanel jPanel = new JPanel();frame.setBounds(400,320,400,240);JPopupMenu popup = new JPopupMenu();jPanel.setComponentPopupMenu(popup);frame.getContentPane().add(jPanel);frame.setVisible(true);//add方法——给弹出菜单增加菜单项 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JPanel panel = new JPanel();JPopupMenu popup = new JPopupMenu();popup.add(new JMenuItem("男生",new ImageIcon("src/1.jpg")));panel.setComponentPopupMenu(popup);frame.getContentPane().add(panel);frame.setVisible(true);//addSeparator方法——给弹出菜单的菜单项之间增加分隔符 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JPanel panel = new JPanel();JPopupMenu popup = new JPopupMenu();popup.add("男");popup.add("女");popup.addSeparator();panel.setComponentPopupMenu(popup);frame.getContentPane().add(panel);frame.setVisible(true);//setPopupSize方法——设置弹出菜单的大小 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JPanel panel = new JPanel();JPopupMenu popup = new JPopupMenu();popup.add("男");popup.add("女");popup.addSeparator();popup.setPopupSize(100,100);frame.getContentPane().add(panel);frame.setVisible(true);
//javaxswingJCheckBoxMenuItem类 //JCheckBoxMenuItem构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenu menu = new JMenu();JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("菜单");frame.getContentPane().add(menu);frame.setVisible(true);//addActionListener方法——监听复选框菜单项的动作事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenu menu = new JMenu();JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("菜单");jCheckBoxMenuItem.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {System.out.println("+");}});frame.getContentPane().add(menu);frame.setVisible(true);//setFont方法——给复选框菜单项设置字体 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenu menu = new JMenu();JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("菜单");jCheckBoxMenuItem.setFont(new Font("微软雅黑", Font.BOLD, 15));frame.getContentPane().add(menu);frame.setVisible(true);
//javaxswingJRadioButtonMenuItem类 //JRadioButtonMenuItem构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenu menu = new JMenu();JRadioButton jRadioButton = new JRadioButton("菜单");menu.add(jRadioButton);frame.getContentPane().add(menu);frame.setVisible(true);//addActionListener方法——监听单选按钮菜单项的动作事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenu menu = new JMenu();JRadioButton jRadioButton = new JRadioButton("菜单");jRadioButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {System.out.println("+");}});frame.getContentPane().add(menu);frame.setVisible(true);//setFont方法——给单选按钮菜单项设置字体 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JMenu menu = new JMenu();JRadioButton jRadioButton = new JRadioButton("菜单");jRadioButton.setFont(new Font("微软雅黑",Font.BOLD,15));frame.getContentPane().add(menu);frame.setVisible(true);
//javaxswingJToolBar类 //JToolBar构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JToolBar toolBar = new JToolBar();JButton button = new JButton("按钮");toolBar.add(button);frame.getContentPane().add(toolBar);frame.setVisible(true);//add方法——为工具栏添加控件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JToolBar toolBar = new JToolBar();JButton button = new JButton("按钮");toolBar.add(button);frame.getContentPane().add(toolBar);frame.setVisible(true);//addSeparator方法——给工具栏增加分隔符 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JToolBar toolBar = new JToolBar();JButton button = new JButton("按钮");toolBar.add(button);JButton button1 = new JButton("按钮");toolBar.add(button1);toolBar.addSeparator(new Dimension(50,100));frame.getContentPane().add(toolBar);frame.setVisible(true);//setFloatable方法——固定工具栏 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JToolBar toolBar = new JToolBar();toolBar.setFloatable(false);JButton button = new JButton("按钮");toolBar.add(button);JButton button1 = new JButton("按钮");toolBar.add(button1);frame.getContentPane().add(toolBar);frame.setVisible(true);
<!--对话框控件 ->
//javaxswingJOptionPane类 //showConfirmDialog方法——创建一个确认对话框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JOptionPane.showConfirmDialog(frame, "确定退出");frame.setVisible(true);//showInputDialog方法——创建接收用户输入信息的对话框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JOptionPane.showInputDialog(frame,"输入名字");frame.setVisible(true);//showMessageDialog方法——创建消息对话框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JOptionPane.showMessageDialog(frame, "欢迎使用");frame.setVisible(true);//showOptionDialog方法——根据用户指定的选项创建对话框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JOptionPane.showOptionDialog(frame, "对话框", "对话框1", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, null, "java");frame.setVisible(true);
//javaxswingJFileChooser类 //JFileChooser构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JFileChooser fileChooser = new JFileChooser();fileChooser.showOpenDialog(frame);frame.setVisible(true);//getSelectedFile方法——获得用户选择的文件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JFileChooser fileChooser = new JFileChooser();fileChooser.showOpenDialog(frame);File selectedFile = fileChooser.getSelectedFile();System.out.println(selectedFile.getAbsolutePath());frame.setVisible(true);//getSelectedFiles方法——获得选择的一组文件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JFileChooser fileChooser = new JFileChooser();fileChooser.showOpenDialog(frame);File[] selectedFile = fileChooser.getSelectedFiles();System.out.println(selectedFile.length);frame.setVisible(true);//setFileFilter方法——设置文件过滤器 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JFileChooser fileChooser = new JFileChooser();fileChooser.showOpenDialog(frame);fileChooser.setFileFilter(new FileFilter() {@Overridepublic String getDescription() {return null;}@Overridepublic boolean accept(File f) {return false;}});frame.setVisible(true);//setFileHidingEnabled方法——设置是否显示隐藏文件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JFileChooser fileChooser = new JFileChooser();fileChooser.showOpenDialog(frame);fileChooser.setFileHidingEnabled(true);frame.setVisible(true);//setFileSelectionMode方法——设置选择模式 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JFileChooser fileChooser = new JFileChooser();fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);fileChooser.showOpenDialog(frame);frame.setVisible(true);//setMultiSelectionEnabled方法——设置是否能够同时选择多个文件或文件夹 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JFileChooser fileChooser = new JFileChooser();fileChooser.setMultiSelectionEnabled(true);fileChooser.showOpenDialog(frame);frame.setVisible(true);//showDialog方法——打开对话框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JFileChooser fileChooser = new JFileChooser();fileChooser.showDialog(frame,"自定义按钮");frame.setVisible(true);//showOpenDialog方法——弹出打开对话框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JFileChooser fileChooser = new JFileChooser();fileChooser.showOpenDialog(frame);frame.setVisible(true);//showSaveDialog方法——弹出保存对话框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JFileChooser fileChooser = new JFileChooser();fileChooser.showSaveDialog(frame);frame.setVisible(true);
//javaxswingJColorChooser类 //JColorChooser构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JColorChooser chooser = new JColorChooser();frame.getContentPane().add(chooser);frame.setVisible(true);//getColor方法——获得在颜色选择器中选择的颜色 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);final JColorChooser chooser = new JColorChooser();frame.getContentPane().add(chooser);chooser.getSelectionModel().addChangeListener(new ChangeListener() {@Overridepublic void stateChanged(ChangeEvent e) {System.out.println(chooser.getColor());}});frame.setVisible(true);//showDialog方法——创建颜色选择对话框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);Color showDialog = JColorChooser.showDialog(frame, "", null);frame.getContentPane().setBackground(showDialog);frame.setVisible(true);
<!--列表控件 ->
//javaxswingJList类 //JList构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultListModel model = new DefaultListModel();model.addElement("JAVA");model.addElement("PHP");model.addElement("ASP");JList list = new JList(model);frame.getContentPane().add(list);frame.setVisible(true);//addListSelectionListener方法——监听列表项选择事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] items = {"Java","Perl","C++"};JList list = new JList(items);list.addListSelectionListener(new ListSelectionListener() {@Overridepublic void valueChanged(ListSelectionEvent e) {System.out.println("选中");}});frame.getContentPane().add(list);frame.setVisible(true);//addMouseListener方法——监听鼠标事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] items = {"Java","Perl","C++"};JList list = new JList(items);list.addMouseListener(new MouseAdapter() {@Overridepublic void mouseClicked(MouseEvent e) {System.out.println("选中");}});frame.getContentPane().add(list);frame.setVisible(true);//getSelectedIndex方法——获得当前选择元素的索引值 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] items = {"Java","Perl","C++"};final JList list = new JList(items);list.addMouseListener(new MouseAdapter() {@Overridepublic void mouseClicked(MouseEvent e) {System.out.println(list.getSelectedIndex());}});frame.getContentPane().add(list);frame.setVisible(true);//getSelectedValue方法——获得当前选择的元素 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] items = {"Java","Perl","C++"};final JList list = new JList(items);list.addMouseListener(new MouseAdapter() {@Overridepublic void mouseClicked(MouseEvent e) {System.out.println(list.getSelectedValue());}});frame.getContentPane().add(list);frame.setVisible(true);//setCellRenderer方法——为列表设置渲染器 //列表设置渲染器//setLayoutOrientation方法——设置列表项的布局方式 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] items = {"Java","Perl","C++"};final JList list = new JList(items);list.setLayoutOrientation(JList.HORIZONTAL_WRAP);frame.getContentPane().add(list);frame.setVisible(true);//setListData方法——为列表设置列表项 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] items = {"Java","Perl","C++"};final JList list = new JList();list.setListData(items);frame.getContentPane().add(list);frame.setVisible(true);//setModel方法——为列表设置列表模型 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultListModel model = new DefaultListModel();model.addElement("JAVA");model.addElement("PHP");model.addElement("ASP");JList list = new JList(model);frame.getContentPane().add(list);frame.setVisible(true);//setSelectedIndex方法——设置当前选中的列表项 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] items = {"Java","Perl","C++"};final JList list = new JList();list.setListData(items);list.setSelectedIndex(1);frame.getContentPane().add(list);frame.setVisible(true);//setSelectionBackground方法——设置列表项选中时的背景色 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] items = {"Java","Perl","C++"};final JList list = new JList();list.setListData(items);list.setBackground(Color.BLUE);frame.getContentPane().add(list);frame.setVisible(true);//setSelectionForeground方法——设置列表项选中时的前景色 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] items = {"Java","Perl","C++"};final JList list = new JList();list.setListData(items);list.setSelectionForeground(Color.BLUE);frame.getContentPane().add(list);frame.setVisible(true);//setSelectionMode方法——设置列表项的选择模式 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] items = {"Java","Perl","C++"};final JList list = new JList();list.setListData(items);list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);frame.getContentPane().add(list);frame.setVisible(true);//setVisibleRowCount方法——设置visibleRowCount属性 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] items = {"Java","Perl","C++"};final JList list = new JList();list.setListData(items);list.setVisibleRowCount(2);frame.getContentPane().add(list);frame.setVisible(true);
//javaxswingDefaultListModel类 //add方法——在列表模型中的指定位置增加元素 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultListModel model = new DefaultListModel();model.add(0, "JAVA");model.add(0, "PHP");model.add(0, "ASP");model.add(0, "JSP");JList list = new JList();list.setModel(model);frame.getContentPane().add(list);frame.setVisible(true);//addElement方法——向列表模型的末尾增加新元素 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultListModel model = new DefaultListModel();model.addElement("JAVA");model.addElement("PHP");model.addElement("ASP");JList list = new JList();list.setModel(model);frame.getContentPane().add(list);frame.setVisible(true);//clear方法——清空列表模型中的全部元素 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultListModel model = new DefaultListModel();model.addElement("JAVA");model.addElement("PHP");model.addElement("ASP");model.clear();JList list = new JList();list.setModel(model);frame.getContentPane().add(list);frame.setVisible(true);//contains方法——判断列表模型中是否包含指定的元素 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultListModel model = new DefaultListModel();model.addElement("JAVA");model.addElement("PHP");model.addElement("ASP");JList list = new JList();list.setModel(model);System.out.println(model.contains("JAVA"));frame.getContentPane().add(list);frame.setVisible(true);//elementAt方法——获得指定索引值的元素 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultListModel model = new DefaultListModel();model.addElement("JAVA");model.addElement("PHP");model.addElement("ASP");JList list = new JList();list.setModel(model);System.out.println(model.elementAt(2));frame.getContentPane().add(list);frame.setVisible(true);//elements方法——获得模型中全部元素的枚举 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultListModel model = new DefaultListModel();model.addElement("JAVA");model.addElement("PHP");model.addElement("ASP");JList list = new JList();list.setModel(model);Enumeration<?> elements = model.elements();while (elements.hasMoreElements()) {System.out.println(elements.nextElement());}frame.getContentPane().add(list);frame.setVisible(true);//getSize方法——获得列表模型中元素的个数 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultListModel model = new DefaultListModel();model.addElement("JAVA");model.addElement("PHP");model.addElement("ASP");JList list = new JList();list.setModel(model);System.out.println(model.getSize());frame.getContentPane().add(list);frame.setVisible(true);//remove方法——删除列表模型中指定索引的元素 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultListModel model = new DefaultListModel();model.addElement("JAVA");model.addElement("PHP");model.addElement("ASP");JList list = new JList();list.setModel(model);System.out.println(model.remove(2));frame.getContentPane().add(list);frame.setVisible(true);//removeRange方法——从列表模型中删除指定区域的元素 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultListModel model = new DefaultListModel();model.addElement("JAVA");model.addElement("PHP");model.addElement("ASP");JList list = new JList();list.setModel(model);model.removeRange(0,1);frame.getContentPane().add(list);frame.setVisible(true);
<!--表格控件 ->
//javaxswingJTable类 //JTable构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] columnNames = {"学号","姓名"};String[][] rowData = {{"20101","小王"},{"20102","大王"}};JTable table = new JTable(rowData,columnNames);frame.getContentPane().add(table);frame.setVisible(true);//addColumn方法——向表格中增加一列 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);TableColumn column = new TableColumn(0,100);table.addColumn(column);frame.getContentPane().add(table);frame.setVisible(true);//addRowSelectionInterval方法——增加选中的行 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);table.addRowSelectionInterval(0, 1);frame.getContentPane().add(table);frame.setVisible(true);//getColumn方法——获得表格中的指定列 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);System.out.println(table.getColumn("学号"));frame.getContentPane().add(table);frame.setVisible(true);//getColumnClass方法——获得表格中指定列的类型 //用于获得表格中指定列的类型//getColumnCount方法——获得列模型中的列数 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);System.out.println(table.getColumnCount());frame.getContentPane().add(table);frame.setVisible(true);//getColumnName方法——获得指定列的名称 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);System.out.println(table.getColumnName(0));frame.getContentPane().add(table);frame.setVisible(true);//getModel方法——获得当前表格使用的表格模型 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);System.out.println(table.getModel());frame.getContentPane().add(table);frame.setVisible(true);//getRowCount方法——获得表格中包含的行数 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);System.out.println(table.getRowCount());frame.getContentPane().add(table);frame.setVisible(true);//getSelectedColumn方法——获得用户选中的第一列的索引 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);System.out.println(table.getSelectedColumn());frame.getContentPane().add(table);frame.setVisible(true);//getSelectedRow方法——获得选中行的索引 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);System.out.println(table.getSelectedRow());frame.getContentPane().add(table);frame.setVisible(true);//print方法——打印调用该方法的表格 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);table.print();frame.getContentPane().add(table);frame.setVisible(true);//setAutoCreateRowSorter方法——设置表格能否根据行的内容进行排列 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);table.setAutoCreateRowSorter(true);frame.getContentPane().add(table);frame.setVisible(true);//setAutoResizeMode方法——指定改变表格大小时各列的调整方式 //指定改变表格大小时各列的调整方式//setModel方法——为表格设置新的表格模型 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable();table.setModel(model);frame.getContentPane().add(table);frame.setVisible(true);//setRowHeight方法——设置表格的列高 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);table.setRowHeight(0,50);frame.getContentPane().add(table);frame.setVisible(true);//setShowGrid方法——设置是否显示单元格的分隔线 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"20101","1号"});model.addRow(new String[]{"20102","2号"});JTable table = new JTable(model);table.setShowGrid(false);frame.getContentPane().add(table);frame.setVisible(true);
//DefaultTableModel类 //DefaultTableModel构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JTable table = new JTable();DefaultTableModel model = new DefaultTableModel();table.setModel(model);frame.getContentPane().add(table);frame.setVisible(true);//addColumn方法——向表格模型中增加列 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JTable table = new JTable();DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");table.setModel(model);frame.getContentPane().add(table);frame.setVisible(true);//addRow方法——向表格模型中增加一行数据 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JTable table = new JTable();DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"2001","2002"});model.addRow(new String[]{"小张","小王"});table.setModel(model);frame.getContentPane().add(table);frame.setVisible(true);//getDataVector方法——将表格中的数据保存到一个向量中 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JTable table = new JTable();DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"2001","2002"});model.addRow(new String[]{"小张","小王"});table.setModel(model);Vector dateVector = model.getDataVector();for (Iterator iterator = dateVector.iterator(); iterator.hasNext();) {System.out.println(iterator.next());}frame.getContentPane().add(table);frame.setVisible(true);//setRowCount方法——设置表格模型中数据的行数 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JTable table = new JTable();DefaultTableModel model = new DefaultTableModel();model.addColumn("学号");model.addColumn("姓名");model.addRow(new String[]{"2001","2002"});model.addRow(new String[]{"小张","小王"});table.setModel(model);model.setRowCount(0);frame.getContentPane().add(table);frame.setVisible(true);
<!--树控件 ->
//javaxswingJTree类 //JTree构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};JTree tree = new JTree(nodes);frame.getContentPane().add(tree);frame.setVisible(true);//addSelectionInterval方法——将树控件指定范围内的路径增加到选择状态中 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};JTree tree = new JTree(nodes);tree.addSelectionInterval(0, 2);frame.getContentPane().add(tree);frame.setVisible(true);//addSelectionRow方法——将位于特定行的路径增加到选择状态中 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};JTree tree = new JTree(nodes);tree.addSelectionRow(0);frame.getContentPane().add(tree);frame.setVisible(true);//addTreeExpansionListener方法——监听树结点展开合并事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};JTree tree = new JTree(nodes);tree.addTreeExpansionListener(new TreeExpansionListener() {@Overridepublic void treeExpanded(TreeExpansionEvent event) {JOptionPane.showMessageDialog(null, "合并节点");}@Overridepublic void treeCollapsed(TreeExpansionEvent event) {JOptionPane.showMessageDialog(null, "展开节点");}});frame.getContentPane().add(tree);frame.setVisible(true);//addTreeSelectionListener方法——监听树结点的选择事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};JTree tree = new JTree(nodes);tree.addTreeSelectionListener(new TreeSelectionListener() {@Overridepublic void valueChanged(TreeSelectionEvent e) {JOptionPane.showMessageDialog(null, "选择了一个节点");return;}});frame.getContentPane().add(tree);frame.setVisible(true);//getLastSelectedPathComponent方法——获得用户选择的结点 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};final JTree tree = new JTree(nodes);tree.addTreeSelectionListener(new TreeSelectionListener() {@Overridepublic void valueChanged(TreeSelectionEvent e) {Object selectObject = tree.getLastSelectedPathComponent();JOptionPane.showMessageDialog(null, "选择"+selectObject);}});frame.getContentPane().add(tree);frame.setVisible(true);//getModel方法——获得树模型 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};final JTree tree = new JTree(nodes);TreeModel model = tree.getModel();System.out.println(model.getRoot());frame.getContentPane().add(tree);frame.setVisible(true);//getRowCount方法——输出树结构中当前显示的行数 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};final JTree tree = new JTree(nodes);System.out.println(tree.getRowCount());frame.getContentPane().add(tree);frame.setVisible(true);//setCellEditor方法——设置树结点编辑器 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};final JTree tree = new JTree(nodes);tree.setCellEditor(new DefaultCellEditor(new JTextField()));tree.setEditable(true);frame.getContentPane().add(tree);frame.setVisible(true);//setCellRenderer方法——为树控件设置渲染器 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};final JTree tree = new JTree(nodes);DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();renderer.setLeafIcon(new ImageIcon("src/1.jpg"));tree.setCellRenderer(renderer);frame.getContentPane().add(tree);frame.setVisible(true);//setRootVisible方法——设置根结点是否可见 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};final JTree tree = new JTree(nodes);tree.setRootVisible(true);frame.getContentPane().add(tree);frame.setVisible(true);//setRowHeight方法——设置结点的高度 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};final JTree tree = new JTree(nodes);tree.setRowHeight(50);frame.getContentPane().add(tree);frame.setVisible(true);//setShowsRootHandles方法——设置是否显示“把手” JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);String[] nodes = {"JAVA","PHP","JSP"};final JTree tree = new JTree(nodes);tree.setShowsRootHandles(false);frame.getContentPane().add(tree);frame.setVisible(true);
//javaxswingtreeDefaultTreeModel类 //getChild方法——获得指定结点的指定位置的元素 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultMutableTreeNode root = new DefaultMutableTreeNode("图书");DefaultMutableTreeNode parent1 = new DefaultMutableTreeNode("人工智能");parent1.add(new DefaultMutableTreeNode("大数据"));parent1.add(new DefaultMutableTreeNode("大数据1"));parent1.add(new DefaultMutableTreeNode("大数据2"));parent1.add(new DefaultMutableTreeNode("大数据3"));root.add(parent1);DefaultTreeModel model = new DefaultTreeModel(root);System.out.println(model.getChild(parent1, 3));JTree jTree = new JTree(model);frame.getContentPane().add(jTree);frame.setVisible(true);//getChildCount方法——获得指定结点的子结点个数 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultMutableTreeNode root = new DefaultMutableTreeNode("图书");DefaultMutableTreeNode parent1 = new DefaultMutableTreeNode("人工智能");parent1.add(new DefaultMutableTreeNode("大数据"));parent1.add(new DefaultMutableTreeNode("大数据1"));parent1.add(new DefaultMutableTreeNode("大数据2"));parent1.add(new DefaultMutableTreeNode("大数据3"));root.add(parent1);DefaultTreeModel model = new DefaultTreeModel(root);System.out.println(model.getChildCount(parent1));JTree jTree = new JTree(model);frame.getContentPane().add(jTree);frame.setVisible(true);//getRoot方法——获得树模型的根结点 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);DefaultMutableTreeNode root = new DefaultMutableTreeNode("图书");DefaultMutableTreeNode parent1 = new DefaultMutableTreeNode("人工智能");parent1.add(new DefaultMutableTreeNode("大数据"));parent1.add(new DefaultMutableTreeNode("大数据1"));parent1.add(new DefaultMutableTreeNode("大数据2"));parent1.add(new DefaultMutableTreeNode("大数据3"));root.add(parent1);DefaultTreeModel model = new DefaultTreeModel(root);System.out.println(model.getRoot());JTree jTree = new JTree(model);frame.getContentPane().add(jTree);frame.setVisible(true);//insertNodeInto方法——向树模型中指定位置插入新结点 //插入新的节点 //removeNodeFromParent方法——从树模型中删除结点 //删除节点
<!--进度指示控件 ->
//javaxswingJProgressBar控件 //JProgressBar构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JProgressBar jProgressBar = new JProgressBar(0,100);frame.getContentPane().add(jProgressBar);frame.setVisible(true);//addChangeListener方法——监听进度条变化事件 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JProgressBar jProgressBar = new JProgressBar(0,100);jProgressBar.addChangeListener(new ChangeListener() {@Overridepublic void stateChanged(ChangeEvent e) {System.out.println("启动完毕");}});frame.getContentPane().add(jProgressBar);frame.setVisible(true);}//getValue方法——获得当前进度条显示的值 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JProgressBar jProgressBar = new JProgressBar(0,100);System.out.println(jProgressBar.getValue());frame.getContentPane().add(jProgressBar);frame.setVisible(true);//setBorderPainted方法——设置是否绘制滚动条的边框 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JProgressBar jProgressBar = new JProgressBar(0,100);jProgressBar.setBorderPainted(false);frame.getContentPane().add(jProgressBar);frame.setVisible(true);//setIndeterminate方法——设置滚动条持续滚动 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JProgressBar jProgressBar = new JProgressBar(0,100);jProgressBar.setIndeterminate(true);frame.getContentPane().add(jProgressBar);frame.setVisible(true);//setString方法——设置在滚动条上显示的文本 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JProgressBar jProgressBar = new JProgressBar(0,100);jProgressBar.setString("图书");jProgressBar.setStringPainted(true);frame.getContentPane().add(jProgressBar);frame.setVisible(true);//setValue方法——设置滚动条当前显示的值 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setLayout(new FlowLayout());frame.setBounds(400,320,400,240);JProgressBar jProgressBar = new JProgressBar(0,100);jProgressBar.setValue(50);System.out.println(jProgressBar.getValue());frame.getContentPane().add(jProgressBar);frame.setVisible(true);
//javaxswingProgressMonitor控件 //ProgressMonitor构造方法 //创建进度显示器//close方法——关闭进度显示器 //关闭进度显示器//setNote方法——设置进度显示器上显示的文本 //设置进度显示器上的文本
<!--高级布局管理器 ->
//javaawtGridBagLayout网格包布局//GridBagLayout构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);GridLayout gridBagLayout = new GridLayout();frame.getContentPane().setLayout(gridBagLayout);frame.setVisible(true);//anchor属性——设置组件在其所显示区域的显示位置 //设置组件在其显示区域的显示位置,通常有9个方位//fill属性——设置组件的填充方式 //fill属性可以设置组件填充//gridx属性和gridy属性——设置组件起始点所在单元格的索引值 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);GridLayout gridBagLayout = new GridLayout();JButton button = new JButton();button.setText("0,0");GridBagConstraints gridBagConstraints = new GridBagConstraints();gridBagConstraints.gridy = 0;gridBagConstraints.gridx = 0;frame.getContentPane().setLayout(gridBagLayout);frame.getContentPane().add(button,gridBagConstraints);frame.setVisible(true);//gridheight属性和gridwidth属性——设置组件占用网格的行数和列数 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);GridLayout gridBagLayout = new GridLayout();JButton button = new JButton();button.setText("0,0");GridBagConstraints gridBagConstraints = new GridBagConstraints();gridBagConstraints.gridy = 0;gridBagConstraints.gridx = 0;gridBagConstraints.gridwidth = 2;frame.getContentPane().setLayout(gridBagLayout);frame.getContentPane().add(button,gridBagConstraints);frame.setVisible(true);//insets属性——设置组件四周与单元格边缘之间的最小距离 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);GridLayout gridBagLayout = new GridLayout();JButton button = new JButton();button.setText("0,0");GridBagConstraints gridBagConstraints = new GridBagConstraints();gridBagConstraints.insets = new Insets(10, 10, 10, 10);gridBagConstraints.gridx = 1;gridBagConstraints.gridy = 1;frame.getContentPane().setLayout(gridBagLayout);frame.getContentPane().add(button,gridBagConstraints);frame.setVisible(true);//ipadx属性和ipady属性——修改组件的首选大小 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);GridLayout gridBagLayout = new GridLayout();JButton button = new JButton();button.setText("0,0");GridBagConstraints gridBagConstraints = new GridBagConstraints();gridBagConstraints.ipadx = 10;gridBagConstraints.ipady = 20;gridBagConstraints.gridx = 1;gridBagConstraints.gridy = 1;frame.getContentPane().setLayout(gridBagLayout);frame.getContentPane().add(button,gridBagConstraints);frame.setVisible(true);//weightx属性和weighty属性——设置网格组的每一行和每一列对额外空间的分布方式 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);GridLayout gridBagLayout = new GridLayout();JButton button = new JButton();button.setText("0,0");GridBagConstraints gridBagConstraints = new GridBagConstraints();gridBagConstraints.weightx = 40;gridBagConstraints.weighty = 40;gridBagConstraints.gridx = 1;gridBagConstraints.gridy = 1;frame.getContentPane().setLayout(gridBagLayout);frame.getContentPane().add(button,gridBagConstraints);frame.setVisible(true);
//javaxswingSpringLayout弹簧布局 //SpringLayout构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);SpringLayout springLayout = new SpringLayout();frame.getContentPane().setLayout(springLayout);frame.setVisible(true);//getConstraints方法——获得组件的SpringLayoutConstraints对象 //获得组件的SpringLayoutConstraints对象 //putConstraint方法——建立组件之间各个边的约束 //建立组件之间各个边的约束
//javaxswingBoxLayout箱式布局 //BoxLayout构造方法 JFrame frame = new JFrame();frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setBounds(400,320,400,240);BoxLayout hBox = new BoxLayout(frame.getContentPane(), BoxLayout.X_AXIS);frame.getContentPane().setLayout(hBox);frame.setVisible(true);//Box容器——箱式容器 //布局管理器轻量级容器
<!--输入/输出流 ->
//javaioBufferedInputStream——缓冲字节输入流 //available方法——返回可读取的估计字节数 File file = new File("c:/test.txt");FileInputStream in = new FileInputStream(file);BufferedInputStream bis = new BufferedInputStream(in);bis.read();System.out.println(bis.available());bis.close();in.close();//close方法——关闭输入流并释放与该流关联的所有系统资源 File file = new File("c:/test.txt");FileInputStream in = new FileInputStream(file);BufferedInputStream bis = new BufferedInputStream(in);bis.read();System.out.println(bis.available());bis.close();in.close();//mark方法——记录当前指针所在的位置 File file = new File("c:/test.txt");FileInputStream in = new FileInputStream(file);BufferedInputStream bis = new BufferedInputStream(in);bis.mark(5);int count = 0;for (int i = 0; i < file.length(); i++) {count++;int read = bis.read();if (count%5 == 0) {bis.reset();System.out.println(read);}}bis.close();in.close();//markSupported方法——测试是否支持mark方法和reset方法 File file = new File("c:/test.txt");FileInputStream in = new FileInputStream(file);BufferedInputStream bis = new BufferedInputStream(in);if(bis.markSupported()){System.out.println("BUFFERED类支持mark和reset方法");}bis.close();in.close();//read方法——从输入流中读取数据 File file = new File("c:/test.txt");FileInputStream in = new FileInputStream(file);BufferedInputStream bis = new BufferedInputStream(in);bis.read();System.out.println(bis.available());bis.close();in.close();//reset方法——重新定位输入流 File file = new File("c:/test.txt");FileInputStream in = new FileInputStream(file);BufferedInputStream bis = new BufferedInputStream(in);bis.mark(5);int count = 0;for (int i = 0; i < file.length(); i++) {count++;int read = bis.read();if (count%5 == 0) {bis.reset();System.out.println(read);}}bis.close();in.close();//skip方法——跳过并丢弃指定字节数量的数据 File file = new File("c:/test.txt");FileInputStream in = new FileInputStream(file);BufferedInputStream bis = new BufferedInputStream(in);bis.skip(5);int i = 0;while ((i = bis.read())!=-1) {System.out.println(i);}bis.close();in.close();//javaioBufferedOutputStream——缓冲字节输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);BufferedOutputStream bus = new BufferedOutputStream(fos);byte[] by = "香蕉".getBytes();bus.write(by);bus.flush();bus.close();//flush方法——刷新此缓冲输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);BufferedOutputStream bus = new BufferedOutputStream(fos);byte[] by = "香蕉".getBytes();bus.write(by);bus.flush();bus.close();//write方法——向输出流中写数据 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);BufferedOutputStream bus = new BufferedOutputStream(fos);byte[] by = "香蕉".getBytes();bus.write(by);bus.flush();bus.close();
//javaioBufferedReader——缓冲字符输入流 //close方法——关闭流并释放与之关联的所有资源 BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));System.out.println("输入一个字符串");String str = buf.readLine();buf.close();System.out.println(str);//mark方法——记录当前读指针所在的位置 File file = new File("c:/test.txt");BufferedReader buf = new BufferedReader(new FileReader(file));int count = 0;buf.mark(1);for (int i = 0; i < file.length(); i++) {count++;int read = buf.read();if(count%5==0){buf.reset();System.out.println(read);}}buf.close();//markSupported方法——判断指定流是否支持mark操作 File file = new File("c:/test.txt");BufferedReader buf = new BufferedReader(new FileReader(file));if(buf.markSupported()){System.out.println("BufferedReader支持mark");}buf.close();//read方法——从缓冲输入流中读取字符 File file = new File("c:/test.txt");BufferedReader buf = new BufferedReader(new FileReader(file));int count = 0;buf.mark(1);for (int i = 0; i < file.length(); i++) {count++;int read = buf.read();if(count%5==0){buf.reset();System.out.println(read);}}buf.close();//readLine方法——读取一个文本行 BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));System.out.println("输入一个字符串");String str = buf.readLine();buf.close();System.out.println(str);//ready方法——判断此流是否已准备好被读取 File file = new File("c:/test.txt");BufferedReader buf = new BufferedReader(new FileReader(file));if(buf.ready()){System.out.println(buf.readLine());}buf.close();//reset方法——重定位指针 File file = new File("c:/test.txt");BufferedReader buf = new BufferedReader(new FileReader(file));int count = 0;buf.mark(10);for(int i= 0; i< file.length();i++){count++;int read = buf.read();if(count%3 == 0)buf.reset();System.out.println(read);}buf.close();//skip方法——跳过指定数量的字符 File file = new File("c:/test.txt");BufferedReader buf = new BufferedReader(new FileReader(file));buf.skip(10);int i;while((i = buf.read())!=-1){System.out.println(i);}buf.close();
//javaioBufferedWriter——缓冲字符输出流 //close方法——关闭流 File file = new File("c:/test.txt");FileWriter fw = new FileWriter(file);BufferedWriter bufw = new BufferedWriter(fw);String str = "最近好吗";bufw.write(str);bufw.close();fw.close();//flush方法——刷新缓冲区 File file = new File("c:/test.txt");FileWriter fw = new FileWriter(file);String strArr[] = {"词典","参考大全","手册"};BufferedWriter bufw = new BufferedWriter(fw);for (int i = 0; i < strArr.length; i++) {bufw.write(strArr[i]);}bufw.flush();fw.close();//newLine方法——写入一个行分隔符 File file = new File("c:/test.txt");FileWriter fw = new FileWriter(file);String strArr[] = {"词典1","参考大全1","手册1"};BufferedWriter bufw = new BufferedWriter(fw);for (int i = 0; i < strArr.length; i++) {bufw.write(strArr[i]);bufw.newLine();}bufw.flush();fw.close();//write方法——向缓冲区中写数据 File file = new File("c:/test.txt");FileWriter fw = new FileWriter(file);char[] ch = {'a','b','c'};BufferedWriter bufw = new BufferedWriter(fw);bufw.write(ch,0,3);bufw.flush();fw.close();
//javaioDataInputStream——数据输入流 //read方法——读取一定数量的字节 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);byte[] b = new byte[50];dis.read(b);for (int i = 0; i < b.length; i++) {System.out.println(b[i]);}dis.close();fis.close();//readByte方法——读取此操作需要的字节 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readByte());dis.close();fis.close();//readBoolean方法——读取一个布尔值 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readBoolean());dis.close();fis.close();//readchar方法——读取此操作需要的字符 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readChar());dis.close();fis.close();//readDouble方法——读取一个double值 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readDouble());dis.close();fis.close();//readFloat方法——读取一个float值 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readFloat());dis.close();fis.close();//readFully方法——读取一些字节 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);byte[] b = new byte[20];dis.readFully(b);for (int i = 0; i < b.length; i++) {System.out.println(b[i]);}dis.close();fis.close();//readInt方法——读取一个int值 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readInt());dis.close();fis.close();//readLong方法——读取一个long值 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readLong());dis.close();fis.close();//readShort方法——读取一个short值 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readShort());dis.close();fis.close();//readUnsignedByte方法——读取无符号的byte值 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readUnsignedByte());dis.close();fis.close();//readUnsignedShort方法——读取无符号的short值 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readUnsignedShort());dis.close();fis.close();//readUTF方法——读取UTF-编码的字符串 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);dos.writeUTF("图书");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readUTF());dos.close();dis.close();fos.close();fis.close();//skipBytes方法——在输入流中跳过数据的n字节 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);byte[] b = new byte[50];dis.skipBytes(10);dis.read(b);for (int i = 0; i < b.length; i++) {System.out.println(b[i]);}dis.close();fis.close();
//javaioDataOutputStream——数据输出流 //flush方法——清空此数据输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);byte[] b = "欢迎使用".getBytes();dos.write(b);dos.flush();dos.close();fos.close();//size方法——返回计数器written的当前值 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);byte[] b = "欢迎使用".getBytes();dos.write(b);System.out.println(dos.size());dos.flush();dos.close();fos.close();//write方法——写入基础输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);byte[] b = "欢迎使用".getBytes();dos.write(b);dos.flush();dos.close();fos.close();//writeBoolean方法——将boolean值写入输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);dos.writeBoolean(true);dos.flush();dos.close();fos.close();//writeByte方法——将byte值写入输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);dos.writeByte(99);dos.flush();dos.close();fos.close();//writeBytes方法——将字符串中每一个字符的低字节内容写入输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);dos.writeBytes("JAVA");dos.flush();dos.close();fos.close();//writeChar方法——将char值写入输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);char v = 'a';dos.writeChar(v);dos.flush();dos.close();fos.close();//writechars方法——将字符串每个char值写入输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);dos.writeChars("JAVA");dos.flush();dos.close();fos.close();//writeDouble方法——将double值写入输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);double v = 123.10;dos.writeDouble(v);dos.flush();dos.close();fos.close();//writeFloat方法——将float值写入输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);float v = (float) 123.100;dos.writeFloat(v);dos.flush();dos.close();fos.close();//writeLong方法——将long值写入输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);long v = 123456;dos.writeLong(v);dos.flush();dos.close();fos.close();//writeShort方法——将short值写入输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);short v = 123;dos.writeShort(v);dos.flush();dos.close();fos.close();//writeUTF方法——将UTF-编码字符写入输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);dos.writeUTF("写入文件的数据");dos.flush();dos.close();fos.close();
//javaioInputStream——字节输入流 //available方法——获取有效的可读取字节数 File file = new File("c:/test.txt");FileInputStream in = new FileInputStream(file);System.out.println(in.available());//close方法——关闭输入流 InputStream is = System.in;byte[] b = new byte[50];is.read(b);System.out.println("控制台内容"+new String(b).trim());is.close();//mark方法——在此输入流中标记当前的位置 File file = new File("c:/test.txt");InputStream bis = new BufferedInputStream(new FileInputStream(file));int count = 0;bis.mark(50);for (int i = 0; i < file.length(); i++) {int read = bis.read();if(count%5==0){bis.reset();System.out.println();}count++;System.out.println(read);}bis.close();//markSupported方法——判断是否支持mark和reset方法 File file = new File("c:/test.txt");FileInputStream in = new FileInputStream(file);if(in.markSupported()){System.out.println("支持mark和reset");}else {System.out.println("不支持");}in.close();//read方法——读取字节输入流中的数据 InputStream is = System.in;byte[] b = new byte[50];is.read(b);System.out.println("控制台内容"+new String(b).trim());is.close();//reset方法——重新定位到最后一次mark方法时的位置 File file = new File("c:/test.txt");FileInputStream in = new FileInputStream(file);BufferedInputStream bis = new BufferedInputStream(in);int count = 0;bis.mark(50);for (int i = 0; i < file.length(); i++) {count++;int read = bis.read();if(count== 5)bis.reset();System.out.println(read);}bis.close();//skip方法——跳过并丢弃n字节 File file = new File("c:/test.txt");FileInputStream in = new FileInputStream(file);in.skip(10);int i;while ((i = in.read())!=-1) {System.out.println(i);}in.close();
//javaioOutputStream——字节输出流 //close方法——关闭字节输出流 PrintStream out = System.out;byte[] b = "欢迎使用".getBytes();out.write(b);out.close();//flush方法——刷新缓冲区 PrintStream out = System.out;byte[] b = "欢迎使用".getBytes();out.write(b);out.flush();out.close();//write方法——向输出流写数据 PrintStream out = System.out;byte[] b = "欢迎使用".getBytes();out.write(b);out.flush();out.close();
//javaioObjectOutputStream——对象输出流 //close方法——关闭对象输出流 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);oos.close();fos.close();//flush方法——刷新缓冲区 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);oos.write(10);oos.flush();oos.close();fos.close();//writeObject方法——向输出流写入对象 public class javaTest {public static void main(String[] args) throws Throwable {File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);Student student = new Student();student.name = "小王";student.sex = "男";oos.writeObject(student);oos.flush();oos.close();fos.close();}}class Student implements Serializable{String name;String sex;}//writeBytes方法——向输出流写入字符串 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);String str = "JAVA";oos.writeBytes(str);oos.close();fos.close();//write方法——向输出流写入byte值 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);byte[] b = "JAVA".getBytes();oos.write(b);oos.close();fos.close();//writeChar方法——向输出流写入char值 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);char v = 'a';oos.writeChar(v);oos.close();fos.close();//writeChars方法——向输出流写入String值 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeChars("JAVA");oos.close();fos.close();//writeDouble方法——向输出流写入double值 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeDouble(123.456);oos.close();fos.close();//writeFields方法——将已缓冲的字段写入流中 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);double d = 123.456;oos.writeDouble(d);oos.writeFields();oos.close();fos.close();//writeFloat方法——向输出流写入float值 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeFloat(100.123f);oos.close();fos.close();//writeInt方法——向输出流写入int值 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeInt(100);oos.close();fos.close();//writeLong方法——向输出流写入long值 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);long v = 10000;oos.writeLong(v);oos.close();fos.close();//writeShort方法——向输出流写入short值 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);short v = 123;oos.writeShort(v);oos.close();fos.close();//writeUTF方法——向输出流写入float值 File file = new File("c:/test.txt");FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeUTF("aaaaa");oos.close();fos.close();
//javaioObjectInputStream——对象输入流 //readObject方法——从输入流读取对象 public class javaTest {public static void main(String[] args) throws Throwable {File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);ObjectInputStream ois = new ObjectInputStream(fis);Student st = (Student) ois.readObject();System.out.println(st.name);System.out.println(st.sex);ois.close();fis.close();}}class Student implements Serializable{String name;String sex;}//readInt方法——从输入流读取int值 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);ObjectInputStream ois = new ObjectInputStream(fis);System.out.println(ois.readInt());ois.close();fis.close();//readFloat方法——从输入流读取float值 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);ObjectInputStream ois = new ObjectInputStream(fis);System.out.println(ois.readFloat());ois.close();fis.close();//readchar方法——从输入流读取char值 File file = new File("c:/test.txt");FileInputStream fis = new FileInputStream(file);ObjectInputStream ois = new ObjectInputStream(fis);System.out.println(ois.readChar());ois.close();fis.close();
//javaioRandomAccessFile——随机文件访问类 //close方法——关闭数据流 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.read();r.close();//getChannel方法——返回此文件的FileChannel对象 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");FileChannel channel = r.getChannel();r.close();//getFD方法——返回此流的不透明文件描述符对象 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");FileDescriptor fd = r.getFD();r.close();//getFilePointer方法——返回文件中的当前偏移量 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.seek(10);System.out.println(r.getFilePointer());r.close();//length方法——返回此文件的长度 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.length());r.close();//read方法——读取一个数据字节 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.read();r.close();//readBoolean方法——从文件读取一个boolean值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.readBoolean());r.close();//readByte方法——从文件读取一个byte值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.readByte());r.close();//readInt方法——从文件读取一个int值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.readInt());r.close();//readChar方法——从文件读取一个char值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.readChar());r.close();//readDouble方法——从文件读取一个double值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.readDouble());r.close();//readFloat方法——从文件读取一个float值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.readFloat());r.close();//readFully方法——从文件读取一个字节数组 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");byte[] b = new byte[10];r.readFully(b);for (int i = 0; i < b.length; i++) {System.out.println(b[i]);}r.close();//readLine方法——从此文件读取文本的下一行 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.readLine());r.close();//readLong方法——从文件读取一个long值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.readLong());r.close();//readShort方法——从文件读取一个short值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.readShort());r.close();//readUnsignedByte方法——从文件读取无符号byte值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.readUnsignedByte());r.close();//readUnsignedShort方法——从文件读取无符号short值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.readUnsignedShort());r.close();//readUTF方法——从此文件读取一个UTF-字符串 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");System.out.println(r.readUTF());r.close();//setLength方法——设置此文件的长度 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.setLength(10);r.close();//seek方法——将文件指针移至指定位置 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.seek(10);r.writeChars("欢迎使用");r.close();//skipBytes方法——跳过并丢弃n字节 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.skipBytes(3);System.out.println(r.read());r.close();//write方法——向此文件写入指定的字节 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");byte[] b = {65,66,67,68,69,70};r.seek(r.length());r.write(b);r.close();//writeBoolean方法——将boolean值写入文件 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.seek(r.length());boolean v = true;r.writeBoolean(v);r.close();//writeByte方法——将byte值写入该文件 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.seek(r.length());byte v = 24;r.writeByte(v);r.close();//writeBytes方法——按字节序列将该字符串写入该文件 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.seek(r.length());r.writeBytes("JAVA");r.close();//writeChars方法——写入作为字符数据的字符串 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.seek(r.length());r.writeChars("JAVA");r.close();//writeDouble方法——写入double值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.seek(r.length());double v = 123.123d;r.writeDouble(v);r.close();//writeFloat方法——向文件写入float值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.seek(r.length());float v = 123.123f;r.writeFloat(v);r.close();//writeInt方法——向文件写入int值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.seek(r.length());int v = 123;r.writeInt(v);r.close();//writeLong方法——向文件写入long值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.seek(r.length());long v = 123123;r.writeLong(v);r.close();//writeShort方法——向文件写入short值 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.seek(r.length());short v = 12;r.writeShort(v);r.close();//writeUTF方法——向文件写入UTF- 编码的字符串 File file = new File("c:/test.txt");RandomAccessFile r = new RandomAccessFile(file, "rw");r.seek(r.length());r.writeUTF("参考手册");r.close();
//javaioReader——读取字符流的抽象类 //close方法——关闭流 InputStreamReader rin = new InputStreamReader(System.in);char[] c = new char[50];rin.read(c);String str = new String(c);System.out.println(str.trim());rin.close();//mark方法——标记流中的当前位置 File file = new File("c:/test.txt");BufferedReader r = new BufferedReader(new FileReader(file));int count = 0;r.mark(10);for (int i = 0; i < file.length(); i++) {int read = r.read();if(count%5 == 0){r.reset();System.out.println();}count++;System.out.println(read);}r.close();//markSupported方法——判断是否支持mark操作 File file = new File("c:/test.txt");FileReader r = new FileReader(file);if(r.markSupported()){System.out.println("支持");}else{System.out.println("不支持");}r.close();//read方法——读取流中的数据 InputStreamReader r = new InputStreamReader(System.in);char[] c = new char[100];r.read(c);String str = new String(c);System.out.println(str.trim());r.close();//ready方法——判断是否准备读取此流 File file = new File("c:/test.txt");FileReader r = new FileReader(file);if(r.ready()){int i ;while ((i = r.read())!=-1) {System.out.println(i);}}r.close();//reset方法——重置该流 File file = new File("c:/test.txt");BufferedReader r = new BufferedReader(new FileReader(file));int count = 0;r.mark(5);for (int i = 0; i < file.length(); i++) {int read = r.read();if(count % 5 == 0){r.reset();System.out.println();}count++;System.err.println(read);}r.close();//skip方法——跳过并丢弃n字节 File file = new File("c:/test.txt");FileReader r = new FileReader(file);if(r.ready()){r.skip(10);int i;while ((i=r.read())!=-1) {System.out.println(i);}}r.close();
//javautilScanner——简单文本扫描器 //close方法——关闭扫描器 Scanner s = new Scanner("JAVA LIKE PHP");s.close();//delimiter方法——返回匹配分隔符的 Pattern Scanner s = new Scanner("1 and 2 and yellow and blue and");s.findInLine("(\\d+) and (\\d+) and (\\w+) and (\\w+)");MatchResult result = s.match();for (int i = 0; i < result.groupCount(); i++) {System.out.println(result.group(i));}s.close();//findInLine方法——忽略分隔符查找下一个构造模式 Scanner s = new Scanner("1 and 2 and yellow and blue and");s.findInLine("(\\d+) and (\\d+) and (\\w+) and (\\w+)");MatchResult result = s.match();for (int i = 0; i < result.groupCount(); i++) {System.out.println(result.group(i));}s.close();//findWithinHorizon方法——试图查找下一个指定模式 Scanner s = new Scanner("1 and 2 and yellow and blue and");String str = s.findWithinHorizon("and", 7);System.out.println(str);s.close();//hasNext方法——扫描器的输入中是否有另一个标记 Scanner s = new Scanner("1 and 2 and yellow and blue and");if (s.hasNext(Pattern.compile("\\d"))) {System.out.println("有另一个标记");}s.close();//hasNextBigDecimal方法——下一个标记是否默认基数中的一个 BigDecimal Scanner s = new Scanner("1 and 2 and yellow and blue and");if (s.hasNextBigDecimal()) {System.out.println(s.nextBigDecimal());}s.close();//hasNextBigInteger方法——下一个标记是否默认基数中的一个BigInteger Scanner s = new Scanner("1 and 2 and yellow and blue and");if (s.hasNextBigInteger()) {System.out.println(s.nextBigInteger());}s.close();//hasNextBoolean方法——下一个标记是否为布尔值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if (s.hasNextBoolean()) {System.out.println(s.nextBoolean());}s.close();//hasNextByte方法——下一个标记是否为byte值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if (s.hasNextByte()) {System.out.println(s.nextByte());}s.close();//hasNextDouble方法——下一个标记是否为double值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if (s.hasNextDouble()) {System.out.println(s.nextDouble());}s.close();//hasNextFloat方法——下一个标记是否为float值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if (s.hasNextFloat()) {System.out.println(s.nextFloat());}s.close();//hasNextInt方法——下一个标记是否为int值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if (s.hasNextInt()) {System.out.println(s.nextInt());}s.close();//hasNextLine方法——是否存在下一行 Scanner s = new Scanner("1 and 2 and yellow and blue and");if (s.hasNextLine()) {System.out.println(s.nextLine());}s.close();//hasNextLong方法——下一个标记是否为long值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if (s.hasNextLong()) {System.out.println(s.nextLong());}s.close();//hasNextShort方法——下一个标记是否为short值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if (s.hasNextShort()) {System.out.println(s.nextShort());}s.close();//ioException方法——最后抛出的 IOException Scanner s = new Scanner("1 and 2 and yellow and blue and");IOException ie = s.ioException();if(ie != null){ie.printStackTrace();}s.close();//locale方法——返回此扫描器的语言环境 Scanner s = new Scanner("1 and 2 and yellow and blue and");System.out.println(s.locale());s.close();//match方法——最后扫描操作的匹配结果 Scanner s = new Scanner("1 and 2 and yellow and blue and");s.findInLine("(\\d+) and (\\d+) and (\\w+) and (\\w+)");MatchResult result = s.match();for (int i = 0; i < result.groupCount(); i++) {System.out.println(result.group(i));}s.close();//next方法——读取下一个完整标记 Scanner s = new Scanner("1 and 2 and yellow and blue and");if(s.hasNext()){System.out.println(s.next());}s.close();//nextBigDecimal方法——读取下一个BigDecimal值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if(s.hasNextBigDecimal()){System.out.println(s.nextBigDecimal());}s.close();//nextBigInteger方法——读取下一个BigInteger值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if(s.hasNextBigInteger()){System.out.println(s.nextBigInteger());}s.close();//nextBoolean方法——读取下一个boolean值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if(s.hasNextBoolean()){System.out.println(s.nextBoolean());}s.close();//nextByte方法——读取下一个byte值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if(s.hasNextByte()){System.out.println(s.nextByte());}s.close();//nextDouble方法——读取下一个double值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if(s.hasNextDouble()){System.out.println(s.nextDouble());}s.close();//nextFloat方法——读取下一个float值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if(s.hasNextFloat()){System.out.println(s.nextFloat());}s.close();//nextInt方法——读取下一个int值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if(s.hasNextInt()){System.out.println(s.nextInt());}s.close();//nextShort方法——读取下一个short值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if(s.hasNextShort()){System.out.println(s.nextShort());}s.close();//nextLine方法——读取下一行文本 Scanner s = new Scanner("1 and 2 and yellow and blue and");if(s.hasNextLine()){System.out.println(s.nextLine());}s.close();//nextLong方法——读取下一个long值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if(s.hasNextLong()){System.out.println(s.nextLong());}s.close();//nextShort方法——读取下一个short值 Scanner s = new Scanner("1 and 2 and yellow and blue and");if(s.hasNextShort()){System.out.println(s.nextShort());}s.close();//radix方法——返回扫描器的默认基数 Scanner s = new Scanner("1 and 2 and yellow and blue and");System.out.println(s.radix());s.close();//reset方法——重置扫描器 Scanner s = new Scanner("1 and 2 and yellow and blue and");s.useRadix(4);s.reset();s.close();//skip方法——忽略分隔符跳过匹配的输入信息 Scanner s = new Scanner("1 and 2 and yellow and blue and");s.skip(Pattern.compile("\\d and"));if(s.hasNext()){System.out.println(s.next());}s.close();//toString方法——返回扫描器的字符串表示形式 Scanner s = new Scanner("1 and 2 and yellow and blue and");System.out.println(s.toString());s.close();//useDelimiter方法——设置为指定分隔模式 Scanner s = new Scanner("1 and 2 and yellow and blue and");s.useDelimiter(Pattern.compile("\\sfish\\s"));s.close();//useLocale方法——设置为指定的语言环境 Scanner s = new Scanner("1 and 2 and yellow and blue and");s.useDelimiter(Pattern.compile("\\sfish\\s"));s.useLocale(new Locale("EN","US"));System.out.println(s.locale());s.close();//useRadix方法——设置指定基数 Scanner s = new Scanner("1 and 2 and yellow and blue and");s.useRadix(16);System.out.println(s.radix());s.close();
//javautilWriter——写入字符流的抽象类 //append方法——添加指定字符 PrintWriter out = new PrintWriter(System.out);out = out.append('a');out.write(0);out.close();//close方法——关闭数据流 PrintWriter out = new PrintWriter(System.out);out = out.append('a');out.write(0);out.close();//flush方法——刷新流的缓冲 PrintWriter out = new PrintWriter(System.out);out.write("欢迎使用");out.flush();out.close();//write方法——向字符输出流中写数据 PrintWriter out = new PrintWriter(System.out);out.write("欢迎使用");out.flush();out.close();
<!--数据库操作 ->
//javasqlDriverManager——驱动程序管理类 //deregisterDriver方法——删除一个驱动程序 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Driver driver = DriverManager.getDriver(url);DriverManager.deregisterDriver(driver);//getDriver方法——选择一个适当的驱动程序 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Driver driver = DriverManager.getDriver(url);DriverManager.deregisterDriver(driver);//getDrivers方法——获取全部已加载的驱动程序 Class.forName("com.mysql.jdbc.Driver");Enumeration<Driver> em = DriverManager.getDrivers();while (em.hasMoreElements()) {Driver d = em.nextElement();System.out.println(d.getClass().getName());}//getConnection方法——获取数据库连接 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);System.out.println("连接成功");//getLoginTimeout方法——获取连接数据库的等待时间 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);System.out.println(DriverManager.getLoginTimeout());//getLogWriter方法——获取日志的打印输出流 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);PrintWriter out = DriverManager.getLogWriter();if(out != null){out.print("得到信息");out.close();}//println方法——输出日志 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);DriverManager.println("获取驱动成功");//registerDriver方法——注册给定的驱动程序 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Driver driver = DriverManager.getDriver(url);DriverManager.deregisterDriver(driver);DriverManager.registerDriver(driver);//setLoginTimeout方法——设置连接数据库的等待时间 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";DriverManager.setLoginTimeout(10);//setLogWriter方法——设置日志的打印输出流 File file = new File("c:/test.txt");PrintWriter out = new PrintWriter(file);DriverManager.setLogWriter(out);
//javasqlConnection——数据库连接接口 //clearWarnings方法——清除警告信息 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);con.clearWarnings();//close方法——关闭数据库连接对象 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);con.close();//commit方法——提交事务 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);con.setAutoCommit(false);Statement st = con.createStatement();String sql = "insert into users(username,password)values('xiaoli','123456')";st.execute(sql);con.commit();//createBlob方法——构造二进制的对象 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);con.setAutoCommit(true);Blob blob = con.createBlob();//createNClob方法——构造字节字符的对象 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);con.setAutoCommit(true);NClob nclob = con.createNClob();//createSQLXML方法——构造SQLXML对象 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);con.setAutoCommit(true);SQLXML sqlXML = con.createSQLXML();//createStatement方法——创建一个Statement对象 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);con.setAutoCommit(true);Statement st = con.createStatement();//getAutoCommit方法——获取提交模式 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);con.setAutoCommit(true);Statement st = con.createStatement();//getCatalog方法——获取当前目录名称 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);System.out.println(con.getCatalog());//getClientInfo方法——获取客户端信息列表 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Properties props = con.getClientInfo();//getHoldability方法——获取ResultSet对象的可保存性 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);System.out.println(con.getHoldability());//getMetaData方法——获取数据库的元数据 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);DatabaseMetaData metaData = con.getMetaData();//getTransactionIsolation方法——获取事务隔离级别 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);System.out.println(con.getTransactionIsolation());//getTypeMap方法——获取Map对象 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Map<String, Class<?>> map = con.getTypeMap();//getWarnings方法——获取调用报告的第一个警告 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);SQLWarning warning = con.getWarnings();//isClosed方法——判断Connection对象是否被关闭 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);System.out.println(con.isClosed());con.close();System.out.println(con.isClosed());//isReadOnly方法——判断Connection对象是否为只读模式 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);System.out.println(con.isReadOnly());//isValid方法——判断连接是否有效 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);if(con.isValid(10)){System.out.println("连接有效");}//nativeSQL方法——返回SQL语句的本机形式 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select top 10 * from users";System.out.println(con.nativeSQL(sql));//prepareCall方法——调用数据库存储过程 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "{call saveuser(?,?)}";con.prepareCall(sql);//prepareStatement方法——创建一个预处理语句 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users where password = 123456";PreparedStatement ps = con.prepareStatement(sql);//rollback方法——事务回滚 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement st = con.createStatement();con.setAutoCommit(false);st.execute("delete from users where username = 'xiaoli'");con.rollback();//setAutoCommit方法——设置数据库连接的提交模式 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement st = con.createStatement();con.setAutoCommit(false);st.execute("delete from users where username = 'xiaoli'");con.rollback();//setCatalog方法——设置目录名称 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);con.setCatalog("gmy");//setClientInfo方法——设置客户端信息 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Properties props = new Properties();props.setProperty("ClientUser", "root");props.setProperty("ClientHostname", "root");con.setClientInfo(props);//setHoldability方法——设置ResultSet对象的可保存性 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);con.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);//setReadOnly方法——设置连接只读模式 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);con.setReadOnly(true);//setSavepoint方法——创建一个未命名的保存点 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);con.setSavepoint();//releaseSavepoint方法——移除指定的SavePoint示例 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Savepoint sp = con.setSavepoint("spName");con.releaseSavepoint(sp);//setTransactionIsolation方法——设置事务隔离级别 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);int level = Connection.TRANSACTION_SERIALIZABLE;con.setTransactionIsolation(level);//getTransactionIsolation方法——获取事务隔离级别 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);int level = con.getTransactionIsolation();System.out.println(level);
//javasqlStatement——执行SQL语句接口 //addBatch方法——添加批处理语句 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql1 = "insert into users values('aaa','111')";String sql2 = "insert into users values('bbb','111')";String sql3 = "insert into users values('ccc','111')";Statement stmt = con.createStatement();stmt.addBatch(sql1);stmt.addBatch(sql2);stmt.addBatch(sql3);stmt.executeBatch();stmt.close();//cancel方法——中止SQL语句 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();stmt.cancel();//clearBatch方法——清除批处理语句 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql1 = "insert into users values('aaa','111')";String sql2 = "insert into users values('bbb','111')";Statement stmt = con.createStatement();stmt.addBatch(sql1);stmt.addBatch(sql2);stmt.clearBatch();stmt.close();//clearWarnings方法——清除所有警告 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();stmt.clearWarnings();//execute方法——执行SQL语句 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql1 = "insert into users values('ddd','111')";Statement stmt = con.createStatement();boolean bool = stmt.execute(sql1);System.out.println(bool);//executeBatch方法——执行批处理语句 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql1 = "insert into users values('eee','111')";String sql2 = "insert into users values('fff','111')";String sql3 = "insert into users values('ggg','111')";Statement stmt = con.createStatement();stmt.addBatch(sql1);stmt.addBatch(sql2);stmt.addBatch(sql3);stmt.executeBatch();stmt.close();con.close();//executeUpdate方法——执行更新操作 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "delete from users";Statement stmt = con.createStatement();stmt.addBatch(sql);stmt.executeUpdate(sql);stmt.close();con.close();//executeQuery方法——执行查询操作 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery(sql);stmt.close();con.close();//getConnection方法——获取数据库连接对象 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();Connection conn2 = stmt.getConnection();stmt.close();con.close();//getFetchDirection方法——获取从数据库表获取行的方向 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.getFetchDirection());stmt.close();con.close();//getFetchSize方法——获取结果集的行数 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.getFetchSize());stmt.close();con.close();//getGeneratedKeys方法——获取自动生成的键 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();ResultSet rs = stmt.getGeneratedKeys();stmt.close();con.close();//getMaxFieldSize方法——获取最大字节数 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.getMaxFieldSize());stmt.close();con.close();//getMaxRows方法——获取最大行数 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.getMaxRows());stmt.close();con.close();//getMoreResults方法——移动到Statement对象的下一个结果 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();if(stmt.getMoreResults()){System.out.println("下一个对象");}stmt.close();con.close();//getQueryTimeout方法——获取等待执行的秒数 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.getQueryTimeout());stmt.close();con.close();//getResultSet方法——获取结果集 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();String sql = "select * from users";ResultSet rs = stmt.executeQuery(sql);while (rs.next()) {System.out.println(rs.getString(1));}stmt.close();con.close();//getResultSetConcurrency方法——获取结果集并发性 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.getResultSetConcurrency());stmt.close();con.close();//getResultSetHoldability方法——获取结果集可保存性 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.getResultSetHoldability());stmt.close();con.close();//getResultSetType方法——获取结果集类型 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.getResultSetType());stmt.close();con.close();//getUpdateCount方法——获取更新的记录数 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.getUpdateCount());stmt.close();con.close();//getWarnings方法——获取调用报告的第一个警告 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.getWarnings());stmt.close();con.close();//setMaxRows方法——获取最大行数 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();stmt.setMaxRows(20);stmt.close();con.close();//getMaxRows方法——获取最大行数限制值 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.getMaxRows());stmt.close();con.close();//close方法——关闭Statement对象 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();stmt.close();con.close();//isClosed方法——判断Statement对象是否关闭 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.isClosed());stmt.close();System.out.println(stmt.isClosed());con.close();//isPoolable方法——判断对象是否可池化 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();System.out.println(stmt.isPoolable());stmt.close();con.close();//setCursorName方法——设置指针名称 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();stmt.setCursorName("pname");stmt.close();con.close();//setEscapeProcessing方法——设置是否进行转义处理 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();stmt.setEscapeProcessing(true);stmt.close();con.close();//setFetchDirection方法——设置处理行的方向 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();stmt.setFetchDirection(ResultSet.FETCH_FORWARD);stmt.close();con.close();//setFetchSize方法——设置结果集合的最大行数 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();stmt.setFetchSize(50);stmt.close();con.close();//setMaxFieldSize方法——设置可返回的最大字节数 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();stmt.setMaxFieldSize(1000);stmt.close();con.close();//setMaxRows方法——设置最大行数 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();stmt.setMaxRows(20);stmt.close();con.close();//setPoolable方法——设置语句是否可池化 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();stmt.setPoolable(true);stmt.close();con.close();//setQueryTimeout方法——设置等待执行的秒数 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);Statement stmt = con.createStatement();stmt.setQueryTimeout(5);stmt.close();con.close();
//javasqlPreparedStatement——预编译SQL语句接口 //clearParameters方法——立即清除当前参数值 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "update users set username = ? where username= ? ";PreparedStatement ps = con.prepareStatement(sql);ps.setString(1, "ccc");ps.setString(2, "aaa");ps.clearParameters();ps.executeUpdate();con.close();//execute方法——执行SQL语句 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";PreparedStatement ps = con.prepareStatement(sql);boolean bool = ps.execute();System.out.println(bool);con.close();//executeQuery方法——执行SQL查询语句 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";PreparedStatement ps = con.prepareStatement(sql);ResultSet rs = ps.executeQuery();con.close();//executeUpdate方法——执行更新语句 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "insert into users values(?,?)";PreparedStatement ps = con.prepareStatement(sql);ps.setString(1, "ddd");ps.setString(2, "1111");int i = ps.executeUpdate();System.out.println(i);con.close();//getMetaData方法——获取ResultSet对象列的信息 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "insert into users values(?,?)";PreparedStatement ps = con.prepareStatement(sql);ResultSetMetaData rsmd = ps.getMetaData();System.out.println(rsmd.getColumnName(0));con.close();//getParameterMetaData方法——获取参数信息 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "insert into users values(?,?)";PreparedStatement ps = con.prepareStatement(sql);ParameterMetaData pmd = ps.getParameterMetaData();con.close();//setAsciiStream方法——将指定参数设置为给定输入流 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);FileInputStream is1 = new FileInputStream(new File("c:/1.txt"));FileInputStream is2 = new FileInputStream(new File("c:/2.txt"));String sql = "insert into users values(?,?)";PreparedStatement ps = con.prepareStatement(sql);ps.setAsciiStream(1, is1);ps.setAsciiStream(2, is2);ps.executeUpdate();ps.close();con.close();//setBigDecimal方法——设置大数字参数值 //设置大数字参数值//setBinaryStream方法——设置二进制参数值 //设置二进制参数值 //setBlob方法——设置Blob型参数 //设置Blob型参数 //setBoolean方法——设置布尔型参数 //设置布尔型参数 //setByte方法——设置字节型参数 //设置字节型参数 //setBytes方法——设置字节数组型参数 //设置字节数组型参数//setCharacterStream方法——将指定参数设置为给定Reader对象 //将指定参数设置为给定Reader对象 //setClob方法——设置Clob型参数 //设置Clob型参数 //setDate方法——设置日期型参数 //设置日期型参数 //setDouble方法——设置双精度型参数 //设置双精度型参数 //setFloat方法——设置单精度型参数 //设置单精度型参数 //setInt方法——设置整型参数 //设置整型参数//setLong方法——设置长整型参数 //设置长整型参数 //setNCharacterStream方法——将指定参数设置为Reader对象 //将指定参数设置为Reader对象//setNClob方法——设置NClob类型的参数 //设置NClob类型的参数//setNString方法——设置String类型的参数 //设置String类型的参数//setShort方法——设置Short类型的参数 //设置Short类型的参数 //setString方法——设置String类型的参数 //设置String类型的参数//setTime方法——设置时间类型的参数 //设置时间类型的参数//setTimestamp方法——设置参数值为时间戳 //设置参数值为时间戳//setURL方法——设置参数为URL //设置参数为URL
//javasqlResultSet——结果集接口 //absolute方法——将光标移动到指定行 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);boolean b = rs.absolute(5);System.out.println(b);con.close();//afterLast方法——将光标移动到最后一行之后 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);rs.afterLast();con.close();//beforeFirst方法——将光标移动到第一行之前 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);rs.beforeFirst();con.close();//cancelRowUpdates方法——取消对当前行所做的更新 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";PreparedStatement ps = con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);ResultSet rs = ps.executeQuery();if(rs.next()){if(rs.absolute(5)){rs.updateString("username", "abc");rs.cancelRowUpdates();rs.updateRow();}}rs.close();con.close();//clearWarnings方法——清除所有警告 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";PreparedStatement ps = con.prepareStatement(sql);ResultSet rs = ps.executeQuery();rs.clearWarnings();rs.close();con.close();//close方法——关闭ResultSet对象 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";PreparedStatement ps = con.prepareStatement(sql);rs.close();con.close();//deleteRow方法——删除当前行 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";PreparedStatement ps = con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);ResultSet rs = ps.executeQuery();if(rs.next()){rs.deleteRow();}rs.close();con.close();//findColumn方法——获取ResultSet的列索引 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";PreparedStatement ps = con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);ResultSet rs = ps.executeQuery();if(rs.next()){int i = rs.findColumn("username");System.out.println(i);}rs.close();con.close();//first方法——将光标移动到第一行 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);boolean bool = rs.first();System.out.println(bool);rs.close();con.close();//getAsciiStream方法——获取指定列的ASCII字符流的值 //获取指定列的ASCII字符流的值//getBigDecimal方法——获取BigDecimal型的数据 //获取BigDecimal型的数据 //getBinaryStream方法——获取字节流型的数据 //获取字节流型的数据 //getBlob方法——获取Blob型的数据 //获取Blob型的数据 //getBoolean方法——获取布尔型的数据 //获取布尔型的数据//getByte方法——获取字节型的数据 //获取字节型的数据//getBytes方法——获取字节数组的数据 //获取字节数组的数据 //getCharacterStream方法——获取Reader型的数据 //获取Reader型的数据 //getClob方法——获取Clob型的数据 //获取Clob型的数据 //getConcurrency方法——获取并发模式 //获取并发模式//getCursorName方法——获取SQL光标的名称 //获取SQL光标的名称 //getDate方法——获取日期型的数据 //获取日期型的数据//getDouble方法——获取双精度型的数据 //获取双精度型的数据 //getFetchDirection方法——获取方向 //获取方向 //getFetchSize方法——获取ResultSet对象的当前获取大小 //获取ResultSet对象的当前获取大小 //getFloat方法——获取单精度型的数据 //获取单精度型的数据 //getHoldability方法——获取可保存性 //获取可保存性 //getInt方法——获取整型数据 //获取整型数据//getLong方法——获取长整型数据 //获取长整型数据//getMetaData方法——获取对象的列信息 //获取对象的列信息 //getNCharacterStream方法——获取Reader形式的数据 //获取Reader形式的数据//getNClob方法——获取NClob型的数据 //获取NClob型的数据 //getNString方法——获取String型的数据 //获取String型的数据 //getObject方法——获取object型的数据 //获取object型的数据//getRow方法——获取当前行编号 //获取当前行编号 //getShort方法——获取短整型的数据 //获取短整型的数据//getStatement方法——获取Statement对象 //获取Statement对象 //getString方法——获取String类型的数据 //获取String类型的数据 //getTime方法——获取时间型的数据 //获取时间型的数据//getTimestamp方法——获取时间戳 //获取时间戳//getType方法——获取ResultSet对象的类型 //获取ResultSet对象的类型//getURL方法——获取URL对象形式的数据 //获取URL对象形式的数据 //getWarnings方法——获取报告的第一个警告 //获取报告的第一个警告 //insertRow方法——插入当前行到数据库中 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";PreparedStatement ps = con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);ResultSet rs = ps.executeQuery();rs.moveToInsertRow();rs.updateString("username", "fffff");rs.updateString("password", "11111");rs.insertRow();rs.close();con.close();//isAfterLast方法——判断光标是否位于最后一行之后 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);System.out.println(rs.isAfterLast());rs.afterLast();System.out.println(rs.isAfterLast());rs.close();con.close();//isBeforeFirst方法——判断光标是否位于第一行之前 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);System.out.println(rs.isBeforeFirst());rs.next();System.out.println(rs.isAfterLast());rs.close();con.close();//isClosed方法——判断ResultSet对象是否已经关闭 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);System.out.println(rs.isClosed());rs.close();System.out.println(rs.isClosed());con.close();//isFirst方法——判断光标是否位于第一行 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);System.out.println(rs.isFirst());rs.first();System.out.println(rs.isFirst());con.close();//isLast方法——判断光标是否位于最后一行 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);System.out.println(rs.isLast());rs.last();System.out.println(rs.isLast());con.close();//last方法——将光标移动到最后一行 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);rs.last();con.close();//moveToCurrentRow方法——将光标移动到记住的光标位置 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";PreparedStatement ps = con.prepareStatement(sql);ResultSet rs = ps.executeQuery();rs.next();rs.moveToCurrentRow();ps.close();rs.close();con.close();//moveToInsertRow方法——将光标移动到插入行 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";PreparedStatement ps = con.prepareStatement(sql);ResultSet rs = ps.executeQuery();rs.next();rs.moveToInsertRow();rs.updateString("username", "dddd");rs.updateString("passsword", "11111");ps.close();rs.close();con.close();//next方法——将光标从当前的位置向下移动一行 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);while (rs.next()) {System.out.println(rs.getString("username"));}rs.close();st.close();con.close();//previous方法——光标移动到上一行 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);System.out.println(rs.previous());rs.close();st.close();con.close();//relative方法——按相对行数移动光标 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";Statement st = con.createStatement();ResultSet rs = st.executeQuery(sql);rs.relative(2);System.out.println(rs.getRow());rs.close();st.close();con.close();//setFetchDirection方法——设置行的处理方向 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";PreparedStatement ps = con.prepareStatement(sql);ResultSet rs = ps.executeQuery();rs.setFetchDirection(ResultSet.FETCH_FORWARD);rs.close();ps.close();con.close();//setFetchSize方法——设置结果集的最大行数 Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql:///java?username=root&password=root";Connection con = DriverManager.getConnection(url);String sql = "select * from users";PreparedStatement ps = con.prepareStatement(sql);ResultSet rs = ps.executeQuery();rs.setFetchSize(10);rs.close();ps.close();con.close();//updateBigDecimal方法——用BigDecimal值更新指定列 //用BigDecimal值更新指定列 //updateBoolean方法——用boolean值更新指定列 //用boolean值更新指定列 //updateByte方法——用byte值更新指定列 //用byte值更新指定列 //updateBytes方法——用byte数组值更新指定列 //用byte数组值更新指定列//updateDate方法——用Date值更新指定列 //用Date值更新指定列//updateDouble方法——用double值更新指定列 //用double值更新指定列 //updateFloat方法——用float值更新指定列 //用float值更新指定列 //updateInt方法——用int值更新指定列 //用int值更新指定列 //updateLong方法——用long值更新指定列 //用long值更新指定列 //updateNString方法——用String值更新指定列 //用String值更新指定列 //updateNull方法——用null值更新指定列 //用null值更新指定列 //updateRow方法——更新当前行 //更新当前行//updateShort方法——用short值更新指定列 //用short值更新指定列//updateString方法——用String值更新指定列 //用String值更新指定列//updateTime方法——用Time值更新指定列 //用Time值更新指定列 //updateTimestamp方法——用时间戳更新指定列 //用时间戳更新指定列
<!--安全与加密 ->
//javasecurity、Key接口 //getAlgorithm方法——返回当前密钥的算法名称 KeyGenerator generator = KeyGenerator.getInstance("DES");SecretKey key = generator.generateKey();String algorithm = key.getAlgorithm();System.out.println(algorithm);//getEncoded方法——返回当前密钥 KeyGenerator generator = KeyGenerator.getInstance("DES");SecretKey key = generator.generateKey();byte[] encoded = key.getEncoded();//getFormat方法——返回密钥的基本编码格式 KeyGenerator generator = KeyGenerator.getInstance("DES");SecretKey key = generator.generateKey();String format = key.getFormat();System.out.println(format);
//javasecurityKeyPair类 //getPrivate方法——返回对密钥对的私钥组件的引用 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");KeyPair keyPair = keyPairGen.generateKeyPair();PrivateKey key = keyPair.getPrivate();System.out.println(key);//getPublic方法——返回对密钥对的公钥组件的引用 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");KeyPair keyPair = keyPairGen.generateKeyPair();PublicKey key = keyPair.getPublic();System.out.println(key);
//javasecurityKeyPairGenerator类 //generateKeyPair方法——生成一个密钥对 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");KeyPair keyPair = keyPairGen.generateKeyPair();//getAlgorithm方法——返回密钥对生成器算法的标准名称 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");String algorithm = keyPairGen.getAlgorithm();System.out.println(algorithm);//getInstance方法——返回生成指定算法密钥对的KeyPairGenerator对象 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");//initialize方法——初始化密钥对生成器 DHPublicKey dhPublicKey = null;KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");keyPairGen.initialize(dhPublicKey.getParams());
//javasecuritySignature类 //getAlgorithm方法——返回签名对象的算法名称 Signature signature = Signature.getInstance("MD5withRSA");String algorithm = signature.getAlgorithm();System.out.println(algorithm);//getInstance方法——返回实现指定签名算法的Signature对象 Signature signature = Signature.getInstance("MD5withRSA");//initSign方法——初始化当前签名的对象 Signature signature = Signature.getInstance("MD5withRSA");PrivateKey privateKey = null;signature.initSign(privateKey);//initVerify方法——初始化签名验证 Signature signature = Signature.getInstance("MD5withRSA");PrivateKey privateKey = null;signature.initVerify(privateKey);//sign方法——返回已经更新数据的签名 byte[] data = null;PrivateKey privateKey = null;Signature signature = Signature.getInstance("MD5withRSA");signature.initSign(privateKey);signature.update(data);byte[] sign = signature.sign();//update方法——更新要签名或验证的数据 byte[] data = null;PrivateKey privateKey = null;Signature signature = Signature.getInstance("MD5withRSA");signature.initSign(privateKey);signature.update(data);//verify方法——验证签名是否有效 PublicKey publicKey = null;Signature signature = Signature.getInstance("MD5withRSA");signature.initVerify(publicKey);
//javasecuritySecureRandom类 //SecureRandom方法——构造实现默认随机数算法的安全随机数生成器 SecureRandom secureRandom = new SecureRandom();//getSeed方法——返回随机数生成器的种子字节数量 SecureRandom secureRandom = new SecureRandom();byte[] seed = secureRandom.getSeed(5);for (int i = 0; i < seed.length; i++) {System.out.println(seed[i]);}//nextBytes方法——为字节数组生成随机数 SecureRandom secureRandom = new SecureRandom();byte[] by = new byte[5];secureRandom.nextBytes(by);for (int i = 0; i < by.length; i++) {System.out.println(by[i]);}//setSeed方法——重新设置随机对象的种子 SecureRandom secureRandom = new SecureRandom();byte[] by = secureRandom.getSeed(5);secureRandom.setSeed(by);
//javaxcryptoCipher类 //doFinal方法——结束加密或解密的操作 //结束加密或解密的操作 //getAlgorithm方法——返回当前Cipher对象的算法名称 Cipher cipher = Cipher.getInstance("DES");String algorithm = cipher.getAlgorithm();System.out.println(algorithm);//getBlockSize方法——返回块的大小 Cipher cipher = Cipher.getInstance("DES");int blockSize = cipher.getBlockSize();System.out.println(blockSize);//getInstance方法——返回实现指定转换的Cipher对象 Cipher cipher = Cipher.getInstance("DES");//init方法——用密钥初始化当前Cipher对象 Key key = null;Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.DECRYPT_MODE, key);//update方法——继续多部分加密或解密操作 //继续多部分加密或解密操作
//javaxcryptoSecretKeyFactory类 //generateSecret方法——根据密钥规范生成密钥 //根据密钥规范生成密钥//getAlgorithm方法——返回当前SecretKeyFactory对象的算法名称 //返回当前SecretKeyFactory对象的算法名称//getInstance方法——返回转换指定算法秘密密钥的SecretKeyFactory对象 SecretKeyFactory factory = SecretKeyFactory.getInstance("des");Provider provider = factory.getProvider();System.out.println(provider.getInfo());//getProvider方法——返回当前SecretKeyFactory对象的提供者 SecretKeyFactory factory = SecretKeyFactory.getInstance("des");Provider provider = factory.getProvider();System.out.println(provider.getInfo());
<!--网络传输 ->
//javanetInetAddress类 //getByName方法——根据主机名获取InetAddress对象 InetAddress address = InetAddress.getByName("hello");System.out.println(address);//getHostAddress方法——获取IP地址 InetAddress address = InetAddress.getByName("hello");String ip = address.getHostAddress();System.out.println(ip);//getHostName方法——获取主机名称 InetAddress address = InetAddress.getLocalHost();String name = address.getHostName();System.out.println(name);//getLocalHost方法——返回本地主机的InetAddress对象 InetAddress address = InetAddress.getLocalHost();System.out.println(address);
//javanetSocket类 //Socket方法——创建一个客户端套接字Socket对象 InetAddress address = InetAddress.getByName("2013-20160705IB");Socket socket = new Socket(address,7777);//close方法——关闭Socket套接字连接 InetAddress address = InetAddress.getByName("2013-20160705IB");Socket socket = new Socket(address,7777);socket.close();//connect方法——将Socket套接字连接到指定的服务器 SocketAddress address = new InetSocketAddress("hello",1995);Socket socket = new Socket();socket.connect(address);InetAddress addre = socket.getInetAddress();socket.close();//getInetAddress方法——返回Socket套接字连接的地址 SocketAddress address = new InetSocketAddress("hello",1995);Socket socket = new Socket();socket.connect(address);InetAddress addre = socket.getInetAddress();socket.close();//getInputStream方法——返回套接字的输入流 SocketAddress address = new InetSocketAddress("hello",1995);Socket socket = new Socket();socket.connect(address);InputStream stream = socket.getInputStream();socket.close();//getOutputStream方法——返回套接字的输出流 SocketAddress address = new InetSocketAddress("hello",1995);Socket socket = new Socket();socket.connect(address);OutputStream stream = socket.getOutputStream();socket.close();
//javanetServerSocket类 //ServerSocket方法——创建服务器端套接字ServerSocket对象 ServerSocket serverSocket = new ServerSocket(1995);//accept方法——侦听并接受套接字的连接 ServerSocket serverSocket = new ServerSocket(1995);serverSocket.accept();//close方法——关闭当前的服务端套接字ServerSocket连接 ServerSocket serverSocket = new ServerSocket(1995);serverSocket.accept();serverSocket.close();//isClosed方法——返回ServerSocket的关闭状态 ServerSocket serverSocket = new ServerSocket(1995);serverSocket.accept();serverSocket.close();System.out.println(serverSocket.isClosed());
//javanetURL类 //URL方法——使用URL构造方法创建URL对象 URI url = new URI("www.baidu.com");System.out.println(url);//getPort方法——获取当前URL的端口号 URI url = new URI("www.baidu.com");int port = url.getPort();System.out.println(port);//getDefaultPort方法——获取URL使用的当前协议的默认端口号 //获取URL使用的当前协议的默认端口号 //getProtocol方法——获取URL的协议名称 //获取URL的协议名称 //getHost方法——获取当前URL的主机名称 URI url = new URI("www.baidu.com");String host = url.getHost();System.out.println(host);//openConnection方法——返回一个URLConnection对象 //返回一个URLConnection对象 //openStream方法——打开当前URL的连接 //打开当前URL的连接
//javanetURLConnection类 //connect方法——建立通信连接//建立通信连接//getContentLength方法——返回URL连接中的内容长度//返回URL连接中的内容长度//getContentType方法——返回content-type头字段的值//返回content-type头字段的值//getDate方法——返回date头字段的值//返回date头字段的值//getHeaderFields方法——返回投资端中不可修改的信息//返回投资端中不可修改的信息//getInputStream方法——返回URL连接的输入流//返回URL连接的输入流//getOutputStream方法——返回写入的连接的输出流//返回写入的连接的输出流//setDoInput方法——设置当前URLConnection的doInput字段值//设置当前URLConnection的doInput字段值//setDoOutput方法——设置当前URLConnection的doOutput字段值//设置当前URLConnection的doOutput字段值