Java Swing图形用户界面_第1页
Java Swing图形用户界面_第2页
Java Swing图形用户界面_第3页
Java Swing图形用户界面_第4页
Java Swing图形用户界面_第5页
已阅读5页,还剩105页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

2023/1/151

第10章JavaSwing图形用户界面

2023/1/152导读2023/1/153§10.1JavaSwing概述

Java的java.awt包,即Java抽象窗口工具包(AWT:AbstractWindowToolkit)提供了许多用来设计GUI的组件类。

2023/1/154§10.2窗口

Java提供的JFrame类的实例是一个底层容器,即通常所称的窗口。其他组件必须被添加到底层容器中,以便借助这个地层容器和操作系统进行信息交互。

JFrame类是Container类的间接子类。当需要一个窗口时,可使用JFrame或其子类创建一个对象。2023/1/155§10.2.1JFrame常用方法JFrame()

创建一个无标题的窗口。JFrame(Strings)

创建标题为s的窗口。publicvoidsetBounds(inta,intb,intwidth,intheight

设置窗口的初始位置是(a,b),即距屏幕左面a个像素、距屏幕上方b个像素;窗口的宽是width,高是height。publicvoidsetSize(intwidth,intheight)

设置窗口的大小。publicvoidsetLocation(intx,inty)

设置窗口的位置,默认位置是(0,0)。publicvoidsetVisible(booleanb)

设置窗口是否可见,窗口默认是不可见的。publicvoidsetResizable(booleanb)

设置窗口是否可调整大小,默认可调整大小。publicvoiddispose()

撤消当前窗口,并释放当前窗口所使用的资源。publicvoidsetExtendedState(intstate)

设置窗口的扩展状态.publicvoidsetDefaultCloseOperation(intoperation)

该方法用来设置单击窗体右上角的关闭图标后,程序会做出怎样的处理。例题10-12023/1/156

例题1效果图2023/1/157例题10-1importjavax.swing.*;importjava.awt.*;publicclassExample10_1{publicstaticvoidmain(Stringargs[]){JFramewindow1=newJFrame("第一个窗口");JFramewindow2=newJFrame("第二个窗口");Containercon=window1.getContentPane();con.setBackground(Color.yellow);//设置窗口的背景色

window1.setBounds(60,100,188,108);//设置窗口在屏幕上的位置及大小

window2.setBounds(260,100,188,108);window1.setVisible(true);window1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//释放当前窗口

window2.setVisible(true);window2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//退出程序

}}2023/1/158§10.2.2菜单条、菜单、菜单项1.菜单条JComponent类的子类JMenubar负责创建菜单条,JFrame类有一个将菜单条放置到窗口中的方法:setJMenuBar(JMenuBarbar);该方法将菜单条添加到窗口的顶端2.菜单:JComponent类的子类JMenu负责创建菜单,JMenu类的主要方法有以下几种

JMenu()

建立一个空标题的菜单。

JMenu(Strings)

建立一个指定标题菜单,标题由参数s确定。

publicvoidadd(JMenuItemitem)

向菜单增加由参数item指定的菜单选项。

publicJMenuItemgetItem(intn)

得到指定索引处的菜单选项。

publicintgetItemCount()

得到菜单选项的数目。3.菜单项

JComponent类的子类JMenuItem负责创建菜单项,JMenuItem类的主要方法有以下几种:

JMenuItem(Strings)

构造有标题的菜单项。JMenuItem(Stringtext,Iconicon)

构造有标题和图标的菜单项publicvoidsetEnabled(booleanb)

设置当前菜单项是否可被选择。publicStringgetText()

得到菜单选项的名字。publicvoidsetText(Stringname)

设置菜单选项的名字为参数name指定的字符串。publicvoidsetAccelerator(KeyStrokekeyStroke)

为菜单项设置快捷键。4.嵌入子菜单

JMenu是JMenuItem的子类,因此菜单本身也是一个菜单项,当把一个菜单看作菜单项添加到某个菜单中时,称这样的菜单为子菜单。5.菜单上的图标:图标类Icon声明一个图标,然后使用其子类ImageIcon类创建一个图标,如:Iconicon=newImageIcon(“a.gif”);

例题10-22023/1/159

例题2效果图2023/1/1510例题10-2importjavax.swing.*;importjava.awt.event.InputEvent;importjava.awt.event.KeyEvent;importstaticjavax.swing.JFrame.*;publicclassWindowMenuextendsJFrame{JMenuBarmenubar;JMenumenu,subMenu;JMenuItemitem1,item2;publicWindowMenu(){}publicWindowMenu(Strings,intx,inty,intw,inth){init(s);setLocation(x,y);setSize(w,h);setVisible(true);setDefaultCloseOperation(DISPOSE_ON_CLOSE);}voidinit(Strings){setTitle(s);menubar=newJMenuBar();menu=newJMenu("菜单");subMenu=newJMenu("子菜单");item1=newJMenuItem("菜单项1",newImageIcon("a.gif"));item2=newJMenuItem("菜单项2",newImageIcon("b.gif"));item1.setAccelerator(KeyStroke.getKeyStroke('A'));

2023/1/1511例题10-2item2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));menu.add(item1);menu.addSeparator();menu.add(item2);menu.add(subMenu);subMenu.add(newJMenuItem("子菜单里的菜单项",newImageIcon("c.gif")));menubar.add(menu);setJMenuBar(menubar);}}publicclassExample10_2{publicstaticvoidmain(Stringargs[]){WindowMenuwin=newWindowMenu("带菜单的窗口",20,30,200,190);}}2023/1/1512§10.3常用组件与布局

本节列出一些常用的组件,读者可以查阅类库文档,了解这些组件的属性以及常用方法,也可以在命令行窗口反编译组件即时查看组件所具有的属性及常用方法,例如:

C:\>javapjavax.swing.JComponentC:\>javapjavax.swing.JButton2023/1/1513§10.3.1常用组件1.文本框:由JComponent的子类JTextField创建文本框。2.文本区:由JComponent的子类JTexArea创建文本区。3.按钮:由JComponent的子类JButton类用来创建按钮。4.标签:由JComponent的子类JLabel类用来创建标签。5.选择框:由JComponent的子类JCheckBox类用来创建选择框。6.单选按钮:由JComponent的子类JRadioButton类用来创建单项选择框。7.下拉列表:由JComponent的子类JComboBox类用来创建下拉列表。8.密码框:由JComponent的子类JPasswordField创建密码框。

密码框可以使用setEchoChar(charc)重新设置回显字符。密码框调用char[]getPassword()方法可以返回实际的密码。例子3(Example10_3.java

,ComponentInWindow.java

)包含有上面提到的常用组件。2023/1/1514

例题3效果图2023/1/1515例题10-3importjava.awt.*;importjavax.swing.*;publicclassComponentInWindowextendsJFrame{JTextFieldtext;JButtonbutton;JCheckBoxcheckBox1,checkBox2,checkBox3;JRadioButtonradio1,radio2;ButtonGroupgroup;JComboBox<String>comBox;JTextAreaarea;publicComponentInWindow(){init();setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}voidinit(){setLayout(newFlowLayout());JLabelbiaoqian=newJLabel("文本框:");//标签

add(biaoqian);text=newJTextField(10);//文本框

add(text);

2023/1/1516例题10-3button=newJButton("确定");//按钮

add(button);checkBox1=newJCheckBox("喜欢音乐");//选择框

checkBox2=newJCheckBox("喜欢旅游");checkBox3=newJCheckBox("喜欢篮球");add(checkBox1);add(checkBox2);add(checkBox3);group=newButtonGroup();radio1=newJRadioButton("男");//单选按钮

radio2=newJRadioButton("女");group.add(radio1);group.add(radio2);add(radio1);add(radio2);comBox=newJComboBox<String>();//下拉列表

comBox.addItem("音乐天地");comBox.addItem("武术天地");comBox.addItem("象棋乐园");add(comBox);area=newJTextArea(6,12);//文本区

add(newJScrollPane(area));}}2023/1/1517例题10-3button=newJButton("确定");//按钮

add(button);checkBox1=newJCheckBox("喜欢音乐");//选择框

checkBox2=newJCheckBox("喜欢旅游");checkBox3=newJCheckBox("喜欢篮球");add(checkBox1);add(checkBox2);add(checkBox3);group=newButtonGroup();radio1=newJRadioButton("男");//单选按钮

radio2=newJRadioButton("女");group.add(radio1);group.add(radio2);add(radio1);add(radio2);comBox=newJComboBox<String>();//下拉列表

comBox.addItem("音乐天地");comBox.addItem("武术天地");comBox.addItem("象棋乐园");add(comBox);area=newJTextArea(6,12);//文本区

add(newJScrollPane(area));}}2023/1/1518例题10-3publicclassE{publicstaticvoidmain(Stringargs[]){ComponentInWindowwin=newComponentInWindow();win.setBounds(100,100,300,260);win.setTitle("常用组件");}}2023/1/1519§10.3.2常用容器

JComponent是Container的子类,因此JComponent子类创建的组件也都是容器。容器经常用来添加组件。Jframe是底层容器,本节提到的容器被习惯地称做中间容器,中间容器必须被添加到底层容器中才能发挥作用。

1.JPanel面板:使用JPanel创建面板,再向这个面板添加组件,然后把这个面板添加到其它容器中.JPanel面板的默认布局是FlowLayout布局。2.滚动窗格JScrollPane:可以将文本区放到一个滚动窗格中。

JScorollPanescroll=newJScorollPane(newJTextArea());

3.拆分窗格JSplitPane:窗格有两种类型水平拆分和垂直拆分JSplitPane的两个常用的构造方法:

JSplitPane(inta,Componentb,Componentc)JSplitPane(inta,booleanb,Componentc,Componentd)

4.JLayeredPane分层窗格:分层窗格使用add(Jcomponentcom,intlayer);添加组件com,并指定com所在的层

publicvoidsetLayer(Componentc,intlayer)可以重新设置组件c所在的层publicintgetLayer(Componentc)可以获取组件c所在的层数。2023/1/1520§10.3.3常用布局_1

容器可以使用方法setLayout(布局对象);设置自己的布局,控制组件在容器中的位置。1.FlowLayout布局:

1)创建布局对象FlowLayoutflow=newFlowLayout();2)容器con使用布局对象con.setLayout(flow);3)con可以使用Container类提供的add方法将组件顺序地添加到容器中;

FlowLayout布局对象调用相应的方法可以重新设置布局的对齐方式等.2.BorderLayout布局:

BorderLayout布局是Window型容器的默认布局。使用BorderLayout布局的容器con,可以使用add方法将一个组件b添加到中心区域:con.add(b,BorderLayout.CENTER);或

con.add(BorderLayour.CENTER,b);2023/1/1521§10.3.3常用布局_23.CardLayout布局:

使用CardLayout的一般步骤如下:1)创建CardLayout对象

CardLayoutcard=newCardLayout();2)为容器设置布局

con.setLayout(card);3)容器调用add(Strings,Componentb)将组件b加入容器,并给出了显示该组件的代号s。4)布局对象card用CardLayout类提供的show()方法,显示容器con中组件代号为s的组件:card.show(con,s);4.GridLayout布局:

GridLayout布局策略是把容器划分成若干行乘若干列的网格区域,组件就位于这些划分出来的小格中。GridLayout布局编辑器的一般步骤如下:1)创建布局对象,指定划分网格的行数m和列数n

GridLayoutgrid=newnewGridLayout(10,8);

2)使用GridLayout布局的容器调用方法add(Componentc)将组件c加入容器。

例题4利用GriderLayout布局模拟的国际象棋棋盘,效果如图10.5。2023/1/1522

例题4效果图2023/1/1523例题10-4importjavax.swing.*;importjava.awt.*;publicclassExample10_4{publicstaticvoidmain(Stringargs[]){newWinGrid();}}classWinGridextendsJFrame{GridLayoutgrid;JPanelchessboard;WinGrid(){chessboard=newJPanel();grid=newGridLayout(12,12);chessboard.setLayout(grid);Labellabel[][]=newLabel[12][12];for(inti=0;i<12;i++){for(intj=0;j<12;j++){label[i][j]=newLabel();if((i+j)%2==0)label[i][j].setBackground(Color.black);elselabel[i][j].setBackground(Color.white);chessboard.add(label[i][j]);}}

2023/1/1524例题10-4add(chessboard,BorderLayout.CENTER);add(newJButton("北方参战者"),BorderLayout.NORTH);add(newJButton("南方参战者"),BorderLayout.SOUTH);add(newJButton("西方观察团"),BorderLayout.WEST);add(newJButton("东方观察团"),BorderLayout.EAST);setBounds(10,10,570,390);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);validate();}}2023/1/1525§10.3.3常用布局_35.BoxLayout布局:使用盒式布局的容器将组件排列在一行或一列.BoxLayout布局的一般步骤如下:

1)创建布局对象,使用BoxLayou的构造方法BoxLayout(Containercon,intaxis)可以创建一个盒式布局对象.

2)可以使用Box类的类(静态)方法

createHorizontalBox()获得一个具有行型盒式布局的盒式容器;使用Box类的类(静态)方法

createVerticalBox()获得一个具有列型盒式布局的盒式容器。

3)控制盒式布局容器中组件之间的距离

Box类调用静态方法createHorizontalStrut(intwidth)可以得到一个不可见的水平Struct对象,称做水平支撑.Box类调用静态方法createVertialStrut(intheight)可以得到一个不可见的垂直Struct对象,称做垂直支撑。

例子5

代码链接

两个列型盒式容器boxV1、boxV2和一个行型盒式容器baseBox。在列型盒式容器的组件之间添加垂直支撑,控制组件之间的距离,将boxV1、boxV2添加到baseBox中,并在它俩之间添加了水平支撑。程序运行效果如图10.6。

6.null布局:

空布局容器可以准确地定位组件在容器的位置和大小。组件调用setBounds(inta,intb,intwidth,intheight)方法可以设置本身的大小和在容器中的位置。2023/1/1526

例题5效果图2023/1/1527例题10-5importjavax.swing.*;publicclassWindowBoxLayoutextendsJFrame{BoxbaseBox,boxV1,boxV2;publicWindowBoxLayout(){setLayout(newjava.awt.FlowLayout());init();setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}voidinit(){boxV1=Box.createVerticalBox();boxV1.add(newJLabel("姓名"));boxV1.add(Box.createVerticalStrut(8));boxV1.add(newJLabel("email"));boxV1.add(Box.createVerticalStrut(8));boxV1.add(newJLabel("职业"));boxV2=Box.createVerticalBox();boxV2.add(newJTextField(10));boxV2.add(Box.createVerticalStrut(8));boxV2.add(newJTextField(10));boxV2.add(Box.createVerticalStrut(8));boxV2.add(newJTextField(10));baseBox=Box.createHorizontalBox();baseBox.add(boxV1);baseBox.add(Box.createHorizontalStrut(10));baseBox.add(boxV2);add(baseBox);}}2023/1/1528例题10-5publicclassExample10_5{publicstaticvoidmain(Stringargs[]){WindowBoxLayoutwin=newWindowBoxLayout();win.setBounds(100,100,310,260);win.setTitle("嵌套盒式布局容器");}}2023/1/1529§10.4处理事件

学习组件除了要熟悉组件的属性和功能外,一个更重要的方面是学习怎样处理组件上发生的界面事件。当用户在文本框中键入文本后按回车键、单击按钮、在一个下拉式列表中选择一个条目等操作时,都发生界面事件。程序有时需对发生的事件作出反应,来实现特定的任务,例如,用户单击一个名字叫“确定”或名字叫“取消”的按钮,程序可能需要作出不同的处理。

2023/1/1530§10.4.1事件处理模式

1.事件源:能够产生事件的对象都可以成为事件源.2.监视器:事件源通过调用相应的方法将某个对象注册为自己的监视器。对于文本框,这个方法是:

addActionListener(监视器);事件源注册监视器之后,相应的操作就会导致相应的事件的发生,并通知监视器,监视器就会作出相应的处理。

3.处理事件的接口:

监视器负责处理事件源发生的事件。监视器是一个对象,为了处理事件源发生的事件,监视器这个对象会自动调用一个方法来处理事件。Java规定:为了让监视器这个对象能对事件源发生的事件进行处理,创建该监视器对象的类必须声明实现相应的接口,那么当事件源发生事件时,监视器就自动调用被类重写的某个接口方法(如图10.7)。2023/1/1531事件处理模式效果图2023/1/1532§10.4.2ActionEvent事件1.ActionEvent事件源:

文本框、按纽、菜单项、密码框和单选按纽都可以触发ActionEvent事件,即都可以成为ActionEvent事件的事件源。

2.注册监视器:

能触发ActionEvent事件的组件使用

addActionListener(ActionListenerlisten)

将实现ActionListener接口的类的实例注册为事件源的监视器。3.ActionListener接口:

ActionListener接口在java.awt.event包中,该接口中只有一个方法:

publicvoidactionPerformed(ActinEvente)

事件源触发ActionEvent事件后,监视器将发现触发的ActionEvent事件,然后调用接口中的方法:actionPerformed(ActinEvente)对发生的事件作出处理。ActionEvent类事先创建的事件对象就会传递给该方法的参数e。

4.ActionEvent类中的方法:

publicObjectgetSource()

调用该方法可以获取发生ActionEvent事件的事件源对象的引用。

publicStringgetActionCommand()

调用该方法可以获取发生ActionEvent事件时,和该事件相关的一个命令字符串。

2023/1/1533

例题6

例子6中,文本框text是JTextField的实例,text的监视器listener是实现ActionLiener接口的PoliceListen类创建的对象。在text中输入数字字符串并回车,监视器负责将text中的字符串转化为数,然后计算这个数的平方,并在命令行窗口输出平方。例子6中的text对象和监视器listener都是WindowNumber类创建的窗口中的成员。程序运行效果如图10.8(a)和10.8(b)。代码链接2023/1/1534例题10-6importjava.awt.*;importjavax.swing.*;importstaticjavax.swing.JFrame.*;publicclassWindowNumberextendsJFrame{JTextFieldtext;PoliceListenlistener;publicWindowNumber(){init();setBounds(100,100,150,150);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}voidinit(){setLayout(newFlowLayout());text=newJTextField(10);listener=newPoliceListen();text.addActionListener(listener);//text是事件源,listener是监视器

add(text);}}2023/1/1535例题10-6importjava.awt.event.*;publicclassPoliceListenimplementsActionListener{publicvoidactionPerformed(ActionEvente){intn=0,m=0;Stringstr=e.getActionCommand();try{n=Integer.parseInt(str);m=n*n;System.out.println(n+"的平方是:"+m);}catch(Exceptionee){System.out.println(ee.toString());}}}2023/1/1536例题10-6publicclassExample10_6{publicstaticvoidmain(Stringargs[]){WindowNumberwin=newWindowNumber();}}2023/1/1537

例题7例子7对例子6进行了改进,WindowNumber创建的窗口中有2个文本框,用户在可编辑的文本框中输入数字、回车确认,另一个不可编辑的文本框显示这个数的平方。例子7程序运行效果如图10.9。代码链接2023/1/1538例题10-7WindowNumber.javaimportjava.awt.*;importjavax.swing.*;importstaticjavax.swing.JFrame.*;publicclassWindowNumberextendsJFrame{JTextFieldtextInput,textShow;PoliceListenlistener;publicWindowNumber(){init();setBounds(100,100,150,150);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}voidinit(){setLayout(newFlowLayout());textInput=newJTextField(10);textShow=newJTextField(10);textShow.setEditable(false);listener=newPoliceListen();listener.setJTextField(textShow);//将textShow的引用传递给listen的texttextInput.addActionListener(listener);//textInput是事件源,listener是监视器

add(textInput);add(textShow);}}2023/1/1539例题10-7PoliceListen.javaimportjava.awt.event.*;importjavax.swing.*;publicclassPoliceListenimplementsActionListener{JTextFieldtext;publicvoidsetJTextField(JTextFieldtext){this.text=text;}publicvoidactionPerformed(ActionEvente){intn=0,m=0;JTextFieldtextSource=(JTextField)e.getSource();Stringstr=textSource.getText();if(!str.isEmpty()){try{n=Integer.parseInt(str);m=n*n;text.setText(""+m);}catch(Exceptionee){textSource.setText("请输入数字");}}}}2023/1/1540例题10-7Example10_7.javapublicclassExample10_7{publicstaticvoidmain(Stringargs[]){WindowNumberwin=newWindowNumber();}}2023/1/1541§10.4.3ItemEvent事件1.ItemEvent事件源:选择框、下拉列表都可以触发ItemEvent事件。2.注册监视器:能触发ItemEvent事件的组件使用

addItemListener(ItemListenerlisten)将实现ItemListener接口的类的实例注册为事件源的监视器。3.ItemListener接口:

ItemListener接口在java.awt.event包中,该接口中只有一个方法:

publicvoiditemStateChanged(ItemEvente)

事件源触发ItemEvent事件后,监视器将发现触发的ItemEvent事件,然后调用接口中的itemStateChanged(ItemEvente)方法对发生的事件作出处理。ItemEvent类事先创建的事件对象就会传递给该方法的参数e。4.ItemEvent类中的方法:

getSource()方法返回发生Itemevent事件的事件源外

getItemSelectable()方法返回发生Itemevent事件的事件源。2023/1/1542

例题8代码链接例子8是简单的计算器(程序运行效果如图10.10),实现如下功能:(1)用户在窗口(WindowOperation类负责创建)中的两个文本框中输入参与运算的两个操作数。(2)用户在下拉列选择运算符触发ItemEvent事件,ItemEvent事件的监视器operator(OperatorListener类负责创建)获得运算符,并将运算符传递给ActionEvent事件的监视器computer(3)用户单击按钮触发ActionEvent事件,监视器computer(ComputerrListener类负责创建)给出运算结果。2023/1/1543例题10-8Example10_8.javapublicclassExample10_8{publicstaticvoidmain(Stringargs[]){WindowOperationwin=newWindowOperation();win.setBounds(100,100,390,360);win.setTitle("简单计算器");}}2023/1/1544例题10-8WindowOperation.javaimportjava.awt.*;importjavax.swing.*;publicclassWindowOperationextendsJFrame{JTextFieldinputNumberOne,inputNumberTwo;JComboBox<String>choiceFuhao;JTextAreatextShow;JButtonbutton;OperatorListeneroperator;//监视ItemEvent事件的监视器

ComputerListenercomputer;//监视ActionEvent事件的监视器

publicWindowOperation(){init();setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}2023/1/1545例题10-8voidinit(){setLayout(newFlowLayout());inputNumberOne=newJTextField(5);inputNumberTwo=newJTextField(5);choiceFuhao=newJComboBox<String>();button=newJButton("计算");choiceFuhao.addItem("选择运算符号:");String[]a={"+","-","*","/"};for(inti=0;i<a.length;i++){choiceFuhao.addItem(a[i]);}textShow=newJTextArea(9,30);operator=newOperatorListener();computer=newComputerListener();operator.setJComboBox(choiceFuhao);operator.setWorkTogether(computer);computer.setJTextFieldOne(inputNumberOne);computer.setJTextFieldTwo(inputNumberTwo);computer.setJTextArea(textShow);choiceFuhao.addItemListener(operator);//choiceFuhao是事件源,operator是监视器

button.addActionListener(computer);//button是事件源,computer是监视器

add(inputNumberOne);add(choiceFuhao);add(inputNumberTwo);add(button);add(newJScrollPane(textShow));}}2023/1/1546例题10-8OperatorListener.javaimportjava.awt.event.*;importjavax.swing.*;publicclassOperatorListenerimplementsItemListener{JComboBox<String>choice;ComputerListenerworkTogether;publicvoidsetJComboBox(JComboBox<String>box){choice=box;}publicvoidsetWorkTogether(ComputerListenercomputer){workTogether=computer;}publicvoiditemStateChanged(ItemEvente){Stringfuhao=choice.getSelectedItem().toString();workTogether.setFuhao(fuhao);}}2023/1/1547例题10-8ComputerListener.javaimportjava.awt.event.*;importjavax.swing.*;publicclassComputerListenerimplementsActionListener{JTextFieldinputNumberOne,inputNumberTwo;JTextAreatextShow;Stringfuhao;publicvoidsetJTextFieldOne(JTextFieldt){inputNumberOne=t;}publicvoidsetJTextFieldTwo(JTextFieldt){inputNumberTwo=t;}publicvoidsetJTextArea(JTextAreaarea){textShow=area;}publicvoidsetFuhao(Strings){fuhao=s;}publicvoidactionPerformed(ActionEvente){try{doublenumber1=Double.parseDouble(inputNumberOne.getText());doublenumber2=Double.parseDouble(inputNumberTwo.getText());doubleresult=0;if(fuhao.equals("+")){result=number1+number2;}elseif(fuhao.equals("-")){result=number1-number2;}elseif(fuhao.equals("*")){result=number1*number2;}elseif(fuhao.equals("/")){result=number1/number2;}textShow.append(number1+""+fuhao+""+number2+"="+result+"\n");}catch(Exceptionexp){textShow.append("\n请输入数字字符\n");}}}2023/1/1548§10.4.4DocumentEvent事件1.DocumentEvent事件源:文本区所维护的文档能触发DocumentEvent事件2.注册监视器:能触发DocumentEven事件的事件源使用

addDucumentListener(DocumentListenerlisten)将实现DocumentListener接口的类的实例注册为事件源的监视器。

3.DocumentListener接口:

DocumentListener接口在javax.swing.event包中,该接口中有三个方法:

publicvoidchangedUpdate(DocumentEvente)publicvoidremoveUpdate(DocumentEvente)publicvoidinsertUpdate(DocumentEvente)

事件源触发DucumentEvent事件后,监视器将发现触发的DocumentEvent事件,然后调用接口中的相应方法对发生的事件作出处理。2023/1/1549

例题9

例子9中,有两个文本区。当用户在一个文本区中输入若干英文单词时(用空格、逗号或回车做为单词之间的分隔符),另一个文本区同时对用户输入的英文单词按字典序排序,也就是说随着用户输入的变化,另一个文本区不断地更新排序。程序运行效果如图10.11。2023/1/1550例题10-9Example10_9.javapublicclassExample10_9{publicstaticvoidmain(Stringargs[]){WindowTextSortwin=newWindowTextSort();win.setTitle("窗口");}}2023/1/1551例题10-9WindowTextSort.javaimportjava.awt.*;importjava.awt.event.*;importjavax.swing.event.*;importjavax.swing.*;importjava.util.*;publicclassWindowTextSortextendsJFrameimplementsDocumentListener{JTextAreatext1,text2;WindowTextSort(){init();setLayout(newFlowLayout());setBounds(120,100,260,270);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}

2023/1/1552例题10-9voidinit(){text1=newJTextArea(3,15);text2=newJTextArea(3,15);add(newJScrollPane(text1));add(newJScrollPane(text2));text1.setLineWrap(true);text2.setLineWrap(true);text2.setEditable(false);(text1.getDocument()).addDocumentListener(this);//向文档注册监视器

}publicvoidchangedUpdate(DocumentEvente){//接口方法

Stringstr=text1.getText();//空格、数字和符号(!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~)组成的正则表达式:Stringregex="[\\s\\d\\p{Punct}]+";Stringwords[]=str.split(regex);Arrays.sort(words);//按字典序从小到大排序

text2.setText(null);for(Strings:words)text2.append(s+",");}publicvoidremoveUpdate(DocumentEvente){//接口方法

changedUpdate(e);}publicvoidinsertUpdate(DocumentEvente){//接口方法

changedUpdate(e);}}2023/1/1553§10.4.5MouseEvent事件_1

任何组件上都可以发生鼠标事件,如:鼠标进入组件、退出组件、在组件上方单击鼠标、拖动鼠标等都触发鼠标事件,即导致MouseEvent类自动创建一个事件对象。

1.使用MouseListener接口可以处理以下5种操作触发的鼠标事件在事件源上按下鼠标键、在事件源上释放鼠标键、在事件源上击鼠标键、鼠标进入事件源、鼠标退出事件源。▶MouseEvent中有下列几个重要的方法:

getX()

获取鼠标指针在事件源坐标系中的x-坐标。getY()

获取鼠标指针在事件源坐标系中的y-坐标。

getModifiers()

获取鼠标的左键或右键。

getClickCount()

获取鼠标被单击的次数。

getSource()

获取发生鼠标事件的事件源。

▶事件源注册监视器的方法是addMouseListener(MouseListenerlistener)。

▶MouseListener接口中有如下方法:

mousePressed(MouseEvent)

负责处理在组件上按下鼠标键触发的鼠标事件

mouseReleased(MouseEvent)

负责处理在组件上释放鼠标键触发的鼠标事件

mouseEntered(MouseEvent)

负责处理鼠标进入组件触发的鼠标事件

mouseExited(MouseEvent)

负责处理鼠标离开组件触发的鼠标事件

mouseClicked(MouseEvent)

负责处理在组件上单击鼠标键触发的鼠标事件2023/1/1554

例题10

例子10中,分别监视按钮、文本框和窗口上的鼠标事件,当发生鼠标事件时,获取鼠标指针的坐标值,注意,事件源的坐标系的左上角是原点。2023/1/1555例题10-10Example10_10.javapublicclassExample10_10{publicstaticvoidmain(Stringargs[]){WindowMousewin=newWindowMouse();win.setTitle("处理鼠标事件");win.setBounds(10,10,460,360);}}2023/1/1556例题10-10WindowMouse.javaimportjava.awt.*;importjavax.swing.*;publicclassWindowMouseextendsJFrame{JTextFieldtext;JButtonbutton;JTextAreatextArea;MousePolicepolice;WindowMouse(){init();setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}voidinit(){setLayout(newFlowLayout());text=newJTextField(8);textArea=newJTextArea(5,28);police=newMousePolice();police.setJTextArea(textArea);text.addMouseListener(police);button=newJButton("按钮");button.addMouseListener(police);addMouseListener(police);add(button);add(text);add(newJScrollPane(textArea));}}2023/1/1557例题10-10importjava.awt.event.*;importjavax.swing.*;publicclassMousePoliceimplementsMouseListener{JTextAreaarea;publicvoidsetJTextArea(JTextAreaarea){this.area=area;}publicvoidmousePressed(MouseEvente){area.append("\n鼠标按下,位置:"+"("+e.getX()+","+e.getY()+")");}publicvoidmouseReleased(MouseEvente){area.append("\n鼠标释放,位置:"+"("+e.getX()+","+e.getY()+")");}publicvoidmouseEntered(MouseEvente){if(e.getSource()instanceofJButton)area.append("\n鼠标进入按纽,位置:"+"("+e.getX()+","+e.getY()+")");if(e.getSource()instanceofJTextField)area.append("\n鼠标进入文本框,位置:"+"("+e.getX()+","+e.getY()+")");if(e.getSource()instanceofJFrame)area.append("\n进入窗口,位置:"+"("+e.getX()+","+e.getY()+")");}publicvoidmouseExited(MouseEvente){area.append("\n鼠标退出,位置:"+"("+e.getX()+","+e.getY()+")");}publicvoidmouseClicked(MouseEvente){if(e.getClickCount()>=2)area.setText("鼠标连击,位置:"+"("+e.getX()+","+e.getY()+")");}}2023/1/1558§10.4.5MouseEvent事件_22.使用MouseMotionListener接口可以处理以下两种操作触发的鼠标事件,在事件源上拖动鼠标、在事件源上移动鼠标。▶事件源注册监视器的方法是

addMouseMotionListener(MouseMotionListenerlistener)

MouseMotionListener接口中有如下方法:

mouseDragged(MouseEvent)

负责处理拖动鼠标触发的鼠标事件。

mouseMoved(MouseEvent)

负责处理移动鼠标触发的鼠标事件。2023/1/1559

例题11例子11使用坐标变换来实现组件的拖动

。2023/1/1560例题10-11Example10_11.javapublicclassExample10_11{publicstaticvoidmain(Stringargs[]){WindowMovewin=newWindowMove();win.setTitle("处理鼠标拖动事件");win.setBounds(10,10,460,360);}}2023/1/1561例题10-11importjava.awt.*;importjavax.swing.*;publicclassWindowMoveextendsJFrame{LPlayeredPane;WindowMove(){layeredPane=newLP();add(layeredPane,BorderLayout.CENTER);setVisible(true);setBounds(12,12,300,300);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}2023/1/1562例题10-11importjava.awt.*

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论