java程序设计复习章
1. JAVA概述
JAVA语言的特点
- 跨平台性:java源程序被编译后生成的二进制字节码与平台无关,但能被JVM识别。java解释器得到字节码后,对其进行转化,使之能在不同的平台上运行。
- 面向对象:面向对象技术使得应用程序开发变得简单应用,节省代码
- 安全性:java数据结构是完整的对象,这些封装过的数据类型具有安全性; 编译时要进行java语言和语义的检查
- 多线程
- 简单性
- 解释执行
- 分布性
程序编译执行过程
一次编译,到处运行
JVM
- JVM通过在实际的计算机上仿真模拟各种计算机功能来实现
- java程序在不同平台上运行是不用重新编译
- jvm屏蔽看与具体平台相关的信息,只需编译成在jvm上运行的字节码,就能在多种平台上不加修改的运行
2. JAVA基本语法
2.1 程序构成
逻辑构成:
程序头包的引用
类的定义:可用有多个类定义,但是必须有应该主类,包含main方法,作为程序的入口。主类的名字要同文件名一致。
物理构成:
- 语句:一行以分号”;”结尾的语句
- 块:用括号{}界定的语句序列
- 空白
注释语句
标识符、关键字、转义符
标识符:赋予 变量,类,方法等的名称:
myName,My_name,Points,$points,_sys_ta,OK,_23b,_3_
关键字:自带的用于标志数据类型名 或 程序构造名 等的标识,如 public int
转义符:有特殊意义的,很难用一般方法表示 的字符,如 换行 回车
2.2 基本数据类型与表达式
常量 与 变量
基本数据类型:
byte(8 bit) int(32 bit) long(64 bit) char (16 bit) float(32 bit) double(64 bit)
- 文字量:直接出现在程序中并被编译器直接使用的值
- 整数类: 如
long N = 2209050101L
- 浮点类:如果数字包含小数点 或在 数字后带字母F 或 D, 为浮点数。如
3.14f
- 逻辑类:
boolean flag = true;
- 文本类:必须包含单引号(‘ ‘)引用的文字
字符串String及其文字量
String是一个类,如
String animal = "walrus"
字符串文字量:由0个或者多个字符组成,以双引号括起来
2.3 运算符 与 表达式
2.3.1 运算符
算术运算符:
1
+ - * / % ++ --
赋值运算符:
1
= *= /= <<= >>=
关系运算符:类型是boolean
1
2
3
4// 算术比较符
< <= >= >
// 类型比较符
e instanceof Point // Point是一个类逻辑运算符:
1
2
3// 与 &&
// 或 ||
// 非 !条件运算符:
1
2
3
4
5// 表达式1 ? 表达式2 : 表达式3
// 先计算表达式1
// 为true --> 选择表达式2的值
// 为false --> 选择表达式3的值
result = (score>60) ? "通过" : "不通过"位逻辑运算符
1
2
3
4// & 按位 与
// | 按位 或
// ^ 按位 异或(不同为1)
// ~ 按位取反位移运算符
1
2// << 左移 (x<<n 即x乘以2的n次方)
// >> 右移 (x>>n 即x除以。。。。)
2.3.2 类型转换
- 扩展转换:
从一种整数类型 到 另一种整数类型 或 从float到double的转换 不损失任何信息
从整数类型 到double转化 会损失精度
- 窄化转换:
窄化转换可能会丢失信息
赋值转换:
将表达式类型转换为定制变量的类型
方法调用转换:
1
float prc = Float.parseFloat("6.0");
强制转换:
1
(float)5.0
字符串转换:任何类型都可以转换成字符串类型
1
2int x = 5;
x + ""; //转成String不能从Double自动转float
1
2
3float f1 = 1D; //错
float f2 = 1.2; //错
float f3 = 1.2f;宽类型数据 到 窄类型 数据的转换
1
2float = (float) 1D;
float = (float) 1.2;
2.3.3 输入输出流
标准输入流 System.in
1
2byte[] b = new byte(10);
System.in.read(b); // 从输入流中读取字节到b标准输出流
1
System.out.println("hello");
从键盘输入数据,并输出到屏幕
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16package com.tu.chapter1;
import java.util.Scanner;
public class scannnerTest {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner scan = new Scanner(System.in);
String name = scan.next();
int age = scan.nextInt();
scan.close();
System.out.println(name+"\t" + age);
}
}
2.4 流程控制
具体语法不赘述
变量作用域:java循环等代码块内部可以访问到外部的变量 但是外部无法访问 内部的变量。内部的变量是局部的
2.5 数组使用
2.5.1 概念
数组:由同一类型的一连串对象或者基本类型数据组成,封装在一个数组名称下
每个数组都有一个 成员变量 length
2.5.2 声明
声明数组无需指定元素个数,也不用分配空间 int[ ] Array1
或 int Array2[]
必须经过初始化才能使用
2.5.3 创建
通过关键字new构建数组,可以指定类型和元素个数
1 |
|
2.5.4 初始化
若声明数组名时,给出了初始值,程序就会利用初始值创建数组并左初始化
1 |
|
若没有指定处置,数组被赋予默认的初始值
- 基本类型:0
- boolean:false;
- 引用类型:null
2.5.5 引用
方法:arrary[indnx]
元素下标最大值:length-1
数组名 是一个 引用: int[] a1 = {12,45,2}; int[] a2 = a1
此时,a2 与 a1 引用 同一块内存上的数组, 当两者里面有一个修改时,另一个也对应修改了
举例:复制数组(arraycopy(源数组, 起始索引, 目标数组, 目标数组起始索引, 拷贝长度))
1 |
|
2.5.6 多维数组
二维数组:int[][] gradeTable
二维数组构造:
int[][] myarrary = new int[2][3];
int[][] a2 = {{4,2,1,4}, {3,6,7,1}};
二维数组时 引用一维数组的 数组
二维数组的长度:
array.length
值为行数array[i].length
为列数分步构造二维数组:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19int[][] a1;
a1 = new int[3][];
a1[0] = new int[3];
a1[1] = new int[2];
int[] x = {4,1};
int[] y = {2,7,1};
int[] z = {4,6,1};
a1[0] = y;
a1[1] = x;
a1[2] = z;
for(int[] row : a1) {
for(int e : row) {
System.out.print(e + "\t");
}
System.out.println();
}
2.6 作业
统计平均成绩
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25package com.tu.chapter1;
public class work1 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int[] courseID = {1001,2001,3001};
int[][] scores = {{90,79, 96, 88}, {89,91, 78, 90}, {88, 97, 65, 99}};
int i=0;
for(int[] score : scores) {
int sum = 0;
for(int grade : score) {
sum+= grade;
}
double average = (double)sum / score.length;
System.out.println("课程编号为:"+courseID[i]+"的课程的学生平均成绩为:"+average);
i++;
}
}
}输出99乘法表
1
2
3
4
5
6
7
8
9
10
11
12
13
14package com.tu.chapter1;
public class worrk2 {
public static void main(String[] args) {
for(int i=1; i<=9 ; i++) {
for(int j=1; j<=i; j++) {
System.out.print(i +"*" + j + "=" +i*j + "\t");
}
System.out.println();
}
}
}利用公式e=1/0!+1/1! + 1/2! + … + 1/n!,近似计算e的值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23package com.tu.chapter1;
public class work3 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
double res = 1.0;
int n=20;
int temp =1;
for(int i=1; i<=n;i++ ) {
temp *= i;
double now = 1.0/temp;
res += now;
}
System.out.printf("%d次迭代计算出来e的近似值为%.10f", n,res);
}
}该问题叙述如下:“鸡翁一,值钱五;鸡母一,值钱三;鸡雏三,值钱一;百钱买百鸡,则翁、母、雏各几何?”试编程求解之。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23package com.tu.chapter1;
public class work4 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
// 翁(5) 母(3) 雏(1/3)
// 100 钱 100鸡
for(int i=0; i<=100; i++) {
for(int j=0; j<= 100-i; j++) {
// i只翁 j只母 100-i-j只雏
if(( 100-i-j)%3==0 && (5*i + 3*j + (100-i-j)/3 == 100 )) {
int k = 100 -i -j;
System.out.println(i + "只翁" + "\t" + j + "只母\t"+ k + "只雏\t");
}
}
}
}
}将字符串形式的二进制数转换为十进制数值,并返回。例如,“00000101”对应十进制的5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25package com.tu.chapter1;
public class work5 {
public static int Bin2Dec(String binstr) {
// 1010
int res = 0;
for(int i=0; i<binstr.length(); i++) {
char p = binstr.charAt(binstr.length() - i -1);
int c = Integer.parseInt(p+"");
res += Math.pow(2, i) * c ;
}
return res;
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
System.out.println(Bin2Dec("10000010"));
}
}注意
- String取index上的字符 要用 方法
charAt(index)
- char 变 int 两种方法:
int c = Integer.parseInt(p+"");
int c = p - '0';
- pow方法在Math类里面
- String取index上的字符 要用 方法
3. 类与对象
3.1 概述
面向对象程序设计 OOP主要涉及 抽象,封装,继承,多态
- 对象:万物皆对象,都有其标识,属性和行为
- 类:将属性和行为系相同的对象 归为一类,可以看作对象的抽象,每个对象都属于特定的类。
- 抽象:忽略问题中与当前目标无关的方面
- 封装:使用者不必知道行为的实现细节,只需设计者提供的消息来访问对象
- 继承:新的类可以获得已有类的属性和行为
- 多态:不同类的对象可以响应同名的方法,具体实现方式不同
3.2 类与对象
声明方式:
public abstract class class_name extends father_name implements 接口名{}
变量与对象:变量出来能存储基本数据类型的数据外,还可以存储对象的引用
对象的声明:
People p1
;声明一个引用对象时并没用对象生成对象的创建:
p1 = new People();
在内存中为此对象分配内存空间,返回对象的引用。对象数组的创建:
1
2
3
4People[] P = new People[2];
for(int i=0; i<P.length; i++ ){
P[i] = new People();
}
自动装箱拆箱:
1
2Integer i = 3;
int j = i;变量:
实例变量:没用static修饰的变量,用于存储所有实例都需要的属性信息,不同实例的属性值会 不同
类变量:静态变量,需要加static修饰
- 不管类的对象有多少,类变量只有一份,在整个类中只有一个值。静态变量属于类,所有对象都可以访问;而实例变量是仅属于一个对象的
- 类初始化的同时被赋值
- 在类加载时出现,也就是说在对象还没产生式,就已经出现了。
- 适用情况:需要共享的数据
举例:Point类:有两个私有变量保存每个点的坐标,一个类变量保存已有点的个数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31package com.tu.chapter2;
public class Point {
private int x;
private int y;
public static int pointCount = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
pointCount++;
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
System.out.println(Point.pointCount);
new Point(1, 5);
new Point(4,8);
System.out.println(new Point(7,9).pointCount);
}
}
final修饰符:一经初始化 就不可改变
方法成员:
- 定义类的行为
- 分类:
- 实例方法:声明式不加static修饰符,表示特定对象的行为
- 类方法:当方法成员不依赖于具体实例的属性时,可以将其声明为静态方法。用static修饰
- 重载:一个类中名字相同的多个方法;其参数列表不同,返回值可以相同也可以不同,通过方法重载能够使得一个方法接收不同数据类型的数据
- 参数个数不同
- 参数类型不同
- 个数和类型相同,但是顺序不同
3.3 访问控制
类的访问控制:只有public和无修饰符两种; 对无修饰符的类,在不同的包里无法问
类成员的访问控制:公有,受保护的,无修饰的,私有的
对私有数据成员的方法,要设置相应的公有的get和set方法
3.4 包(Package)
- 概念:是一组类的集合,把相关的源代码文件组织在一起,利用包来划分名字空间,提供包级别的封装及存取权限
- 包名:使用小写字母
3.5 对象的初始化与回收
- 实例对象初始化:在系统生成对象时,会为对象分配内存空间,并自动调用 构造方法 对实例变量做初始化。
- 构造方法:一种与类同名的特殊方法:用于初始化类的新对象
- 无返回类型,无void
- 不能再程序里显示调用
- 默认的构造方法,给对象的属性值赋值0或null
- 内存回收技术:系统通过垃圾收集器周期性释放无用对象所使用的内存
3.6 枚举类型
需要一个有限集合,集合中数据为特定值的时候使用枚举类型
1 |
|
3.7 举例 BankAccount类
1 |
|
3.8 例题
定义一个复数类Complex,具有表示虚部和实部的re和im的私有属性及其相应的get/set方法,具有适当的构造方法(包括有参和无参),提供conj()和abs()方法分别用于返回该复数的共轭复数和模,toString( )方法用于返回复数对象形如“1 + 2i”或“1 -2i”的字符串表示, 其中i表示虚数单位。在main( )方法中创建复数x=5-6i和y=3+4i,然后输出它们及其共轭复数和模。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66package com.tu.chapter2;
public class Complex {
private double re;
private double im;
public Complex() {
super();
this.re = 0.0;
this.im = 0.0;
}
public Complex(double re, double im) {
super();
this.re = re;
this.im = im;
}
public double getRe() {
return re;
}
public void setRe(double re) {
this.re = re;
}
public double getIm() {
return im;
}
public void setIm(double im) {
this.im = im;
}
public Complex conj() {
return new Complex(getRe(), -getIm());
}
public double abs() {
return Math.sqrt(Math.pow(getIm(), 2) + Math.pow(getRe(), 2));
}
@Override
public String toString() {
double im = getIm();
if(im > 0) {
return getRe() + "+"+im + "i";
}
else {
return getRe() + "-"+Math.abs(im)+"i";
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Complex x = new Complex(5,-6);
Complex y = new Complex(3,4);
System.out.println("x的共轭复数:"+ x.conj().toString() + " x的模:"+x.abs());
System.out.println("y的共轭复数:"+ y.conj().toString() + " y的模:"+y.abs());
}
}声明一个学生Student及其测试类StudentTester。
① Student类数据成员包括学号、姓名、性别、成绩。学号(从2209050101开始)自动维护且不许外部修改,设计适当的构造方法、数据成员的set/get方法,重写toString方法用于输出学生信息。
② 在StudentTester类中创建一个Student类型的数组,并引用动态创建的若干个Student实例。对学生信息进行设置修改和访问输出。
③ 在StudentTester类中定义一个静态方法printStudents,以表格形式输出学生数组。创建好数组或修改元素后可以调用该方法输出数组,以观察数据变化。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74package com.tu.chapter2;
enum Gender{
Male,
Female;
}
public class Student {
private static long number = 2209050101l;
private long now_number;
private String name;
private Gender sex;
private double grade;
public Student(String name, Gender sex, double grade) {
this.name = name;
this.sex = sex;
this.grade = grade;
now_number = number++;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Gender getSex() {
return sex;
}
public void setSex(Gender sex) {
this.sex = sex;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student [now_number=" + now_number + ", getSex()=" + getSex() + ", getGrade()=" + getGrade() + "]";
}
}
package com.tu.chapter2;
public class StudentTester {
public static void printStudents(Student[] students) {
System.out.println("学号\t\t姓名\t性别\t成绩");
for(Student student : students) {
System.out.println(student.getNow_number() +"\t"+ student.getName() +"\t"+ student.getSex() +"\t"+ student.getGrade());
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Student[] students = new Student[3];
students[0] = new Student("s1", Gender.Female, 98.3);
students[1] = new Student("s2", Gender.Male, 80.3);
students[2] = new Student("s3", Gender.Female, 77.9);
printStudents(students);
// 后续添加 get set方法做测试
}
}
4. 继承、接口和多态
4.1 继承
- 父类是所有子类的公共属性及方法的集合
- 基类(超类)与派生类(子类) 子类 is a 父类
- 子类不能直接访问从父类中继承的私有属性及方法,但可使用公有方法进行访问
- 属性隐藏:
- 子类又声明了与父类中相同的成员变量名,则从父类继承的变量会被隐藏
- 子类执行继承自父类的操作时,处理的是继承自父类的变量;但执行直接自己声明的方法时,所操作的就是它自己声明的变量
- 若要访问被隐藏的父类 属性可使用
super.属性名
- 方法覆盖:
- 子类不需使用从父类继承来的方法,则可以声明自己的同名方法
- 覆盖方法的返回类型,方法名称,参数列表必须一模一样
- final方法:
- 防止任何继承类改变它本来的含义
- 子类的构造方法:
- 子类不能从父类继承构造方法,只可以通过super关键字调用父类构造方法
- 子类没用声明构造方法,系统会执行子类的构造方法时调用父类的无参构造方法,相当于super()
4.2 终结类和终结方法
- 定义:被final修饰的类或方法
- 特性:
- 终结类不能被继承
- 不能被当前类的子类重写
4.3 抽象类与抽象方法
- 抽象类:用abstract修饰的类,代表一个抽象概念的类
- 特性:
- 没有具体实例对象的类,不能用new方法进行实例化
- 可以包含常规类能够包含的东西,如构造方法,非抽象方法
- 也可包含抽象方法(仅有声明,没有实现)
- 抽象方法:抽象类中才可以声明抽象方法
- 声明语法:仅有方法头,无方法体
- 注意:
- 抽象类子类如果不是抽象类,它必须为父类的所有抽象方法书写方法体;否则子类页必须是抽象类。
- 只有抽象类才能又抽象方法
- 优点:当一个抽象类的所有子类都使用同样一个方法时,可能每个子类的行为是不一样的
- 类的组合:类中可以又其他类的对象作为成员, 可以用”has a”描述
4.4 图形类举例
1 |
|
1 |
|
1 |
|
1 |
|
4.5 接口
接口:与抽象类一样定义了多个类的共同属性,是一个“纯”抽象类,只提供了一种形式,不提供实现
与抽象类的异同:
- 接口本质上是一种特殊的抽象类,用于实现多继承;与抽象类都是声明多个类的共同属性
- 接口允许看起来不相干的类之间定义共同行为。而抽象类还是要被其他类共同继承的!相当于 is a 和 like的区别
接口的语法:
interface in1 {public static int const = 3; public abstarct int area();}
- 数据成员必须赋初值,此值不能再更改
- 方法必须是抽象方法,关键字可以省略
对象与接口之间的转型:
对象被转型成 其所属类实现的接口类型 (窄 –> 宽 )
对象转换后接口也可以转回原类 (宽 –> 窄)
Car jetta = new Car(); Insurable item = jetta; // 转成接口类型 (Car)item).getMileage(); //转回原类
1
2
3
4
5
6
7
- 接口的拓展:接口通过扩展的技术派生处新的接口
```java
interface 子接口 extends 父接口1, 父接口2{
加入新接口成员
}
塑型(类型转换):隐式/显式的类型转换
隐式类型转换:
- 基本数据类型:存储容量低的自动向存储容量高的转换
- 引用变量:被塑型为更一般的类或其接口类型
显式类型转换:
- 基本数据类型:(int)871.34, (char)65,
- 引用变量:还原为本来的类型
4.6 多态
多态:不同类型的对象可以响应相同的消息
绑定:一个方法调用同一个方法主体连接到一起
内部类:在一个类或者方法的定义中定义的类,可以访问其外层类中所有数据成员和方法
匿名内部类:
1
2
3
4
5
6
7//new 父类名 或 接口名(){
// 类体
//}
FatherClass f = new FatherClass(){
void showFC(sout("调用了匿名子类重写的父类FatherClass的方法!"));
}
f.showFC();
4.7 带有接口的Shape类
1 |
|
1 |
|
1 |
|
5. 常用Java类库
5.1 Java API
java提供的包主要有:java.lang, java.util, java.io, java.awt, java.swing,java.net
5.2 Object类
Object类式所有类的直接或间接父类,处在类层次最高点
主要方法:
public final Class getClass()
返回Class对象public String toString()
返回当前对象本身的有关信息public boolean equals(Object obj)
比较两个对象是否式同一个对象protected Object clone()
生成当前对象的一个拷贝public int hashCode()
返回该对象的哈希代码值
相等 与 同一 的概念:
- 相等:两个对象具有相同类型,相同属性
- 同一:两个引用变量指向同一个对象
- 两个对象相等,并不一定同一!
- 可以使用“==”判断这两个对象是否同一
equals方法
Object类中定义:
1
2
3public boolean equals(Object x){
return this == x;
}equals重写(只需判断两个对象各个属性域的值是否相同)
1
2
3
4
5
6
7
8public boolean equals(Object x){
if(this.getClass() != x.getClass()){
return false;
}
Circle b = (Circle)x;
return this.getRadius() == b.getRadius();
}
clone方法
根据已存在的对象构造一个新的对象,覆盖为public,要实现接口Cloneable里的Clone方法
代码示例:
1
2
3
4
5
6public class Circle implements Cloneable{
public Obejct Clone() throws CloneNotSupportedException{
return this.clone();
}
}浅拷贝与深拷贝:浅拷贝是两者引用一个对象。深拷贝是创建了一个新对象
getClass方法
final方法,返回一个Class对象,通过这个对象可以查询Class的各种信息,如getName, getSuperClass, getInterfaces
1
2
3
4void PrintClassInfo(Object obj){
sout("The Object's class is "+ obj.getClass().getName());
sout("The Object's super class is "+ obj.getClass().getSuperclass().getName());
}
5.3 语言包(java.lang)
语言包中提供了java最基础的类,包括数据类型包装类,字符串类,数学类,系统和运行类,类操作类
数据类型包装类:基本数据类型都有一个数据包装类,为final类型
生成数据类型包括类对象的方法
基本类型 生成包装类对象:
1
Double b = new Double(1.23);
从字符串生成包装类对象:
1
2Integer i =new Integer("1234");
Double e = new Double("-34.5");已知字符串对象,使用valueOf方法将其转成包装类对象:
1
Integer.valueOf("125");
自动装箱:
1
Inteher i = 3;
得到基本数据类型数据的方法
int c = Integer.parseInt("234");
1
2
3
4
- ```java
Integer a = new Integer(3);
int i = a;
常量字符串String类
常量字符串:String字符串的值和长度都不可变
生成String类对象的方法:
String aString = "This is a string";
1
2
3
4
5
- ```java
String c = new String("dhk");
char[] cc = {'a', 'c'};
String c2 = new String(cc) ;
常用方法:
返回字符串里字符个数
1
2String s = "abcd"
int len = s.length();返回序号index处的字符
1
char c = s.charAt(1);
在原字符串值查找是否包含子字符串s1, 如果包含,返回匹配的第一个字符的位置序号,否则返回-1
1
int index = s.indexOf("bc");
返回接收者对象中从begin开始到end-1的子字符串
1
String s1 = s.subString(0, 3);
以指定字符为分隔符,分割字符串
1
2String[] ss = s.split(" ");//以空格划分
// split("//.") 以"."分割拼接字符串
1
String s = s.concat("sf4f");
把原字符替换成新字符
1
s.repalce('a', 'b');
把字符串两端空字符串去掉
1
s.trim();
转大/小写
1
2s.toLowerCase();
s.toUpperCase();
使用正则表达式拆分和替换字符串
基本方法
1
2
3
4
5String s = "AA,BB CC:DD";
String[] words = s.split("[, :]");
for(String word : words){
System.out.println(word);
}使用正则表达式包util.regex匹配字符串
1
2
3
4
5
6// Pattern对象,其matches方法用于字符串形式的模式匹配目标字符串
Pattern p = Pattern.compile("^[1-9]\\d{5}$");// ^开始 [1-9]的单个数字 \\d十进制的整数 {5}重复5次 $结束
Matcher m = p.matcher("266580");
System.out.println(m.matches());
System.out.println(Pattern.matches("^[1-9]\\d{5}$", "018374"));1
2
3
4
5
6// . 匹配任意一个字符
// \d 匹配一个或多个数字
// \. 匹配"."
// (\d)? ?表示括号内的选项是可选的
// \s+ 可以匹配多个空格
// 在 Java 中正则表达式中则需要有两个反斜杠才能被解析为其他语言中的转义作用
可变字符串StringBuffer类
可变字符串,其字符个数叫做对象的长度length,其分配的存储空间称为对象的容量capacity
StringBuffer sb = new StringBuffer(); String s = null; String s2 = "ccc"; sb.append("aaa"); ab.append(s); sb.append(s2); sb.append("bbb"); System.out.println(sb); // aaanullaaabbb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- 常用方法
```java
StringBuffer sb = new StringBuffer("aab");
System.out.println("length: "+ sb.length());
System.out.println("capacity: "+ sb.capacity());
char c = sb.charAt(2);
sb.setCharAt(0, 'v');//将index位置的字符设置为
System.out.println(sb);
char[] cc = new char[10];
sb.getChars(0, 3, cc, 0); //把原字符串的从0到2位置的字符拷贝到cc中
System.out.println(cc);
StringBuffer ss =sb.insert(0,"ab" );
System.out.println(ss);
StringBuffer ss1 = sb.append(ss);
System.out.println(ss1);已知一个字符串,返回将字符串中的非字母字符都删除后的字符串
1
2
3
4
5
6
7
8
9
10String aBuffer = new StringBuffer(original.length());
char ch;
for(int i=0; i<original.length(); i++){
ch = original.charAt(i);
if(Character.isLetter(ch)){
aBuffer.append(ch);
}
}
return new String(aBuffer);
数学Math类
1
2
3
4
5
6
7
8
9
10
11
12
13Math.E;
Math.PI;
Math.sqrt(4,2); //对4开方
Math.pow(x, n);
Math.sin()/cos/asin/acos/sinh/cosh;
Math.min/max();
Math.exp(x);
Math.log(x);
Math.round/ceil/floor();
Math.random();
System类
1
2arrarycopy();//复制一个数组
currentTimeMillis();//获取系统当前日期和时间
5.4 实用包(java.util)
StringTokenizer, Scanner, 集合类,日期类
StringTokenizer:允许以某种分隔标准将字符串分割成单独子字符串
1
2
3
4
5
6String str = "数学::英语::语文::化学";
StringTokenizer st = new StringTokenizer(str, "::");//默认是按空白格分割
int n = st.countTokens();
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}Scanner:文本扫描器
1
2
3
4
5
6
7
8
9
10
11
12// 从键盘输入
String name; int age;
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
name = scan.next();
if(name.toUpperCase().equals("Q")){
break;
}
age = scan.nextInt();
}
scan.close();Vector
类:向量中元素必须为引用类型 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35Vector<String> v = new Vector<String>();
// 添加元素
v.addElement("wendy");
v.add("Frank");
System.out.println(v);
v.insertElementAt("Andy", 1);//在1位置插入,后面的元素往后移
System.out.println(v);
// 删除元素
v.remove(0);
System.out.println(v);
//v.removeAllElements();//移除所有元素
// 修改元素
v.setElementAt("Lain", 1);
System.out.println(v);
String s = v.set(0, "Paul");//i修改0位置的元素,返回被替代的元素
System.out.println(v);
System.out.println(s);
//访问元素
String s1 = v.elementAt(0);
System.out.println(s1);
String s2 = v.get(0);
System.out.println(s2);
String s_first = v.firstElement();
String s_end = v.lastElement();
boolean flag = v.isEmpty();
boolean is_contain = v.contains("wendy");
System.out.println(is_contain);
// 查找向量中的元素
int index1 = v.indexOf("Paul");
int index2 = v.indexOf("Paul",1);
System.out.println(index1 + "\t" + index2);Enumeration接口
1
2
3
4
5
6Vector<String> v1 = new Vector<String>();
v1.add("ab"); v1.add("vb"); v1.add("tu");
Enumeration<String> e = v1.elements();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}Iterator接口
1
2
3
4
5
6Vector<String> v1 = new Vector<String>();
v1.add("ab"); v1.add("vb"); v1.add("tu");
for(Iterator<String> e = v1.iterator(); e.hasNext(); ){
c=e.next();
System.out.println(c);
}ArrayList类
1
2
3
4
5
6
7
8
9
10
11ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println(list.size());
list.add(5);//在末尾添加元素
list.add(0,8);//在0索引处加元素
list.add(3);
System.out.println(list);
list.remove(1);//移除第2个元素
System.out.println(list);
int ele = list.get(0);
int e1 = list.set(0, 88);
System.out.println(list);Comparable接口和Comparator接口
Comparable接口用于定义对元素做自然排序的方法
int compareTo(T o)
,在元素所属类中实现1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68package com.tu.chapter4;
import java.util.ArrayList;
import java.util.Collections;
public class Circle implements Comparable<Circle> {
private float r;
public Circle(float r) {
super();
this.r = r;
}
public float getR() {
return r;
}
public void setR(float r) {
this.r = r;
}
@Override
public String toString() {
return "Circle [r=" + r + "]";
}
@Override
public int compareTo(Circle o) {
// TODO 自动生成的方法存根
// 从小到大排序
if(this.r > o.r) {
return 1;
}
else if(this.r == o.r) {
return 0;
}
else {
return -1;
}
//return Double.compare(this.r, o.r);
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
ArrayList<Circle> list = new ArrayList<Circle>();
list.add(new Circle(5));
list.add(new Circle(9));
list.add(new Circle(1));
list.add(new Circle(3));
System.out.println(list);
// 自然排序后:
Collections.sort(list);
System.out.println(list);
}
}Comparator接口:定义强行对某个对象collection进行整体排序的比较器,实现
int compare(T o1, T o2)
, 做定制排序1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41package com.tu.chapter4;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Circle_Comparator implements Comparator<Circle>{
public static void main(String[] args) {
// TODO 自动生成的方法存根
ArrayList<Circle> list = new ArrayList<Circle>();
list.add(new Circle(5));
list.add(new Circle(9));
list.add(new Circle(1));
list.add(new Circle(3));
System.out.println(list);
Circle_Comparator comparator = new Circle_Comparator();
Collections.sort(list, comparator);
System.out.println(list);
}
@Override
public int compare(Circle o1, Circle o2) {
// TODO 自动生成的方法存根
return Double.compare(o1.getR(), o2.getR());
}
}或者
1
2
3
4
5
6Collections.sort(list, new Comparator<Circle>() {
@Override
public int compare(Circle o1, Circle o2) {
return Double.compare(o1.getR(), o2.getR());
}
});或者
1
Collections.sort(list, (o1, o2)->Double.compare(o1.getR(), o2.getR()));
Collections类:提供静态方法,反转,排序,获得最大最小元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17Vector<Integer> v = new Vector<Integer>();
v.add(5);
v.add(7);
v.add(9);
v.add(4);
System.out.println(Collections.max(v));
Collections.reverse(v);
System.out.println(v);
// 升序
Collections.sort(v);
System.out.println(v);
// 降序 (先升序后再翻转列表)
Collections.reverse(v);
System.out.println(v);Arrays类:操作普通数组,排序,搜索
1
2
3
4
5
6
7
8int []a = { 5,9,1,6};
Arrays.sort(a);
for(int x : a) {
System.out.println(x);
}
int index = Arrays.binarySearch(a, 6);
System.out.println(index);Date类:获取系统当前日期和时间值
1
2
3
4
5
6Date date1 = new Date();
System.out.println(date1.toString());
long time1 = date1.getTime(); //以ms为单位
System.out.println(time1);
System.out.println(date1.after(new Date(time1+5)));Calendar类:能将date对象转换成一系列单个的日期整形数据集,如YEAR,MONTH,DAY,HOUR等常量
1
2
3
4
5
6Calendar time = new GregorianCalendar();
System.out.println(time.getTime());//返回Date对象,显示日历
System.out.println(time.get(Calendar.YEAR));//获取特定对象信息
System.out.println(time.get(Calendar.DAY_OF_WEEK));
time.add(Calendar.MONTH, -4); //从当前日期减去4个月
System.out.println(time.getTime());
5.5 文本包(java.text)
添加String.format的用法
+ 为整数或者负数添加符号,
%+d
- 左对齐,
%-5d
0 数字前补0,
"%04d", 99
0099空格 在整数之前添加指定数量空格,
"% 4d", 99
| 99|, 以“,”对数字分组,
"%,f", 9999.99
9.999.990000. 在小数点后规定多少个数字,
"%.2f", 99.45224
int n = 46; System.out.println(String.format("%#o", n)); // 056 System.out.println(String.format("%#x", n)); // 0x2e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
## 5.6 例题
**建立两个类及并进行相应测试:**
**① 建立一个学生类Student,数据成员包括学号、姓名、性别,成绩等,方法成员包括构造方法、set/get方法、toString( )方法等。**
**②** **建立一个管理学生对象的类StudentManager。在其中定义向量(或列表)成员,用于存储学生对象;提供若干方法,分别用于向量(或列表)进行学生对象的 ** 插入、移除、修改、排序(按成绩升序)、浏览、查找(按姓名)、统计人数等操作。请对这些方法进行必要的测试,其中,查找到某个学生后将其成绩修正为99分。
```java
package com.tu.chapter4;
enum Sex{
Female, Male;
}
public class Student {
private int number;
private static int Fixnumber = 000001;
private String name;
private Sex sex;
private double grade;
public Student( String name, Sex sex, double grade) {
super();
this.name = name;
this.sex = sex;
this.grade = grade;
this.number = Fixnumber++;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Sex getSex() {
return sex;
}
public void setSex(Sex sex) {
this.sex = sex;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student [number=" + String.format("%1$06d", number) + ", name=" + name + ", sex=" + sex + ", grade=" +grade + "]";
}
}
package com.tu.chapter4;
import java.util.Collections;
import java.util.Vector;
public class StudentManager {
private Vector<Student> v;
public StudentManager() {
super();
v = new Vector<Student>();
}
// 插入
public void add(Student stu) {
v.add(stu);
}
// 移除1
public Student remove(int i) {
int len = v.size();
if(i > len - 1 || i<= -1) {
return null;
}
else {
v.remove(i);
return v.elementAt(i);
}
}
// 移除2
public Student remove(Student stu) {
boolean res = v.remove(stu);
if(res) {
return stu;
}
else {
return null;
}
}
// 获取i
public Student get(int i) {
int len = v.size();
if(i > len - 1 || i<= -1) {
return null;
}
else {
return v.elementAt(i);
}
}
// 修改
public void set(int i, Student stu) {
int len = v.size();
if(i > len - 1 || i<= -1) {
System.out.println("超出索引,无法修改i位置的元素");
}
else {
v.setElementAt(stu, i);
}
}
// 按照成绩升序
public void sort() {
Collections.sort(v, (s1,s2)->Double.compare(s1.getGrade(), s2.getGrade()));
}
// 浏览
public void display() {
System.out.println("姓名\t学号\t性别\t成绩");
for(Student stu : v) {
System.out.println(stu.getName()+"\t"+String.format("%1$06d", stu.getNumber()) + "\t" + stu.getSex()+ "\t" + stu.getGrade());
}
}
// 按姓名查找
public Student search(String name) {
for(Student stu : v) {
if(stu.getName() == name) {
return stu;
}
}
return null;
}
//统计人数
public int size() {
return v.size();
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
StudentManager sm = new StudentManager();
sm.add(new Student("wendy", Sex.Female, 99));
sm.add(new Student("Mike", Sex.Male, 93));
sm.add(new Student("Paul", Sex.Male, 96));
sm.add(new Student("Mike", Sex.Female, 90));
sm.display();
// 找个某个学生,修正成绩为99
Student s1 = sm.search("wendy");
System.out.println(s1);
s1.setGrade(99);
sm.display();
}
}
6. 异常处理
6.1 简介
- 异常:java中声明了很多异常类,每个异常类都代表一种运行错误,类中包含该运行错误的信息及其获取方法
- 处理异常的机制:
- 抛出throw:如果发生了异常,该方法生成一个代表该异常的对象并把他交给运行时系统,运行时系统便寻找相应代码处理
- 捕获catch:从生成异常的方法开始进行回溯,知道找到包含相应异常处理的方法为之。
6.2 异常处理方法
声明抛出异常:如果不想再当前方法内处理异常,可以使用throws子句声明将异常抛出到调用方法中。
1
2
3
4static void func()throws FileNotFoundException {
String fn = "java.txt";
FileInputStream fs = new FileInputStream(fn);
}捕获异常:try{}catch(E e){}
1
2
3
4
5
6
7
8
9
10
11
12
13try {
System.out.println("Enter the first number:");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int x = Integer.valueOf(br.readLine());
System.out.println("Enter the next number:");
int y = Integer.valueOf(br.readLine());
}catch(NumberFormatException | IOException e) {
System.out.println("Those are not proper Integers");
System.exit(-1);
}
7. IO流与文件读写
7.1 File类
File类:表示一个文件,目录,或一个文件和目录的组合,用于获取文件,目录的各种信息,并对其进行管理
// 文件的获取 File file = new File("Doc", "学校简介.txt"); if(file.exists()) { System.out.println("文件名:"+ file.getName()); System.out.println("绝对路径:"+ file.getAbsolutePath()); System.out.println("文件路径:"+ file.getPath()); System.out.println("大小:"+ file.length()+ " 字节"); } else { System.out.println("文件路径不存在"); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- ```java
// 获取目录下的子目录和文件信息
File dir = new File("Doc");
String dirs="",files="";
File[] list = dir.listFiles();
for(File f : list) {
if(f.isFile()) {
files += "\t" + f.getName() + "\n";
}
else {
dirs += "\t" + f.getName() + "\n";
}
}
System.out.println(dir.getAbsolutePath() + "下的目录:"+dirs );
System.out.println(dir.getAbsolutePath() + "下的文件:"+files);
7.2 I/O流
I/O流:信息的输入和输出;
一个流就是一个从源流向目的地的数据序列
输入流:程序打开一个输入流,程序可从输入流读取数据
输出流:打开一个输出流,程序通过输出流向这个目标位置写信息
读写数据方法:打开一个流 —> 从流中读取信息/将信息写入流 –> 关闭流
分类:
- 面向字符的流:专门用于字符数据 FileReader/FileWriter
- 面向字节的流:用于一般目的,读写图片,声音等二进制的数据 InputStream/OutputStream
标准输入输出流:
- System.in:InputStream类型,代表标准输入流,默认状态对于键盘输入
- System.out:PrintStream类型,代表标准输出流,对于屏幕输出
举例:从键盘读入信息并显示
1
2
3
4
5
6
7BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
while(s.length() !=0) {
System.out.println(s);
s = br.readLine();
}
br.close();
文本文件读写:
FileWriter类(父类时 OutputStreamWriter):将字符按默认的字符集写入文件
1
2
3
4
5
6String fName = "Doc\\Hello.txt";
FileWriter fw = new FileWriter(fName);
fw.write("Hello!\n");
fw.write("This is my first text file.\n");
fw.write("你好,世界!\n");
fw.close();BufferedWriter类(把OutputStreamWriter包装到BufferedWriter中,避免频繁调用转换器)
1
2
3
4
5
6
7String fName = "Doc\\Hello1.txt";
BufferedWriter bw = new BufferedWriter( new FileWriter(fName));
bw.write("Hello!");
bw.newLine();
bw.write("This is my first text file.\n");
bw.write("你好,世界!\n");
bw.close();FileReader类:从文件读取字符
BufferedReader类:给输入字符流增加一个内部缓冲区,实现高效读取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15String fName = "Doc\\Hello1.txt";
try {
BufferedReader br = new BufferedReader(
new FileReader(fName));
String line = br.readLine();// int ch = br.read();逐个字符读取,返回Unicode编码
while(line != null){
System.out.println(line);
line = br.readLine();
}
br.close();
}catch(IOException e) {
System.out.println(e.getMessage());
}文本文件的复制:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15String source = "Doc\\学校简介.txt", des= "Doc\\\\学校简介_copy.txt", line;
try {
BufferedReader br= new BufferedReader(new FileReader(source));
BufferedWriter bw = new BufferedWriter(new FileWriter(des));
line = br.readLine();
while(line != null) {
bw.write(line);
bw.newLine();
line = br.readLine();
}
br.close();
bw.close();
}catch(IOException e) {
e.getMessage();
}
二进制文件读写
写入文件
OutputStream(输出字节流):
FileOutputStream(文件输出字节流):wtrite(byte[] b, int off, int len)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17String fName = "Doc\\\\Hello.txt", line="";
try {
FileOutputStream fos = new FileOutputStream(fName);
line = "Hello!\r\n";
fos.write(line.getBytes());
line = "你好!\r\n";
fos.write(line.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}OutputStreamWriter与FileOutputStream写文本文件(可指定字符编码方式)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19BufferedWriter bw;
try {
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fn), "UTF-8"));
bw.write("中国石油大学(华东");
bw.newLine();
bw.write("1953-2024");
bw.close();
} catch (UnsupportedEncodingException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}DataOutputStream(数据输出流,将基本类型数据转成字节流),BufferedOutputStream(对输出流进行缓冲)
读取文件
1
2
3
4
5
6
7
8
9
10String fn = "Doc//upc.txt";
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(fn), "UTF-8"));
String line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
7.3 例题
文本文件的读写(BufferedReader 做缓冲,FileReader读入)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15String source = "Doc\\学校简介.txt", des= "Doc\\\\学校简介_copy.txt", line;
try {
BufferedReader br= new BufferedReader(new FileReader(source));
BufferedWriter bw = new BufferedWriter(new FileWriter(des));
line = br.readLine();
while(line != null) {
bw.write(line);
bw.newLine();
line = br.readLine();
}
br.close();
bw.close();
}catch(IOException e) {
e.getMessage();
}二进制文件读写(BufferedInputStream + FileInputStream)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17String source = "Doc\\学校简介.txt", des= "Doc\\\\学校简介_copy.txt", line;
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(des));
byte[] buffer =new byte[1024];
int len;
while((len = bis.read(buffer))!= -1){
bos.write(buffer, 0, len);
}
bos.close();
bis.close();
System.out.println("复制成功");
}catch(Exception e) {
e.getMessage();
}BufferedReader + InputStreamReader+FileInputStream + 指定编码方式
1
2
3
4
5
6
7
8
9
10
11
12
13try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(source), "UTF-8"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(des), "UTF-8"));
while((line = br.readLine())!= null) {
System.out.println(line);
bw.write(line);
bw.newLine();
}
bw.close();
br.close();
}catch(Exception e) {
e.getMessage();
}
8. 基于Swing的图形用户界面
8.1 Swing容器
Swing组件归为三个层次:
- 顶层容器:表示一个窗体、对话框或applet显示区域,有一个内容面板(contentPane)用于容纳中间中层容器和基本组件
- 中间层容器:容纳其他组件,JPanel,JScrollPane
- 原子组件(基本组件):直接向用户展示信息或获取用户输入JButton,JLabel,JTextField,JCheckBox
Swing容器
顶层容器窗体类JFrame:可设置窗体Title, 位置,大小,默认关闭操作,添加组件
顶层窗体对话窗体类JDialog
中间层容器面板类JPanel:燃原子组件和组件层面板,作为一个整体加入JFrame等顶层容器里,可设置绝对布局
中间层容器滚动面板类JScrollPane:用于滚动显示面板里的组件,如滚动显示文本区域,只允许加入一个组件;若有多个组件,先将他们放入一个JPane里,如何把JPane放入JScrollPane
(做 记事本: JScrollPane + TextArea)
8.3 原子组件
JButton
JRadioButton:有选中和未选中两种状态,吧多个单选按钮添加在一个按钮组ButtonGroup(用户只能选择一个)
JCheckBox:多选
JComBox:组合框,文本框与下拉列表组合的组件
1
2
3
4
5
6
7
8
9String[] schools = {"中国石油大学","中国地质大学","中国海洋大学"};
comboBox_1 = new JComboBox<String>(schools);
comboBox_1.setBounds(79, 196, 32, 21);
contentPane.add(comboBox_1);
//方法
getSelectedItem();
getSelectedIndex();
JList列表类(可一次多选)
需要JSCrollPane+JList
1
2
3
4
5
6
7
8
9crollPane = new JScrollPane();
scrollPane.setBounds(314, 153, 88, 40);
contentPane.add(scrollPane);
list_1 = new JList();
list_1.setListData(schools);
scrollPane.setViewportView(list_1);
// getSelectedValues()返回所有选择项
// getSelectedValue() 返回第一个选择项TextArea 文本框 (一般是JSCrollPane+ta)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27ta.setForeground(Color.BLACK);
Document doc = ta.getDocument();
doc.addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
setTitle(APP_NAME + "-" + file + "(*)");
isTextModified = true;
}
}
StringBuffer sb = new StringBuffer("");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String str = br.readLine();
while(str != null) {
sb.append(str + "\n");
str = br.readLine();
}
if(sb.length() > 0) sb.deleteCharAt(sb.length()-1);
br.close();
ta.setText(sb.toString());
setTitle(APP_NAME+"-"+file);
isTextModified = false;
}catch(Exception e1) {
e1.getMessage();
}
8.3 菜单
- 菜单栏JMenuBar + 多个菜单JMenu + 每个餐单的选项JMenuItem
- 弹出式菜单:JPopupMenu
8.4 对话框
标准对话框:
showConfirmDialog 显示确认对话框,询问有关确认问题,如yes/no/canel
1
2
3
4
5
6
7
8
9
10
11this.addWindowListener(new WindowAdapter(){
public void windowColsing(WindowEvent e) {
JFrame frm = (JFrame)e.getWindow();
int resultDlg = JOptionPane.showConfirmDialog(frm, "确定要退出程序吗?","操作确认", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(resultDlg == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
showMessageDialog:显示一个消息对话框,告知用户某事已发生
1
JOptionPane.showMessageDiaglog(JFrame, "输入用户名和密码不正确,请重试!", "系统提示",JOptionPane.ERROR_MESSAGE );
showInputDialog:
文件选择器JFileChooser
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30JFileChooser fc = new JFileChooser();//文件选择器
FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文件(*.txt)", "txt");
fc.addChoosableFileFilter(filter);
filter = new FileNameExtensionFilter("HTML文件(*.htm,*.html)", "htm", "html");
fc.addChoosableFileFilter(filter);
int returnVal = fc.showOpenDialog(null);
if(returnVal != JFileChooser.APPROVE_OPTION) {
return ;
}
String filename = fc.getSelectedFile().getAbsolutePath();
StringBuffer sb = new StringBuffer("");
try {
BufferedReader br = new BufferedReader(
new FileReader(filename));
String str = br.readLine();
while(str!=null) {
sb.append(str+"\n");
str = br.readLine();
}
br.close();
ta.setText(sb.toString());
setTitle(APP_NAME + "-" + filename);
isTextModified = false;
}catch(Exception e1) {
ta.setText(e1.getMessage());
}颜色选择器JColorChooser
1
2
3
4Color color = JColorChooser.showDialog(ta, "请选择颜色", Color.RED);
if(color != null){
ta.setForeground(color);
}
8.5 例题
计算器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17double num = Double.parseDouble(t1.getText());
//num = Math.toRadians(num);//变弧度
num = num * Math.PI / 180 ;
if(method == "正弦") {
res = Math.sin(num);
}
else if(method == "余弦") {
res = Math.cos(num);
}
else if(method == "正切") {
res = Math.tan(num);
}
else {
res = 1 / Math.tan(num);
}
t2.setText(String.format("%.4f", res));简易文本编辑器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298public class JMenu_Tester extends JFrame {
public JMenu_Tester() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
// 退出窗体
this.addWindowListener(new WindowAdapter(){
public void windowColsing(WindowEvent e) {
JFrame frm = (JFrame)e.getWindow();
int resultDlg = JOptionPane.showConfirmDialog(frm, "确定要退出程序吗?","操作确认", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(resultDlg == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
menuBar = new JMenuBar();
setJMenuBar(menuBar);
mnNewMenu = new JMenu("\u6587\u4EF6");
menuBar.add(mnNewMenu);
mntmNewMenuItem = new JMenuItem("\u6253\u5F00"); //打开文件
mntmNewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = new JFileChooser();//文件选择器
FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文件(*.txt)", "txt");
fc.addChoosableFileFilter(filter);
filter = new FileNameExtensionFilter("HTML文件(*.htm,*.html)", "htm", "html");
fc.addChoosableFileFilter(filter);
int returnVal = fc.showOpenDialog(null);
if(returnVal != JFileChooser.APPROVE_OPTION) {
return ;
}
filename = fc.getSelectedFile().getAbsolutePath();
StringBuffer sb = new StringBuffer("");
try {
BufferedReader br = new BufferedReader(
new FileReader(filename));
String str = br.readLine();
while(str!=null) {
sb.append(str+"\n");
str = br.readLine();
}
br.close();
ta.setText(sb.toString());
setTitle(APP_NAME + "-" + filename);
isTextModified = false;
}catch(Exception e1) {
ta.setText(e1.getMessage());
}
}
});
menuItem_11 = new JMenuItem("\u65B0\u5EFA"); // 新建文件
menuItem_11.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(isTextModified) {
int result = JOptionPane.showConfirmDialog(null, "文档未保存,是否新建?", "新建确认", JOptionPane.YES_NO_OPTION);
if(result == JOptionPane.YES_OPTION) {
ta.setText("");
filename = null;
setTitle("简易文本编辑器");
}
}
else {
ta.setText("");
filename = null;
isTextModified = false;
setTitle("简易文本编辑器");
}
}
});
mnNewMenu.add(menuItem_11);
mnNewMenu.add(mntmNewMenuItem);
menuItem = new JMenuItem("\u4FDD\u5B58"); //保存文件
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(filename != null) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
bw.write(ta.getText());
bw.close();
//textArea.setText("文件已保存");
setTitle(APP_NAME + "-" + filename);
isTextModified = false;
}catch(Exception e2) {
ta.setText(e2.getMessage());
}
}
else {
JFileChooser fileChooser = new JFileChooser();
if(fileChooser.showSaveDialog(menuItem) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(ta.getText());
bw.close();
//textArea.setText("文件已保存");
setTitle(APP_NAME + "-" + filename);
isTextModified = false;
}catch(Exception e2) {
ta.setText(e2.getMessage());
}
}
}
}
});
mnNewMenu.add(menuItem);
menuItem_7 = new JMenuItem("\u53E6\u5B58\u4E3A");//另存为
menuItem_7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();//文件选择器
FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文件(*.txt)", "txt");
fc.addChoosableFileFilter(filter);
filter = new FileNameExtensionFilter("HTML文件(*.htm,*.html)", "htm", "html");
fc.addChoosableFileFilter(filter);
int returnVal = fc.showOpenDialog(null);
if(returnVal != JFileChooser.APPROVE_OPTION) {
return ;
}
String filename1 = fc.getSelectedFile().getAbsolutePath();
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(filename1));
bw.write(ta.getText());
bw.close();
}catch(Exception e3) {
e3.getMessage();
}
}
});
mnNewMenu.add(menuItem_7);
separator = new JSeparator();
mnNewMenu.add(separator);
menuItem_1 = new JMenuItem("\u9000\u51FA"); //退出
menuItem_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int resultDlg = JOptionPane.showConfirmDialog(null, "确定要退出程序吗?","操作确认", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(resultDlg == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
mnNewMenu.add(menuItem_1);
mnNewMenu_1 = new JMenu("\u7F16\u8F91");
menuBar.add(mnNewMenu_1);
menuItem_2 = new JMenuItem("\u590D\u5236");//复制
menuItem_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ta.copy();
}
});
mnNewMenu_1.add(menuItem_2);
menuItem_3 = new JMenuItem("\u7C98\u8D34");//粘贴
menuItem_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ta.paste();
}
});
mnNewMenu_1.add(menuItem_3);
menuItem_4 = new JMenuItem("\u526A\u5207"); //剪切
menuItem_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ta.cut();
}
});
mnNewMenu_1.add(menuItem_4);
menuItem_5 = new JMenuItem("\u6E05\u7A7A"); // 清空
menuItem_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ta.setText("");
}
});
mnNewMenu_1.add(menuItem_5);
separator_1 = new JSeparator();
mnNewMenu_1.add(separator_1);
menuItem_6 = new JMenuItem("\u5168\u9009"); //全选
menuItem_6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ta.selectAll();
}
});
mnNewMenu_1.add(menuItem_6);
menu = new JMenu("\u6837\u5F0F");
menuBar.add(menu);
menuItem_8 = new JMenuItem("\u5B57\u4F53");//字体
menuItem_8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String fronts[] = {"Serif", "SansSerif", "Monospaced", "KaiTi", "SimHei"};
String selectedFont =(String)JOptionPane.showInputDialog(menu, "请选择字体","字体", JOptionPane.PLAIN_MESSAGE,null,fronts, fronts[0] );
System.out.println(selectedFont);
ta.setFont(new Font(selectedFont,ta.getFont().getStyle() ,ta.getFont().getSize()));
}
});
menu.add(menuItem_8);
menuItem_9 = new JMenuItem("\u5B57\u53F7");//字号
menuItem_9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String size[] = {"7","8","9","10","11","12","13","14"};
int selectedsize = Integer.parseInt((String)JOptionPane.showInputDialog(menu, "请选择字号", "字号设置", JOptionPane.PLAIN_MESSAGE, null, size, size[0]));
ta.setFont(new Font(ta.getFont().getFamily(), ta.getFont().getStyle(), selectedsize));
}
});
menu.add(menuItem_9);
menuItem_10 = new JMenuItem("\u989C\u8272"); //字体颜色
menuItem_10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color color = JColorChooser.showDialog(ta, "请选择颜色", Color.RED);
if(color != null){
ta.setForeground(color);
}
}
});
menu.add(menuItem_10);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
ta = new JTextArea();
scrollPane.setViewportView(ta);
Document doc = ta.getDocument();
doc.addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
}
public void insertUpdate(DocumentEvent e) {
setTitle(APP_NAME + "-" + filename + "(*)");
isTextModified = true;
}
public void removeUpdate(DocumentEvent e) {
setTitle(APP_NAME + "-" + filename + "(*)");
isTextModified = true;
}
});
popupMenu = new JPopupMenu();
addPopup(ta, popupMenu);
radioButtonMenuItem = new JRadioButtonMenuItem("\u9ED1\u8272");
buttonGroup.add(radioButtonMenuItem);
popupMenu.add(radioButtonMenuItem);
radioButtonMenuItem_1 = new JRadioButtonMenuItem("\u7EA2\u8272");
buttonGroup.add(radioButtonMenuItem_1);
popupMenu.add(radioButtonMenuItem_1);
radioButtonMenuItem_2 = new JRadioButtonMenuItem("\u84DD\u8272");
buttonGroup.add(radioButtonMenuItem_2);
popupMenu.add(radioButtonMenuItem_2);
radioButtonMenuItem_3 = new JRadioButtonMenuItem("\u7EFF\u8272");
buttonGroup.add(radioButtonMenuItem_3);
popupMenu.add(radioButtonMenuItem_3);
}
}