2021-06-14

Java面向对象

面向对象程序设计总结(java基础)

本文章为java2使用教程(第五版)耿祥义所著的重点知识点及代码的总结,适用于Java初学者和在校学生的参考文章。本文特别基础的内容并未涉及,但文章所涉及的内容也较为基础,所以本文比较适合作为课本教材的总结参考和Java初学者的学习参考。

笔者打算用多篇文章来系统总结Java的内容,所以本文是第一篇Java的基础入门篇章。所涉及的代码和知识点并非过于简单易懂,适合已经正在学习Java(而不是还没开始学习)的小伙伴们参考学习。并且文章中的纰漏和错误欢迎大家批评指正!

面向对象程序设计总结(java基础) 1

前四章的课后应用题 1

第五章 子类与继承 3

第六章 接口与实现 5

第七章 内部类与异常处理 6

第八章 常用类 8

第九章 组件及事件处理 10

前四章的课后应用题

第二章应用题:计算输入的数字的和及平均值

import java.util.*;

public class 计算输入的数字的和及平均值 {//介绍了Scanner建的对象调用hasNextDouble和nextDouble的方法

public static void main(String args[]){

System.out.println(“请输入您想输入的数字:”);

Scanner reader=new Scanner(http://System.in);

int i=0;

double sum=0;

while(reader.hasNextDouble()){

double m=reader.nextDouble();

sum=sum+m;

i++;

}

double h=sum/i;

System.out.printf(“您输入的数字总和是:%f\n”,sum);

System.out.printf(“您输入的这些数字平均数是:%f”,h);

}

}

第三章应用题:判断用户输入的数字是否为机器随机生成的数字(10以内)

import java.util.*;

public class test2thMarch {

public static void main(String args[]){

double a[]={1,2,3,4,5,6,7,8,9};

System.out.println(“请您输入您想输入的数字:”);

Scanner scanner=new Scanner(http://System.in);

double h=scanner.nextInt();

double s=0;

for(int i=0;i<a.length;i++){

if(h!=a[i]){

continue;

}

else{

System.out.println(h+“是数组a中的数字”);

s=a[i];

break;

}

}

if(s==0){

System.out.println(h+“不是数组a中的数字”);

}

}

}

第四章应用题:计算平均成绩

import java.util.*;

public class Text {

public static void main(String args[]){

System.out.println(“请输入评委的个数:”);

Scanner shu=new Scanner(http://System.in);

int a=shu.nextInt();//这样使得你在文本框中输入的数显现出来

System.out.println(“请输入各个评委的分数:”);

double b[]=new double[a];//记住这种把变量设为数组length的方法

for(int i=0;i<b.length;i++){

b[i]=shu.nextInt();

}

java.util.Arrays.sort(b);//此种方法可将数组中的数字按小大排列好

System.out.println(“去掉一个最高分:”+b[b.length-1]);

System.out.println(“去掉一个最低分:”+b[0]);

double sum=0;

for(int i=1;i<b.length-2;i++){

sum=sum+b[i];

}

double ave=sum/a;

System.out.println(“此选手的最终成绩为:”+ave);

}

}

第五章 子类与继承

//1.super关键字;2.final关键字

SUPER关键字是为了调用父类的属性或方法!

super表示父类属性
使用:super.属性—明确表示从父类中调用属性
super表示父类方法
a.表示父类构造方法:
super( );—表示调用父类无参构造方法,此时super( )可以省略。若调用父类的有参 构造,要明确表示调用的是父类的哪个有参构造方法,例如super(方法参数);此时不能省略,且必须处于构造方法的首行。注:此时不存在this的构造器调用!
b.表示父类被覆写的方法:
super.方法名(参数);

final关键字也成终结器,被它所修饰,值和类型都不能发生改变!

1.final修饰属性
被final修饰的属性就成了常量,在声明时赋值,且赋值后不能修改,常与static搭配使用。
final修饰数据类型,不论是基本类型,还是引用类型,其值都不能变,对于引用类型来说,不变的是其存储的地址值。

2.final修饰方法
被final修饰的方法不能被覆写。

3.final修饰类
被final修饰的类不能有子类。

//—abstract类和abstract方法

public abstract class SIM{//抽象类只负责写出方法名称,具体方法细节交给子类

public abstract String giveNumber();

public abstract String giveCropName();

}

public class Mobile extends SIM{

public String giveNumber(){//子类来详细编写抽象父类所给出的方法

return “11111111111”;

}

public String giveCropName(){

return “中国移动”;

}

}

public class Unicom extends SIM{

public String giveNumber(){

return “11111111111”;

}

public String giveCropName(){

return “中国联通”;

}

}

//—子类的继承

public class computer {

public int oneway(int a,int b){

return a*b;

}

public int onetwo(int a,int b){

return a+b;

}

}

class jisuanqi extends computer{

public int onetwo(int a,int b){//子类重写了父类的一个方法

return a-b;

}

void speak(String s){

System.out.println(“xxxxx”+s);

}

}

public class 子类继承与抽象 {

public static void main(String args[]){

computer c=new jisuanqi();

System.out.println(c.onetwo(1, 0));//子类可直接使用从父类继承的方法

System.out.println(c.oneway(1, 2));//子类可以重写从父类继承的方法

//-表明父类可给子类直接new对象(既体现继承的多态性)*/SIM sim=new Unicom();

System.out.println(“手机号码是”+sim.giveNumber());

System.out.println(“使用的卡是”+sim.giveCropName());

sim=new Mobile();

System.out.println(“手机号码是”+sim.giveNumber());

System.out.println(“使用的卡是”+sim.giveCropName());

/-父类声明的对象可直接使用子类的方法(对象的上转型对象)*/

computer aaa;

aaa.speak(我是计算机!);

}

}

第六章 接口与实现

//抽象(abstract)和接口(interface)的区别

1.抽象类要被子类继承,接口要被类实现。

2.接口只能做方法声明,抽象类中可以作方法声明,也可以做方法实现。

3.接口只能做方法声明,抽象类中可以作方法声明,也可以做方法实现。

4.接口是设计的结果,抽象类是重构的结果。

5.抽象类和接口都是用来抽象具体对象的,但是接口的抽象级别最高。

6.抽象类可以有具体的方法和属性,接口只能有抽象方法和不可变常量。

7.抽象类主要用来抽象类别,接口主要用来抽象功能。

interface SpeakHello{//interface接口和abstract抽象类一样都是只写名称不详写内容

void speakHello();

}

class English implements SpeakHello{

public void speakHello(){//类中使用接口的方法必须提高权限即用public

System.out.println(“英国人打招呼说:hello”);

}

}

//NO.1-两个实现接口的类中写的方法内容并不一样(接口也具多态性)

class Chinese implements SpeakHello{

public void speakHello(){

System.out.println(“中国人打招呼说:你好”);

}

}

//NO.2-----接口声明的对象可调用实现接口类中的方法

class KindPeople{

public void look(SpeakHello hello){//接口类型的参数

hello.speakHello();//接口回调(和继承中上类型转化一样)

}

}

public class 接口的回调和多态 {

public static void main(String args[]){

KindPeople kp=new KindPeople();

kp.look(new English());

kp.look(new Chinese());

}

}

第七章 内部类与异常处理

//1.内部类和外嵌类的关系;

:java中支持在一个类中定义内部类,而类本身称为外嵌类

内部类的外嵌类的变量在内部类仍然有效,内部类的类中的方法

也可以调用外部类中的方法。

内部类中不能傻声明类变量和类方法,外嵌类中可以用内部类声明对象

作为外嵌类的成员

内部类仅仅作为外嵌类使用,其他的类不能用某个类来声明对象

class NbaPlayer{

Lakers name;//内部类声明对象(表明外嵌类可new内部类对象)

NbaPlayer(){

name=new Lakers(198,93);//外嵌类new内部类

}

public void showMess(){

name.speak();//外嵌类可调用声明过内部类的方法

}

class Lakers{//内部类的声明

String hisname=“kobe bryant”;

int height,weight;

Lakers(int h,int w){

height=h;

weight=w;

}

void speak(){

System.out.println(“他是”+hisname+"/t他的身高是"+height+"/t他的体重是"+weight);

}

}//内部类的结束

} //外部类的结束

public class 内部类 {

public static void main(String args[]){

NbaPlayer kb=new NbaPlayer();

kb.name.speak();

kb.showMess();

}

}

2.匿名类;

Interface SpeakHello{//匿名类不仅可用接口interface,还可用抽象abstract。用法和如下一致

void speak();

}

class Machine{

void turnOn(SpeakHello hello){//这个类和这个方法就像是一个引子为main函数中匿名类做铺垫

hello.speak();//接口的对象.接口的方法(可以说是固定句式)

}

}

public class 匿名类 {

public static void main(String args[]){

Machine mc=new Machine();

mc.turnOn(new SpeakHello(){//和接口有关的匿名类(该子类没有用明显的类声明来定义,所以称为匿名类)

public void speak(){

System.out.println(“你好,世界!”);

}

}

);

mc.turnOn(new SpeakHello(){//和接口有关的匿名类(该子类没有用明显的类声明来定义,所以称为匿名类)

public void speak(){

System.out.println(“Hello,world!”);

}

}

);

}

}

3.异常类;

public class 异常类 {

public static void main(String args[]){

int m=0,n=10,t=200;

try{

m=Integer.parseInt(“2222”);//这个方法可以把数字字符串转化成数字

n=Integer.parseInt(“ab22”);//这个方法不可以把字母转化成数字

t=1212;//由于错误发生在了n这一行即程序运行结束,所以t没有机会在此行被赋值

}

catch(NumberFormatException e){//e前边的意思是数字格式(这个位置的单词不可写错)

System.out.println(“发生的异常是:”+e.getMessage());

}

System.out.println(“m=”+m+"\tn="+n+"\tt="+t);

}

}

第八章 常用类

//常用类的总结(依据课本后边小结)

1.String 类的常用方法

①int length();获取length中的String对象的字符序列长度。

②boolean equals(String s);比较String对象的“字符串”是否与参数s指定的字符序列相同(比较字符串要用equals这个方法)。

Sring s1=“我喜欢篮球”;

s2=new String(“我喜欢篮球”);

s1.equals(s2);//返回true

③boolean startsWith(String s),boolean endsWith(String s);判断String对象的字符序列的前缀,后缀是否与s指定的字符序列相同。

String s1=“湖人队总冠军”;

s1.startsWith(“湖人”);//返回true s1.endsWith(“湖人”);//返回false

④int compareTo(String s);按照Unicode的序列,若String对象的序列与s相同返回0,Unicode大于s返回正数,否则负数。

tom=“student”;

tom.campareTo(“student”);//返回0 tom.containsTo(“ok”);//返回正数

⑤boolean contains(String s);判断s中是否包含String对象的字符序列。

tom=“student”;

tom.containsTo(“stu”);//返回true tom.containsTo(“ok”);//返回false

⑥int indexOf(String s),int lastOf(String s);检测String对象与s相同时的字符数(从0开始计),indexOf从头开始lastOf从尾开始。(未检测到返回-1)

tom=“i am a good man”;

tom.indexOf(a);//返回2

⑦String substring(int start,int end);返回String对象中start和end中间的字符。

String tom=“我喜欢打球”;

String str=tom.sunstring(1,3);//str=喜欢

⑧String trim();//去掉String对象的字符中的空格。

tom=“i am a man”;

rom.trim();//返回iamagoodman

2.StringTokenizer类

StringTokenizer(String s,String delim)//为字符s的排列构造一个分析器依deliim字符为分割

StringTokenizer(“iamagoodman”,"*")//值为i am a good man。

3.Scanner类

①Scanner调用next()类解析字符序列中的单词,如果最后一个单词已被next()方法返回,用hasNext()返回true否则返回famlse。

②若要解析数字,则用nextDouble()和nextInt()的方法将解析的数字带回。(若返回的字符非数字而用此法则有InputMismatchException异常)

4.StringBuffer和String类的不同与联系

String对象的序列是不可修改的,也就是String对象的实体是不可能发生变化的。而StringBuffer类的对象的实体的内存空间可以改变大小,便于存放一个

可变的字符序列。

5.Data类与Calender类

① Data data1=new Data();

syso(nowTime);//输出你现在计算机上的时间

Data data2=new Data(1000);//1000表示1000毫秒

若你运行java程序是北京时间将输出1970年01月01日08时00分01秒(因为计算机本身的时间设置为格林威治时间1907.1.1.0时,北京比他快8小时)

② Calender calender=Calender.getInstance();

calender.get(Calender.MONTH)//就会返回此时月份的数字(比如我现在使用它返回3)

calender.get(Calender.DAY_OF_WEEK);//返回1表示星期一(比如我现在返回5)

6.BigInteger类

程序如果要处理较大的数就可用java.math包中的BigInteger类的对象。如下:

BigInteger subtract(BigInteger val)//返回当前对象与val的差

BigInteger remainder(BigInteger val)//返回当前对象与val的余

BigInteger abs()//返回当前对象的绝对值

BigInteger pow(int a)//返回当前对象的a次方幂

7.format方法

①String s=String.format("%.2f",3.12345);//值为3.12

②x=111.222,y=222.222,z=333.111

String s=String.format("%2 . 3 f , .3f,%1 .3f,d,%3 d " , x , y , z ) / / 值 为 222.222 , 333 , 111 ( X d",x,y,z)//值为222.222,333,111(X d",x,y,z)//222.222,333,111(X表示第X个数)

import java.util.*;

import java.util.Random;

public class RedEnvelop {

public static void main(String args[]){

int remainPeople;

double remainMoney,getMoney,totalMoney,endMoney;

Scanner sc=new Scanner(http://System.in);

remainPeople=sc.nextInt();

totalMoney=sc.nextDouble();

System.out.println(“参与抢红包的人数是:”+remainPeople);

System.out.println(“此次红包设定的金额是:”+totalMoney);

System.out.println(“以下是各位用户所抢到的钱数:”);

Math math=new Math();

math.count(remainPeople, totalMoney);

while(remainPeople>0){

if(remainPeople>1){

getMoney=math.getMoneys;

System.out.printf(“这个用户获得:%f元/n”,getMoney);

}

else

System.out.printf(“这个用户获得:%f元/n”,math.endMoneys);

}

System.out.printf(“此次%f元红包已被抢完!”,totalMoney);

}

}

/*abstract class Father{

int remainPeople;

double remainMoney,getMoney,totalMoney,endMoney;

abstract double count();

}*/

class Math{

Random random;

int remainPeoples;

double remainMoneys,getMoneys,totalMoneys,endMoneys;

double count(double remainPeoples,double totalMoneys){

endMoneys=totalMoneys;

if(remainPeoples==1){

return endMoneys;

}

else{

getMoneys=random.nextDouble();

if(getMoneys<0.01){

getMoneys=0.01;

}

remainPeoples–;

endMoneys=endMoneys-getMoneys;

return getMoneys;

}

}

}

第九章 组件及事件处理

①带菜单的窗口

import javax.swing.*;

import java.awt.*;

class WindowMenue extends JFrame{

void init(String s){

setTitle(s);

JMenuBar menubar=new JMenuBar();

JMenu menu=new JMenu(“吃菜”);

JMenu menusub=new JMenu(“菜中菜”);

JMenuItem q1=new JMenuItem(“java talks”);

JMenuItem q2=new JMenuItem(“Play talks”); //之前全是新建对象(3.JMenuItem是菜单中的单项,它添加到JMenu中)

menu.add(q1);

menu.add(q2);

menu.add(menusub); //先是往菜单里边添加具体项(4.JMenu本身就是JMenuItem的子类,可将它也作为一个Item添加到Menu中)

menusub.add(new JMenuItem(“汽车销售系统”)); //new菜中菜的项(2.JMenu负责创建一个菜单,将菜单创建好后要将它添加到JMenubar中)

menubar.add(menu); //再把拟好的菜单加入菜单条中

setJMenuBar(menubar); //建立一个菜单条(1.JMenubar是一个菜单条,只有set才能将它添加在一个窗口中)

}

public WindowMenue(String s,int x,int y,int w,int h){ //注意这个是构造方法

init(s);

setLocation(x,y); //设置窗口的位置

setSize(w,h); //设置窗口的大小

setVisible(true); //使窗口可见

setDefaultCloseOperation(DISPOSE_ON_CLOSE); //设置窗口关闭的选项

}

}

public class 带菜单的窗口{

public static void main(String args[]){

WindowMenue n=new WindowMenue(“LAL”,60,80,340,390);

}

}

//JMenubar将自己set后才能添加到窗口中~~JMenu将自己的菜单编辑好后添加到JMenubar(因为JMenu就是负责创建菜单的)~~JMenuItem是菜单中的单项它要添加到JMnu中去(同时JMenu也是JMenuItem的一个子类因此他也当错一个Item添加到JMenu中)

②焦点和键盘事件

import javax.swing.*;

import javax.swing.event.*;

import java.awt.*;

import java.awt.event.*;

public class 焦点和键盘事件 {

public static void main(String args[]){

Win w=new Win();

w.setBounds(100,100,600,600);

w.setTitle(“输入序列号”);

}

}

class Win extends JFrame{

JTextField jt[]=new JTextField[3];

Police police;

JButton button;

Win(){

setLayout(new FlowLayout());

Police police = null ;

for(int i=0;i<jt.length;i++){

jt[i]=new JTextField(i);

jt[i].addKeyListener(police);//监视键盘事件

jt[i].addFocusListener(police);//调用焦点监视器

add(jt[i]);

}

button=new JButton(“确定”);

add(button);

jt[0].requestFocusInWindow(); //打开窗口自动就给文本框一个焦点

setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

class Police implements FocusListener,KeyListener{

public void keyPressed(KeyEvent e){//按下键盘时的监视器

JTextField t=(JTextField)e.getSource();

if(t.getCaretPosition()>=6) //如果文本框中的字符大于等于6

t.transferFocus(); //焦点将转移

}

public void keyTyped(KeyEvent e){}

public void keyRelased(KeyEvent e){}

public void focusGained(FocusEvent e){//组件由无输入焦点变为有输入焦点

JTextField t=(JTextField)e.getSource();

t.setText(null);

}

public void focusLost(FocusEvent e){}

@Override

public void keyReleased(KeyEvent e) {

// TODO Auto-generated method stub

}

}

③单选多选下拉列表框

import javax.swing.*;

import java.awt.*;

class ComponentWindow extends JFrame{

void inits(){

setLayout(new FlowLayout());//有了它选项内容才能出来(灵魂)

JCheckBox c1=new JCheckBox(“like lakers”);

JCheckBox c2=new JCheckBox(“like clippers”);//new复选框(能勾能抹) 1.JCheckBox是复选框

JRadioButton r1=new JRadioButton(“james”);

JRadioButton r2=new JRadioButton(“goege”);//new单选框(两个只能选其一) 2.JRadioButton是单选框

JComboBox cc=new JComboBox();//new下拉列表 3.JComboBox是下拉列表

ButtonGroup group=new ButtonGroup();

group.add(r1);

group.add(r2);//建立group组就是为了实现‘单选’这个功能

add(c1);

add(c2);

add(r1);

add(r2);//将各个选项框框加入到窗口

add(cc); //添加下拉条

cc.addItem(“Jrdan”);

cc.addItem(“Kobe”);//添加下拉条中的选项名称

}

public ComponentWindow(){

inits();

setVisible(true);//使得窗口可见

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//使得右上角关闭键直接关掉窗口

}

}

public class 单选多选下拉列表框{

public static void main(String args[]){

ComponentWindow n=new ComponentWindow();

n.setBounds(111,111,611,611);//设置窗口大小(注意continer的对象才能编辑窗口的背景颜色)

n.setTitle(“lakerschampion”);//设置窗口名称

}

}

④消息对话框

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class 消息对话框 {

public static void main(String args[]){

WindowMess wm=new WindowMess();

wm.setTitle(“消息对话框”);

wm.setBounds(100,100,400,400);

}

}

class WindowMess extends JFrame implements ActionListener{

JTextField text;

JTextArea area;

String regex="[a-zA-Z]+";

WindowMess(){

text=new JTextField(22);

text.addActionListener(this);

area=new JTextArea();

add(text,BorderLayout.NORTH);

add(area,BorderLayout.CENTER);

setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void actionPerformed(ActionEvent e){

if(e.getSource()==text){

String str=text.getText();

if(str.matches(regex)){ //如果文本框输入的字符与regex符合(即是英文字母)

area.append(str+",");

}

else{ //如果输入非英文字母将弹出消息对话框

JOptionPane.showMessageDialog(this,“您输入了非法字符”,“消息对话框”,JOptionPane.WARNING_MESSAGE);

//(还有好几种对话框)消息对话框组件,提示信息,窗口标题,叹号专用量(还有各种可查)

text.setText(null); //将输入框清空

}

}

}

}

⑤确认对话框

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class 确认对话框 {

public static void main(String args[]){

WindowEnter we=new WindowEnter();

we.setTitle(“带窗口的确定对话框”);

we.setBounds(100,100,400,400);

}

}

class WindowEnter extends JFrame implements ActionListener{

JTextField field;

JTextArea area;

WindowEnter(){

field=new JTextField(10);

area=new JTextArea();

field.addActionListener(this);

add(field,BorderLayout.NORTH);

add(area,BorderLayout.CENTER);

setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void actionPerformed(ActionEvent e){

String s=field.getText();

int n=JOptionPane.showConfirmDialog(this,“确认是否正确”,“确定对话框”,JOptionPane.YES_NO_OPTION);//确认文本框的方法(JOptionPane的方法)

if(n==JOptionPane.YES_OPTION) //如果选定YES这个按钮

area.append("\n"+s); //大文本区域输出小文本框输入的字符

else

field.setText(null); //否则的话也清空小本框输入的内容

}

}

⑥颜色对话框

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class 颜色对话框 {

public static void main(String args[]) {

WindowColor wc=new WindowColor();

wc.setTitle(“带颜色的对话框”);

wc.setBounds(100,100,200,300);

}

}

class WindowColor extends JFrame implements ActionListener{

JButton button;

WindowColor(){

button=new JButton(“打开颜色对话框”);

button.addActionListener(this);

setLayout(new FlowLayout());

add(button);

setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void actionPerformed(ActionEvent e){

Color newcolor=JColorChooser.showDialog(this,“调色版” , getContentPane().getBackground());//调用JClorChooser的方法

if(newcolor!=null)

getContentPane().setBackground(newcolor); //如果选中某颜色,窗口背景将会被设置为此颜色

}

}

⑦itemEvenet事件(小计算器)

import javax.swing.*;

import java.io.*;

import java.awt.*;

import java.awt.event.*;

public class ItemEvnbt事件{

public static void main(String args[]){

WindowOperation wo=new WindowOperation();

wo.setBounds(100, 100, 400, 400); //窗口的位置和大小

wo.setTitle(“简单计算机”); //窗口的标题

}

}

class WindowOperation extends JFrame{

JTextField textone,texttwo;

JComboBox select;

JTextArea area;

JButton button;

ComputerListener computer;

OperationListener operation;

WindowOperation(){

init();

setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

void init(){

setLayout(new FlowLayout()); //窗口中各组件的声明

textone=new JTextField(5);

texttwo=new JTextField(5);

select=new JComboBox();

button=new JButton(“计算”);

String []a={“请选择符号”,"+","-","*","/"};

for(int i=0;i<a.length;i++){

select.addItem(a[i]);

}

area=new JTextArea(9,30);

computer=new ComputerListener(); //监视器部分

operation=new OperationListener();

operation.setComboBox(select);

operation.setWorkTogether(computer);

computer.setJTextField1(textone);

computer.setJTextField2(texttwo);

computer.setTextFieldArea(area);

select.addItemListener(operation); //将下拉列表添加到Item监视器

button.addActionListener(computer); //将按钮添加到Action监视器

add(textone); //将各个组件加入窗口

add(select);

add(texttwo);

add(button);

add(new JScrollPane(area));

}

}

class OperationListener implements ItemListener{

JComboBox choice;

ComputerListener ccc;

void setComboBox(JComboBox box){

choice=box;

}

void setWorkTogether(ComputerListener computer){

ccc=computer;

}

public void itemStateChanged(ItemEvent e){

String str=choice.getSelectedItem().toString();//把下拉菜单中的元素传入到str

ccc.setfuao(str); //再把str传入到setfuao

}

}

class ComputerListener implements ActionListener{

JTextField inputone,inputtwo;

JTextArea showarea;

String fuhao;

void setJTextField1(JTextField t){

inputone=t;

}

void setJTextField2(JTextField t){

inputtwo=t;

}

void setTextFieldArea(JTextArea area){

showarea=area;

}

void setfuao(String s){

fuhao=s;

}

public void actionPerformed(ActionEvent e){

try{

double number1=Double.parseDouble(inputone.getText());//将符号转化为数字

double number2=Double.parseDouble(inputtwo.getText());

double result=0;

if(fuhao.equals("+")){

result=number1+number2;

}

else if(fuhao.equals("-")){

result=number1-number2;

}

else if(fuhao.equals("*")){

result=number1*number2;

}

else if(fuhao.equals("/")){

result=number1/number2;

}

showarea.append(number1+""+fuhao+""+number2+"="+result+"\n");//文本框中所展示

}

catch(Exception exp){

showarea.append(“您输入的是非法数字\n”);

}

}

}

⑧DocumentEvent事件(排序单词)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.util.Arrays;

import java.io.*;

import javax.swing.event.*;

import java.util.*;

public class Exercise{

public static void main(String args[]){

WindowDecument wd=new WindowDecument();

wd.setBounds(100,100,600,500);

wd.setTitle(“排序单词”);

}

}

class WindowDecument extends JFrame{

JTextArea inputarea,showarea;

JMenuBar menubar;

JMenu menu;

JMenuItem itemCopy,itemPaste,itemCut;

TextListener textlistener;

HandleListener handlelistener;

WindowDecument(){

init();

setLayout(new FlowLayout());

setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

void init(){

inputarea=new JTextArea(15,20);

showarea=new JTextArea(15,20);

showarea.setLineWrap(true); //文本自动换行

showarea.setWrapStyleWord(true); //文本以单词为界换行

menubar=new JMenuBar();

menu=new JMenu(“编辑”);

itemCopy=new JMenuItem(“复制(C)”);

itemPaste=new JMenuItem(“粘贴(P)”);

itemCut=new JMenuItem(“剪切(T)”);

itemCopy.setAccelerator(KeyStroke.getKeyStroke(‘c’));//设置快捷键

itemPaste.setAccelerator(KeyStroke.getKeyStroke(‘P’));

itemCut.setAccelerator(KeyStroke.getKeyStroke(‘t’));

itemCopy.setActionCommand(“copy”);//设置文字的ActionEvent事件

itemPaste.setActionCommand(“paste”);

itemCut.setActionCommand(“cut”);

menu.add(itemCopy); //设置菜单项

menu.add(itemPaste);

menu.add(itemCut);

menubar.add(menu);

setJMenuBar(menubar);

add(new JScrollPane(inputarea));

add(new JScrollPane(showarea));

textlistener=new TextListener(); //开始动用检测器

handlelistener=new HandleListener();

textlistener.setInputArea(inputarea);

textlistener.setShowArea(showarea);

handlelistener.setInputArea(inputarea);

handlelistener.setShowArea(showarea);

(inputarea.getDocument()).addDocumentListener(textlistener);//使用文档注册监视器

itemCopy.addActionListener(handlelistener);

itemPaste.addActionListener(handlelistener);

itemCut.addActionListener(handlelistener);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值