第一章 java开发入门
输出hello world!
public class ABC {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
第二章 java编程基础
计算1~~99奇数的和
public class ABc {
public static void main(String[] args) {
int y = 0;
for(int i=1;i<100;i++){
if(i%2!=0){
y+=i;
}
}
System.out.println(y);
}
}
public class ABc {
public static void main(String[] args) {
Scanner read=new Scanner(System.in);
int x=0,y=0;
while(read.hasNext()){
x=read.nextInt();
y=function(x);
System.out.println(y);
}
}
public static int function(int x){
int y=0;
if(x>0){
y=x+3;
}else if(x==0){
y=0;
}else{
y=x*x-1;
}
return y;
}
}
数组排序。函数调用
public class ABc {
public static void main(String[] args) {
int[] a={25,24,12,76,101,96,28};
System.out.println("排序前:");
old(a);
System.out.println("排序后:");
sort(a);old(a);
}
public static void sort(int[] numbers){
int temp; // 记录临时中间值
int size = numbers.length; // 数组大小
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (numbers[i] < numbers[j]) { // 交换两数的位置
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
}
public static void old(int[] x){
for(int i=0;i<x.length;i++){
System.out.print(x[i]+" ");
}
System.out.println();
}
}
第三章 面向对象(上)
设计学生类。类的封装,this的使用,构造方法,单例模式
public class ABc {
public static void main(String[] args) {
//创建两个Student对象
Student stu1=new Student();//一个使用无参的构造方法,然后调用方法给姓名分数赋值
stu1.setName("陈灵杰");
stu1.setGrade(100);
stu1.say();//调用输出方法
Student stu2=new Student("廖灵慧",0);//使用有参构造方法,在方法中给姓名和成绩赋值
stu2.say();
//单例模式
Single s1=Single.getInstance();
Single s2=Single.getInstance();
System.out.println(s1==s2);//答案为ture,两个参数代表的同一对象
}
}
//创建Student类(封装)
class Student{
private String name;//name属性私有化
private double grade;
//为了让外界访问私有属性设置两个public方法(配套用)
public String getName() {//方法1获取属性值
return name;
}
public void setName(String name) {//方法2设置属性值
this.name = name;//左边表示类私有成员。右边表示参数(重名)
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
//两个构造方法,在实例化对象的同时对对象的属性进行赋值
public Student(){ //有参的构造函数存在这个不能省略
}
public Student(String name,double grade){
this.name=name;
this.grade=grade;
}
//普通方法,如果用静态方法可以在外界不创建实例对象直接使用
//但在方法类对属性需要创建对象,题中是非静态变量
public void say(){
System.out.println("name:"+name+" grade:"+grade);
}
}
//单例模式,只存在一个实例对象
class Single{
private static Single INabc=new Single();//创建一个对象
private Single(){// 私有化构造方法
}
public static Single getInstance(){//提供返回对象的静态方法(收费站)
return INabs;
}
}
内部类的使用
public class ABc {
public static void main(String[] args) {
Father.Child t1=new Father().new Child();//通过外部类对象去创建内部类对象
t1.introFather();
Father.boy t2=new Father.boy();//不创建外部类对象去实例化内部类对象
t2.outroFather();
Father t3=new Father();//创建外部类对象
t3.test();
}
}
//创建Father类
class Father{
private String name="陈灵杰";//name属性私有化
private static String a="廖灵慧";//静态类只能使用静态成员
class Child{//非静态内部类
public void introFather(){
System.out.println("非静态内部类:");
System.out.println(" name:"+name);//使用外部类私有属性
}
}
static class boy{//静态内部类
public void outroFather(){
System.out.println("静态内部类:");
System.out.println(" name:"+a);//使用外部类私有属性
}
}
public void test(){//普通方法
Child child=new Child();//创建内部类调用内部类方法
System.out.println("\n外部类使用内部类成功!!");
child.introFather();//调用外部类方法
class gril{//方法内部类
void show(){
System.out.println("\n方法内部类使用成功");
}
}
gril t=new gril();//创建方法内部类调用内部类方法
t.show();
}
}
第四章 面向对象下
继承,super的用法
public class ABc {
public static void main(String[] args) {
Student st1=new Student("陈灵杰",19);
st1.show();
UnderGraduate st2=new UnderGraduate("廖灵慧",19,"小学");
st2.show();
}
}
class Student{//父类
public String name;
public int age;
public Student(){//防止出错尽量加上
}
public Student(String name,int age){
this.age=age;
this.name=name;
}
public void show(){
System.out.println("name: "+name+" age: "+age);
}
}
class UnderGraduate extends Student{//子类
private String degree;
public UnderGraduate(){
}
public UnderGraduate(String name,int age,String degree){
super(name,age);//调用父类构造方法
this.degree=degree;
}
public void show(){
System.out.println("name: "+name+" age: "+age+" degree: "+degree);
}
}
多态 接口 抽象类 匿名内部类
interface Shape{//定义接口,抽象类可以含有非抽象方法
int X=1;//定义全局变量
double area(double a);//定义抽象方法
}
class Square implements Shape{//实例化接口,可同时先继承一个类,或实例化多个接口
public double area(double sidelength){
return sidelength*sidelength;
}
}
class Circle implements Shape{
public double area(double r){
return Math.PI*r*r;
}
}
public class ABc {
public static void main(String[] args) {
//同一标签不同类型对象
Shape t1 = new Square();
Shape t2 = new Circle();
Square t3 = new Square();
shape(t1);
shape(t2);
System.out.println("实例对象直接调用方法实现:");
System.out.println(" "+t3.area(3));
//匿名内部类实现对象实例化
shape(new Animal(){//new父类(参数列表)或父类接口()
public viod shape(){
System.out.println("匿名内部类被使用:");
}
});
}
//多态
public static void shape(Shape an){//静态方法调用,可用instanceof判断对象类型
System.out.println("静态方法实现:");
System.out.println(" "+an.area(2)); //根据类型调用对应方法
}
}
异常 finally
//自定义异常
class NoThisSongException extends Exception{//必须继承紫Exception及其子类
public NoThisSongException(){
super();//调用Exception的无参构造方法
}
public NoThisSongException(String message){
super(message);
}
}
class Player{
public void play(int index)throws NoThisSongException{//在方法中抛出异常避免编译错误
if(index>10){//抛出异常后可以由调用者处理但必须处理否者编译通不过
throw new NoThisSongException("你播放的歌曲不存在");
}
System.out.println("正在播放歌曲");
}
}
public class ABc {
public static void main(String[] args) {
Player t1 = new Player();
try{
t1.play(13);
}catch (NoThisSongException e){
System.out.println("异常信息:"+e.getMessage());
}finally{//只有System.exit(0)才能让它不运行,保证资源安全close也放在这
System.out.println(" 进入finally代码块");
}
}
}
第五章 多线程
多线程的继承与接口基本使用 后台程序 Thread方法sleep
//继承实现多线程
class MyThread1 extends Thread{
public MyThread1(String name){
super(name);//调用Thread的有参构造方法
}
public void run(){
while(true){
System.out.println(this.getName()+"正在运行 1");
try {//Thread及其子类调用必须进行异常处理
MyThread1.sleep(2000);//史过程看的更清楚延迟2秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//接口实现多线程
class MyThread2 implements Runnable{
public void run(){
while(true){//获取线程名字 先获取线程再获取线程名
System.out.println((Thread.currentThread()).getName()+"正在运行 2");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//设置 后台线程
class MyThread3 implements Runnable{
public void run(){
while(true){
System.out.println((Thread.currentThread()).getName()+"正在运行 3");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ABc {
public static void main(String[] args) {
//以下都是简单写法,不创参数接受直接创立实例对象
new MyThread1("继承线程").start();//调用父类方法,同时调用被重写的run方法
//传入实例对象同时进行命名再创建Thread类有构造方法接受接口对象调用同上
new Thread(new MyThread2(),"接口线程").start();
//设置后台线程在线程调用运行之前,前台线程结束运行时自动停止运行
new Thread(new MyThread3(),"后台程序").setDaemon(true);
new Thread(new MyThread3(),"后台程序").start();
while(true){
System.out.println("main方法正在运行 4");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
两种多线程比较 多线程同步
//继承实现多线程
class MyThread1 extends Thread{
public MyThread1(String name){
super(name);//调用Thread的有参构造方法 命名
}
private int book=80;
public void run(){
while(true){
if(book>0){
System.out.println((Thread.currentThread()).getName()+"分发第"+book--+"作业本");
try {//Thread及其子类调用必须进行异常处理
MyThread1.sleep(10);//史过程看的更清楚延迟2秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
//接口实现多线程 共用同一资源
class MyThread2 implements Runnable{
private int tick=100;
private int tick1=100;
Object lock=new Object();
public void run(){
while(true){
sale();
//共享资源代码块保证一个实例对象里面一次只有一个线程访问;lock为run外的常量
synchronized(lock){
if(tick>0){
System.out.println(Thread.currentThread().getName()+"售卖第"+tick--+"火车票");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
} //同步方法 在run中调用 私有方法lock为调用对象,静态lock为调用的class 都是唯一的
private synchronized void sale(){
if(tick1>0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"赠送第"+tick1--+"电影票");
}
}
}
public class ABc {
public static void main(String[] args) {
new MyThread1("老师甲").start();//创建一个线程对象并启动
new MyThread1("老师乙").start();
MyThread2 tw=new MyThread2();//只能有一个实例对象
new Thread(tw,"windos1").start();//创建线程并启动
new Thread(tw,"windos2").start();
}
}
线程调度,线程优先级 让步休眠插队
public class ABc{
public static void main(String[] args) throws Exception {
//线程优先级
Thread min=new Thread(new MIN(),"优先级小的线程");
Thread max=new Thread(new MAX(),"优先级大的线程");
max.setPriority(10); min.setPriority(Thread.MIN_PRIORITY);//设置优先级
max.start();//开启线程
min.start();
// 线程休眠 进入堵塞态
new Thread(new SleepThread(),"休眠线程").start();
//线程让步进入就绪态
Thread t3=new YieldThread("让步线程");
t3.start();
//线程插队 进入堵塞态
Thread t4=new Thread(new JoinThread(),"插队线程");
t4.start();
for(int i=1;i<=10;i++){
if(i==2){
t4.join();//前提必须开启该线程 同时对异常进行处理和sleep同
}
System.out.println(Thread.currentThread().getName()+"正在输出:"+i);
}
}
}
//设置优先级
class MAX implements Runnable{
public void run(){
for(int i=20;i<=30;i++){
System.out.println(Thread.currentThread().getName()+"正在输出:"+i);
}
}
}
class MIN implements Runnable{
public void run(){
for(int i=100;i<=110;i++){
System.out.println(Thread.currentThread().getName()+"正在输出:"+i);
}
}
}
//线程休眠
class SleepThread implements Runnable{
public void run(){
for(int i=220;i<=230;i++){
if(i==228){
System.out.print("线程休眠: ");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"正在输出:"+i);
}
}
}
//线程让步
class YieldThread extends Thread{
public YieldThread(String name){
super(name);
}
public void run(){
for(int i=330;i<=390;i++){
if(i==332){
System.out.pri
第六章 javaAPI
String和StringBuffer
public static void main(String[] args) throws Exception {
String str1="Helloworld";//定义字符串对象并赋值
String str3=" abllo world ";
{//字符串长度 位置上的元素 某元素第一次和最后一次出现位置
System.out.println(str3.length()+" "+str3.charAt(2)+" "+str3.indexOf('o')+" "+str3.lastIndexOf('o'));
}
{ //字符串元素的替换
System.out.println(str3.replace("ab","He"));
System.out.println(str3.trim());
System.out.println(str3.replace(" ",""));
}
{ //字符串的判断 开头结尾元素是否包含是否为空是否与其他字符串相等 相等返回true ==返回flase
System.out.println(str3.startsWith("He")+" "+str3.endsWith("ld")+" "+str3.contains("world")+" "+str3.isEmpty()+" "+str3.equals(str1));
}
{ //字符串截取和分割
System.out.println(str3.substring(7)+" "+str3.substring(4,7));
}
char[] ch=str1.toCharArray();//转换成字符数组
StringBuffer str2=new StringBuffer();
for(int i=str1.length()-1;i>=0;i--)
if(ch[i]>='A'&&ch[i]<='Z'){//将一个元素取出来作为一个新的字符串处理加入
str2.append(String.valueOf(ch[i]).toLowerCase());
}else if(ch[i]>='a'&&ch[i]<='z'){
str2.append(String.valueOf(ch[i]).toUpperCase());
}
System.out.println(str2.toString());
}
}
Date DateFormat Calendar SimpleDateFormat 日期
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class ABc{
public static void main(String[] args) throws Exception {
//时间戳 1970 .1 .1 00.00开始 可以被Date构造函数处理
long t=System.currentTimeMillis();
System.out. println(t);
//calendar抽象类 方法获取当前时间
Calendar date=Calendar.getInstance();
System.out.println(date.get(Calendar.MONTH)+1+"月");//月份从0开始的
date.add(Calendar.DATE, 100);//当前时间后的一百天
System.out.println(date.get(Calendar.MONTH)+1+"月");
Date date2=date.getTime();//setTime 实现date和calendar转换
//Dateformat中四种格式 FULL完整 LONG长格式 MEDIUM普通 SHORT短格式
DateFormat date3 =DateFormat.getDateInstance(DateFormat.FULL);
String str=date3.format(date2);//化为日期的字符串格式
System.out.println(str);
DateFormat date4 =DateFormat.getDateInstance(DateFormat.LONG);
System.out.println(date4.format(date2));
SimpleDateFormat date5=new SimpleDateFormat(
"Gyyyy年MM月dd天:今天是yyyy年的第D天");
System.out.println(date5.format(new Date()));
}
}
randon随机数 数据包装类
import java.util.Random;
public class ABc{
public static void main(String[] args) throws Exception {
//Random产生随机数
System.out.println("按时间随机产生种子");
Random rand=new Random();
int[] num=new int[5];
int[] num1=new int[5];
for(int i=0;i<num.length;i++){
//产生1-30的随机数 double和float产生0.0-0.1
num[i]=20+rand.nextInt(31);
System.out.println(num[i]);
}
System.out.println("用10做种子");
Random rand1=new Random(10);
for(int i=0;i<num1.length;i++){
num1[i]=20+rand1.nextInt(31);
System.out.println(num1[i]);
}
//包装类
System.out.println("包装类: ~~");
int a=20,b;
Integer t=new Integer(a);//装箱
b=t.intValue();//拆箱
//自动拆装箱
int d=40;Integer c=d;int f=c;
System.out.println("人工拆装:"+t.toString()+" "+t+" 自动拆装箱:"+c+" "+f);
}
}
Runtime System Math
import java.util.Enumeration;
import java.util.Properties;
public class ABc{
public static void main(String[] args) throws Exception {
//System 获取系统属性 currentTimeMillis 获取时间戳 arraycopy(原数组,开始位置,目标数组,开始位置,长度)
System.out.println("System类:");
Properties t1=System.getProperties();//封装系统所有属性,键值形式存在
Enumeration T1=t1.propertyNames();//获取属性key返回Enumeration对象
while(T1.hasMoreElements()){
String key=(String)T1.nextElement();//获取属性键
String value=System.getProperty(key);//获取键对应的值
System.out.println(key+"------>"+value);
}
//Runtime单例程 不能直接实例化
System.out.println("Runtime类:");
Runtime t2=Runtime.getRuntime();
System.out.println("服务器个数:"+t2.availableProcessors()+"个");
System.out.println("空闲内存:"+t2.freeMemory()/1024/1024+"M");
System.out.println("最大内存:"+t2.maxMemory()+"M");
//Math
System.out.println("Math类: ~~");
double a=-3.5,b=3.5;
System.out.println(Math.abs(a)+" "+Math.ceil(a)+" "+Math.floor(a)+" "+Math.round(a)+" "+Math.max(a,b)+" "+Math.random());
}
}
第七章 集合类
list 的 ArrayList 和两种遍历方式
import java.util.ArrayList;
import java.util.Iterator;
public class ABc{
public static void main(String[] args) throws Exception {
//还有LinkedList适合做删减 下面适合查询
ArrayList t1=new ArrayList();
for(int i=0;i<11;i++){
t1.add(i);
}
System.out.println("迭代器遍历:");
Iterator T1=t1.iterator();//获取Tterator对象
while(T1.hasNext()){//判断ArryList是否有下一个数
Object obj=T1.next();//取出ArrayList集合元素
System.out.println(obj);
}
System.out.println("foreach遍历:");
for(Object list: t1){//数据类型 参数:容器
System.out.println(list);
}
}
}
set 的hashCode Treeset
public class ABc{
public static void main(String[] args) throws Exception {
//还有二叉树Treeset集合 元素不可重复
HashSet ch=new HashSet();
Person p1=new Person ("jack",25);
Person p2=new Person ("jack",25);
Person p3=new Person ("Rose",24);
ch.add(p1);//添加对象 验证哈希值和数值是否相等,相同就删去
ch.add(p2);
ch.add(p3);
for(Object obj: ch){
Person p=(Person)obj;
System.out.println(p.name+": "+p.age);
}
}
}
//定义类 必须重写hashCode。和equals方法
class Person{
String name;
int age;
public Person(String name,int age){
super();
this.name=name;
this.age=age;
}
public int hashCode(){
return name.hashCode();
}
public boolean equals(Object obj){
if(this==obj){ //判断是否是同一对象
return true;
}
if(!(obj instanceof Person)){//判断是否为Person类型
return false;
}
Person man=(Person)obj;
return man.name.equals(this.name); //判断名字是否相同
}
}
Map 的TreeMap和HashMap
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class ABc{
public static void main(String[] args) throws Exception {
//Map 键值对应 HashMap不能重复
TreeMap ch=new TreeMap(new MyComparator());
ch.put("1","Lucy");
ch.put("2","Lucy");
ch.put("3","John");
ch.put("4","Smith");
ch.put("5","Amanda");
for(Object key: ch.keySet()){//获取键值
System.out.println(key+": "+ch.get(key));//获取值
}
Set dh=ch.keySet();//获取建的集合
Iterator it = dh.iterator();//获取迭代器对象
while(it.hasNext()){
Object key=it.next();
Object value=ch.get(key);
System.out.println(key+": "+value);
}
}
}
//定义类 必须重写hashCode。和equals方法
class MyComparator implements Comparator{//自定义比较器
public int compare(Object obj1,Object obj2){//实现比较方法
String t1=(String)obj1;
String t2=(String)obj2;
return t2.compareTo(t1);//比较值后返回
}
}
第八章 IO(输入输出)
字节流与字符流 LineNumberReader 加行号 newLine()加换行符
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.FileWriter;
public class ABc{
public static void main(String[] args) throws Exception {
FileInputStream in=new FileInputStream("E:/A.txt");
FileOutputStream out=new FileOutputStream("E:\\B.txt",true);//加true不覆盖原来有的
byte[] buf=new byte[1024];//数组缓冲区提高读写速度
int len;
while ((len=in.read(buf))!=-1){
out.write(buf,0,len);
}
in.close();//关闭流之后对象不可再用
out.close();
FileInputStream ccc=new FileInputStream("E:/A.txt");
InputStreamReader br=new InputStreamReader(ccc);//字节流转化为字节流
BufferedReader bw=new BufferedReader(br);
BufferedWriter bf=new BufferedWriter(new FileWriter("E:\\C.txt"));//文件不存在会先创建
LineNumberReader lr=new LineNumberReader(br);//跟踪行号输入元源 方便查错
lr.setLineNumber(1);//设置文件读取起始行
String str=null;
while ((str=bw.readLine())!=null){//一次读一行
bf.write(lr.getLineNumber()+": "+str);
bf.newLine();//写入换行符
}
bw.close();
bf.close();
}
}
RandomAccessFile不属于流但有读写功能 输入流
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
public class ABc{
public static void main(String[] args) throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));//将键盘输入的字节转化为字符
String password=null;
boolean b=false;
for(int i=0;i<5;i++){
System.out.println("请输入密码:");
password=br.readLine();
if(password.equals("123456")){
System.out.println("恭喜你成功进入游戏!");
b=true;
break;
}
if(!b&&i<4){
System.out.println("密码错误请重新输入!");
}
if(!b&&i==4){
System.out.println("帐号存在安全问题禁止登入!");
System.exit(0);
}
}
//RandomAccessFile不属于流但有读写功能
RandomAccessFile ra=new RandomAccessFile("D.txt","rw");//先在当前目录下创建文件输入次数,rw支持读写
int times=0; //使用次数
times=Integer.parseInt(ra.readLine());//第一次读入文件times为5
if(times>0){
System.out.println("您还可以使用:"+times--+"次");//使用一次减少一次
ra.seek(0); //使记录指针指向文件开头
ra.writeBytes(times+"");//将剩余的次数写入文件
}else{
System.out.println("您使用次数已到请续费使用!");
}
ra.close();
}
}
第九章 GUI(图形用户界面)
设置标签 运用边界布局
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyMouseHandler extends JFrame{
public MyMouseHandler(){
final JLabel jlabel=new JLabel("此处显示鼠标右键点击的坐标");
jlabel.setOpaque(true);//其他组件不透明看到其他组建的背景颜色
jlabel.setBackground(Color.PINK);
this.setLocation(450, 250);//位于屏幕的位置
this.add(jlabel,BorderLayout.NORTH);//标签位于窗体的位置
this.setSize(500,400);//窗体大小
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置点击关闭按钮时的默认操作
this.addMouseListener(new MouseAdapter(){//用内部类的方式为屏幕注册监听器
public void mouseClicked(MouseEvent e){
if(e.getButton()==e.BUTTON1){//根据鼠标动作做出反映
int x=e.getX();//获取x,y坐标
int y=e.getY();
String banner="鼠标当前点击位置的坐标是("+x+","+y+")";
jlabel.setText(banner);//在窗口中添加标签组件
}
}
});
this.setVisible(true);//窗体可见
}
public static void main(String[] args) {
new MyMouseHandler();//创建实例对象
}
}
ublic class MyMouseHandler extends JFrame{
private JPanel panel=new JPanel();//创建Jpanel面板
private JLabel label=new JLabel("爱好",Font.PLAIN);//爱好标签
private JCheckBox cb1=new JCheckBox("兵乓球");//爱好复选框
private JCheckBox cb2=new JCheckBox("羽毛球");
private JCheckBox cb3=new JCheckBox("唱歌");
private JLabel label1=new JLabel("性别");//性别标签
private JRadioButton aaa=new JRadioButton("男");//性别单选按钮
private JRadioButton bbb=new JRadioButton("女");
private ButtonGroup bg=new ButtonGroup();//实现单选功能,逻辑按钮无需显示,添加选项
private JTextArea area=new JTextArea();//文本域组件
private JScrollPane pane=new JScrollPane(area);//窗口上方带滚动条的面板容器放置文本域
private Set<String> hobbies=new HashSet<String>();//Set集合存放选中的兴趣
private String gender="";//gender选中的性别
private ActionListener listener=new ActionListener(){//JcheckBox事件监听器
public void actionPerformed(ActionEvent e){
JCheckBox cb=(JCheckBox) e.getSource();
if(cb.isSelected()){
hobbies.add(cb.getText());//选中的复选框把文本添加到Set集合中
}else{
hobbies.remove(cb.getText());//从集合中移除
}
print();
}
};
private ActionListener listener2=new ActionListener(){//JRadioButton单选框事件监听器
public void actionPerformed(ActionEvent e){
JRadioButton jb=(JRadioButton) e.getSource();
gender=jb.getText();
print();
}
};
private void print(){//打印方法
area.setText("");//清空文本域
if(hobbies.size()>0)//如果set集合有元素就打印兴趣
area.append("你的兴趣爱好有: ");
Iterator<String> it=hobbies.iterator();
while(it.hasNext()){
area.append(it.next()+" ");
}
if(!"".equals(gender))//判断是否为空 打印性别
area.append("你的性别是: "+gender);
}
public static void main(String[] args) {
new MyMouseHandler();//创建实例对象
}
public MyMouseHandler(){//构造方法
panel.add(label);//添加标签单选和复选按钮
panel.add(cb1);
panel.add(cb2);
panel.add(cb3);
panel.add(label1);
panel.add(aaa);
panel.add(bbb);
bg.add(aaa);//加入单选组
bg.add(bbb);
cb1.addActionListener(listener);//为复选单选注册事件监听器
cb2.addActionListener(listener);
cb3.addActionListener(listener);
aaa.addActionListener(listener2);
bbb.addActionListener(listener2);
Container container=this.getContentPane();//将Jpanel面板和JscrollPane面板添加到JFrame容器中
container.add(panel, BorderLayout.NORTH);
container.add(pane, BorderLayout.CENTER);
this.pack();
this.setLocation(700,450);
this.setSize(500,150);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//窗口关闭按钮
this.setVisible(true);//可见
}
}
下拉式菜单和弹出式菜单
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import java.awt.event.*;
import javax.swing.*;
public class MyMouseHandler extends JFrame{
private JLabel label=new JLabel("请选择菜单",JLabel.CENTER);//爱好标签
public MyMouseHandler(){//构造方法
//下拉式菜单
JMenuBar menuBar=new JMenuBar();//菜单栏
JMenu aMenu=new JMenu("菜单A");
JMenu bMenu=new JMenu("菜单B");
JMenuItem aaMenuItem=new JMenuItem("菜单项 AA");
JMenuItem abMenuItem=new JMenuItem("菜单项 AB");
JMenuItem baMenuItem=new JMenuItem("菜单项 BA");
menuBar.add(aMenu);
menuBar.add(bMenu);
aMenu.add(aaMenuItem);
aMenu.addSeparator();
aMenu.add(abMenuItem);
bMenu.add(baMenuItem);
aaMenuItem.addActionListener(listener);//注册事件监听器
abMenuItem.addActionListener(listener);
baMenuItem.addActionListener(listener);
setJMenuBar(menuBar);
getContentPane().add(label,BorderLayout.CENTER);
//弹出式菜单
JPopupMenu popupMenu=new JPopupMenu();
JMenuItem refresh=new JMenuItem("刷新");
JMenuItem create=new JMenuItem("创建");
JMenuItem exit=new JMenuItem("关闭");
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
popupMenu.add(refresh);
popupMenu.addSeparator();
popupMenu.add(create);
popupMenu.addSeparator();
popupMenu.add(exit);
this.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getButton()==e.BUTTON3){
popupMenu.show(e.getComponent(),e.getX(),e.getY());
}
}
});
this.setLocation(700,450);
this.setSize(500,150);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//窗口关闭按钮
this.setVisible(true);//可见
}
private ActionListener listener=new ActionListener(){
public void actionPerformed(ActionEvent e){
JMenuItem source=(JMenuItem)(e.getSource());
label.setText("选择了菜单:"+source.getText());
label.setHorizontalAlignment(JLabel.CENTER);
}
};
public static void main(String[] args) {
new MyMouseHandler();//创建实例对象
}
}
第十章 网络编程
import java.net.InetAddress;
public class Text {
public static void main(String[] args) throws Exception{
InetAddress localAddress=InetAddress.getLocalHost();
InetAddress remoteAddress=InetAddress.getByName("www.oracle.com");
System.out.println("本机的IP地址:"+localAddress.getHostAddress());//字符串格式的ip
System.out.println("本机的主机名:"+localAddress.getHostName());//本机计算机名或其他的域名或ip
System.out.println("甲骨文的IP地址:"+remoteAddress.getHostAddress());
}
}
UDP无线连接通信
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
//发送端
public class Text1 {
public static void main(String[] args) throws Exception {//需要抛出异常
DatagramSocket ds=new DatagramSocket(3000);//没参数时只能用于发送端
String str="hello world";
DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(),
InetAddress.getByName("localhost"),8001);//发送端必须有地址端口
ds.send(dp);
ds.close();
}
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//接收端
public class Text {
public static void main(String[] args) throws Exception{
byte[] buf=new byte[1024];//接收数据
DatagramSocket ds=new DatagramSocket(8001);//码头 封装接收的数据
DatagramPacket dp=new DatagramPacket(buf,1024);//集装箱 没有ip端口只用于接收端接收数据
ds.receive(dp);//等待接收数据没有数据就会受阻
String str=new String(dp.getData(),0,dp.getLength());//获取内容长度
System.out.println(str);
ds.close();
}
}
TCP面向连接通信
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务器端
public class Text1 {
public static void main(String[] args) throws Exception {//需要抛出异常
new TCPServer().listen();
}
}
class TCPServer{
public void listen() throws Exception{
ServerSocket serverSocket =new ServerSocket(8002);//创建服务器并绑定端口
Socket client=serverSocket.accept();//接收数据
OutputStream os=client.getOutputStream();//获取客户端的输出流
os.write(("hello world").getBytes());
Thread.sleep(5000);//模仿其他程序占用时间
os.close();
client.close();
}
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.io.InputStream;
//客户端
public class Text {
public static void main(String[] args) throws Exception{
new TCPclient().connect();
}
}
class TCPclient{
public void connect() throws Exception{
Socket client=new Socket(InetAddress.getLocalHost(),8002);//获取ip和端口
InputStream is=client.getInputStream();//得到接收收数据的流
byte[] buf=new byte[1024];//定义缓存区
int len=is.read(buf);//将数据读到缓存区
System.out.println(new String(buf,0,len));
client.close();
}
}