




已阅读5页,还剩89页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter14 GraphicalUserComponentsPart2 Outline14 1Introduction14 2JTextArea14 3CreatingaCustomizedSubclassofJPanel14 4JPanelSubclassthatHandlesItsOwnEvents14 5JSlider14 6Windows AdditionalNotes14 7UsingMenuswithFrames14 8JPopupMenu14 9PluggableLook and Feel14 10JDesktopPaneandJInternalFrame14 11JTabbedPane14 12LayoutManagers BoxLayoutandGridBagLayout 14 1Introduction AdvancedGUIcomponentsTextareasSlidersMenusMultipleDocumentInterface MDI AdvancedlayoutmanagersBoxLayoutGridBagLayout TextArea类 TextArea 文本区的列数和行数取默认值 文本区有水平和垂直滚动条 TextArea Strings 文本区的初始字符串为s 文本区有水平和垂直滚动条 TextArea intx inty 文本框行数为y 列数为x 文本区有水平和垂直滚动条 TextArea Strings intx inty 文区的初始字符串为s 文本框行数为y 列数为x 文本区有水平和垂直滚动条 TextArea类 TextArea Strings intx inty intscrollbar 文本区的初始字符串为s 文本框行数为y 列数为x scrollbar取值TextArea SCROLLBARS BOTHTextArea SCROLLBARS VERTICAL ONLYTextArea SCROLLBARS HORIZONTAL ONLYTextArea SCROLLBARS NONE控制文本区滚动条的显示状态 publicvoidsetText Strings 将文本区中的文本设置为参数s指定的文本 文本区中先前的文本将被清除 TextArea类 publicStringgetText 获取文本区中的文本 publicvoidsetEditable booleanb 指定文本区的可编辑性 文本区默认是为可编辑的 publicbooleanisEditable booleanb 获取文本区是否是可编辑的 当文本区是可编辑时 该方法返回true 否则返回false publicvoidinsert Stringsintx 在指定位置x处 插入指定文本s x是指距文本区开始处字符的个数 x不能大于文本区中字符的个数 publicvoidreplaceRange Strings intstart intend 用给定新文本s替换从指定位置start开始到指定位置end结束的文本 start和end不能大于文本区中字符的个数 TextArea类 publicvoidappend Strings 在文本区中尾加文本intgetCaretPosition 获取文本区中输入光标的位置 publicvoidsetCaretPosition intposition 设置文本区中输入光标的位置 其中position不能大于文本区中字符的个数 StringgetSelectedText 获取文本区中选中的文本 publicintgetSelectionStart 获取被选中的文本的开始位置 publicintgetSelectionEnd 获取被选中的文本的结束位置 TextArea类 publicvoidsetSelectionStart intn 设置文本区中被选中的文本的开始位置 其中n不能大于文本区中字符的个数 publicvoidsetSelectionStart intn 设置文本区中被选中的文本的结束位置 其中n不能大于文本区中字符的个数 publicvoidselectAll 选中文本中的全部文本 addTextListener TextListener 向文本框增加文本监视器 removeTextListener TextListener 移去文本框上的文本监视器 TextArea类 importjava applet importjava awt publicclassExample9 4extendsApplet TextAreatext1 text2 publicvoidinit text1 newTextArea 我是学生 6 16 text2 newTextArea 6 16 add text1 add text2 text2 append 我在学习java语言 text1 insert 们 1 text1 selectAll intlength text2 getText length text2 setSelectionStart 2 text2 setSelectionEnd length 14 2JTextArea JTextAreaAreaformanipulatingmultiplelinesoftextextendsJTextComponent与JTextField不同 没有动作事件 通常用一个外部事件来处理JextArea中的文本 importjava awt importjava awt event importjavax swing publicclassTextAreaDemoextendsJFrame privateJTextAreatextArea1 textArea2 privateJButtoncopyButton setupGUIpublicTextAreaDemo super TextAreaDemo Boxbox Box createHorizontalBox Stringstring Thisisademostringto n illustratecopyingtext nfromonetextareato n anothertextareausingan nexternalevent n setuptextArea1textArea1 newJTextArea string 10 15 box add newJScrollPane textArea1 setupcopyButtoncopyButton newJButton Copy box add copyButton copyButton addActionListener newActionListener publicvoidactionPerformed ActionEventevent textArea2 setText textArea1 getSelectedText endanonymousinnerclass endcalltoaddActionListener setuptextArea2textArea2 newJTextArea 10 15 textArea2 setEditable false box add newJScrollPane textArea2 addboxtocontentpaneContainercontainer getContentPane container add box placeinBorderLayout CENTERsetSize 425 200 setVisible true endconstructorTextAreaDemopublicstaticvoidmain Stringargs TextAreaDemoapplication newTextAreaDemo application addWindowListener newWindowAdapter publicvoidwindowClosing WindowEventevent System exit 0 endclassTextAreaDemo 运行结果 14 3CreatingaCustomizedSubclassofJPanel Jpanel用来作为接收鼠标事件的专用绘图区域合并绘图区和Swing的GUI构件会导致图形 GUI构件不能正确显示 扩展Jpanel用来创建新构件 将图形和GUI构件分开 paintComponent方法 从Jcomponent类继承 确保在GUI上下文中按正确的次序绘制 确保完整地保留Swing的绘图机制 paintComponent方法的覆盖 14 3CreatingaCustomizedSubclassofJPanel JFrame和JApplet类不是Jcomponent的子类 不包含paintComponent方法 直接在JFrame或JApplet的子类中绘图 需要覆盖paint方法 例 将绘图区域与按钮分开 14 3CreatingaCustomizedSubclassofJPanel importjava awt importjavax swing publicclassCustomPanelextendsJPanel publicfinalstaticintCIRCLE 1 SQUARE 2 privateintshape useshapetodrawanovalorrectanglepublicvoidpaintComponent Graphicsg super paintComponent g if shape CIRCLE g fillOval 50 10 60 60 elseif shape SQUARE g fillRect 190 10 60 60 setshapevalueandrepaintCustomPanelpublicvoiddraw intshapeToDraw shape shapeToDraw repaint endclassCustomPanel importjava awt importjava awt event importjavax swing publicclassCustomPanelTestextendsJFrame privateJPanelbuttonPanel privateCustomPanelmyPanel privateJButtoncircleButton squareButton setupGUIpublicCustomPanelTest super CustomPanelTest createcustomdrawingareamyPanel newCustomPanel myPanel setBackground Color green setupsquareButtonsquareButton newJButton Square squareButton addActionListener newActionListener drawasquarepublicvoidactionPerformed ActionEventevent myPanel draw CustomPanel SQUARE circleButton newJButton Circle circleButton addActionListener newActionListener drawacirclepublicvoidactionPerformed ActionEventevent myPanel draw CustomPanel CIRCLE setuppanelcontainingbuttonsbuttonPanel newJPanel buttonPanel setLayout newGridLayout 1 2 buttonPanel add circleButton buttonPanel add squareButton attachbuttonpanel endclassCustomPanelTest 运行结果 14 4JPanelSubclassthatHandlesItsOwnEvents JPanelDoesnotsupportconventionaleventse g eventsofferedbybuttons textareas etc Capableofrecognizinglower leveleventse g mouseevents keyevents etc Self containedpanelListensforitsownmouseevents例 侦听鼠标事件 并在自身上绘制椭圆 packagecom deitel jhtp5 ch14 importjava awt importjava awt event importjavax swing publicclassSelfContainedPanelextendsJPanel privateintx1 y1 x2 y2 publicSelfContainedPanel addMouseListener newMouseAdapter publicvoidmousePressed MouseEventevent x1 event getX y1 event getY publicvoidmouseReleased MouseEventevent x2 event getX y2 event getY repaint addMouseMotionListener newMouseMotionAdapter publicvoidmouseDragged MouseEventevent x2 event getX y2 event getY repaint publicDimensiongetPreferredSize returnnewDimension 150 100 publicvoidpaintComponent Graphicsg super paintComponent g g drawOval Math min x1 x2 Math min y1 y2 Math abs x1 x2 Math abs y1 y2 importjava awt importjava awt event importjavax swing importcom deitel jhtp5 ch14 SelfContainedPanel publicclassSelfContainedPanelTestextendsJFrame privateSelfContainedPanelmyPanel publicSelfContainedPanelTest myPanel newSelfContainedPanel myPanel setBackground Color green Containercontainer getContentPane container setLayout newFlowLayout container add myPanel addMouseMotionListener newMouseMotionListener publicvoidmouseDragged MouseEventevent setTitle Dragging x event getX y event getY publicvoidmouseMoved MouseEventevent setTitle Moving x event getX y event getY setSize 300 200 setVisible true publicstaticvoidmain Stringargs SelfContainedPanelTestapplication newSelfContainedPanelTest application addWindowListener newWindowAdapter publicvoidwindowClosing WindowEventevent System exit 0 运行结果 14 5JSlider Jslider 游标 Enableuserstoselectfromrangeofintegervalues高度可定制构件能显示主刻度 次刻度和刻度标签SeveralfeaturesTickmarks majorandminor 刻度Snap toticks 刻度对齐Orientation horizontalandvertical 水平方向的最小值位于最左边 垂直方向的最小值位于最下边 Fig 14 6JSlidercomponentwithhorizontalorientation Jslider支持与鼠标和键盘的交互 左右方向键分别使游标减少或增加1个刻度 PgDn和PgUp键分别使游标减少或增加总刻度范围的1 10 Home键 移动游标到最小值 End键 移动游标到最大值 当用户和Jslider交互时发生ChangeEvent事件 ChangListener中定义响应ChangeEvent的stateChange方法 Jslider的方法 getValue 返回当前游标的位置 setMajorTickSpacing 设置Jslider上刻度的间隔 setPaintTicks 显示刻度 例 利用游标改变圆的大小 14 5JSlider importjava awt importjavax swing publicclassOvalPanelextendsJPanel privateintdiameter 10 drawanovalofthespecifieddiameterpublicvoidpaintComponent Graphicsg super paintComponent g g fillOval 10 10 diameter diameter validateandsetdiameter thenrepaintpublicvoidsetDiameter intnewDiameter ifdiameterinvalid defaultto10diameter newDiameter 0 newDiameter 10 repaint usedbylayoutmanagertodeterminepreferredsizepublicDimensiongetPreferredSize returnnewDimension 200 200 usedbylayoutmanagertodetermineminimumsizepublicDimensiongetMinimumSize returngetPreferredSize endclassOvalPanel importjava awt importjava awt event importjavax swing importjavax swing event publicclassSliderDemoextendsJFrame privateJSliderdiameterSlider privateOvalPanelmyPanel publicSliderDemo super SliderDemo myPanel newOvalPanel myPanel setBackground Color yellow diameterSlider newSlider SwingConstants HORIZONTAL 0 200 10 diameterSlider setMajorTickSpacing 10 diameterSlider setPaintTicks true diameterSlider addChangeListener newChangeListener publicvoidstateChanged ChangeEvente myPanel setDiameter diameterSlider getValue Containercontainer getContentPane container add diameterSlider BorderLayout SOUTH container add myPanel BorderLayout CENTER setSize 220 270 setVisible true publicstaticvoidmain Stringargs SliderDemoapplication newSliderDemo application addWindowListener newWindowAdapter publicvoidwindowClosing WindowEventevent System exit 0 运行结果 当用户操纵窗口时 窗口产生窗口事件 Window类的addWindowListener方法为窗口事件注册事件侦听器 WindowListener接口提供了7个方法来处理窗口事件 windowActivated 点击窗口使之激活时调用 windowClosed 关闭窗口后调用 windowClosing 当用户开始关闭窗口时调用 14 6Windows AdditionalNotes windowDeactived 激活另一个窗口时调用 windowIconified 最小化窗口时调用 windowDeiconified 从最小化还原时调用 windowOpened 窗口第一次在屏幕上显示时调用 将窗口显示在屏幕上的方法 showsetVisible true 设置窗口的大小 setSize 设置窗口在屏幕上的位置 setLocation 14 6Windows AdditionalNotes 14 6Windows AdditionalNotes JFrameWindowswithtitlebarandborderSubclassofjava awt FrameSubclassofjava awt WindowHeavyweightcomponentThreeoperationswhenusercloseswindowDISPOSE ON CLOSEDO NOTHING ON CLOSEHIDE ON CLOSEapplication setDefaultCloseOperation JFrame DISPOSE ON CLOSE Frame类的方法 Frame Stringname Locationp Shapes exactdescriptionFrame Stringname Locationp defaultshapeFrame Stringname Shapes defaultlocationFrame Stringname nameonlyFrame alldefaultsisNamed StringaName isthisyourname moveTo LocationnewLocation movethewindowresize ShapenewShape changeshaperesize floatfactor grow shrinkbyfactor 14 6Windows AdditionalNotes drawText Stringtext Locationloc displaytextstringgetTextSize Stringmsg getshapesofstringdrawLine Locationp1 Locationp2 drawlinesegmentdrawCircle Locationcenter intradius drawcircleclear eraseentireFramecontentsclear Locationcorner Shaperetangle eraseretanglearea 14 6Windows AdditionalNotes 菜单的类型 下拉式菜单和弹出式菜单 菜单只在激活时可见 菜单的交互 侦听器向每个单独的菜单项注册 选择一个菜单项 产生一个ActionEvent 将ActionEvent发送给该选项的侦听器 执行ActionPerformed 14 7UsingMenuswithFrames 14 7UsingMenuswithFrames MenusAllowsforperformingactionswithclutteringGUI在SwingGUI中 菜单仅能在Jframe和JApplet类中使用 提供setJMenuBar方法定义菜单的类 JMenuBar JMenuItem JMenu JCheckBoxMenuItem JRadioButtonMenuItem JMenuBar类 Jcomponent的子类包含了管理菜单条所必需的方法 菜单条是菜单项的容器 JMenuItem类 javax swing AbstractButton的子类包含了管理菜单项所必需的方法 菜单项是菜单中的一个GUI构件 菜单项会触发某种方法或提供子菜单 JMenu类 javax swing JMenuItem的子类包含了管理菜单所必需的方法 菜单被加入到菜单条或其它菜单中 单击某个菜单时 菜单被展开并显示菜单项列表 14 7UsingMenuswithFrames JCheckBoxMenuItem类 javax swing JMenuItem的子类带有复选框的菜单项 包含管理具有开关状态的菜单项所必需的方法 JRadioButtonMenuItem类 javax swing JMenuItem的子类带有单选按钮的菜单项 包含管理具有开关状态的菜单项所必需的方法 14 7UsingMenuswithFrames 例 创建各种类型的菜单项 例 创建各种类型的菜单项 JMenuBarbar newJMenuBar setJMenuBar bar bar add fileMenu JMenuItemexitItem newJMenuItem Exit exitItem setMnemonic x fileMenu add exitItem exitItem addActionListener JMenuItemaboutItem newJMenuItem About aboutItem setMnemonic A fileMenu add aboutItem aboutItem addActionListener JMenufileMenu newJMenu File fileMenu setMnemonic F 例 创建各种类型的菜单项 Jframe的setMenuBar方法 把菜单条添加到JFrame中 AbstractButton的setMnemonic方法 指定AbstractButton的快捷键 Alt 带有下划线的字母 Jmenu的addSeparator方法 为菜单添加分隔线 14 7UsingMenuswithFrames importjava awt importjava awt event importjavax swing publicclassMenuTestextendsJFrame privatefinalColorcolorValues Color black Color blue Color red Color green privateJRadioButtonMenuItemcolorItems fonts privateJCheckBoxMenuItemstyleItems privateJLabeldisplayLabel privateButtonGroupfontGroup colorGroup privateintstyle publicMenuTest super UsingJMenus JMenufileMenu newJMenu File fileMenu setMnemonic F JMenuItemaboutItem newJMenuItem About aboutItem setMnemonic A fileMenu add aboutItem aboutItem addActionListener newActionListener publicvoidactionPerformed ActionEventevent JOptionPane showMessageDialog MenuTest this Thisisanexample nofusingmenus About JOptionPane PLAIN MESSAGE setupExitmenuitemJMenuItemexitItem newJMenuItem Exit exitItem setMnemonic x fileMenu add exitItem exitItem addActionListener newActionListener terminateapplicationwhenuserclicksexitItempublicvoidactionPerformed ActionEventevent System exit 0 createmenubarandattachittoMenuTestwindowJMenuBarbar newJMenuBar setJMenuBar bar bar add fileMenu createFormatmenu itssubmenusandmenuitemsJMenuformatMenu newJMenu Format formatMenu setMnemonic r createColorsubmenuStringcolors Black Blue Red Green JMenucolorMenu newJMenu Color colorMenu setMnemonic C colorItems newJRadioButtonMenuItem colors length colorGroup newButtonGroup ItemHandleritemHandler newItemHandler createcolorradiobuttonmenuitemsfor intcount 0 count colors length count colorItems count newJRadioButtonMenuItem colors count colorMenu add colorItems count colorGroup add colorItems count colorItems count addActionListener itemHandler selectfirstColormenuitemcolorItems 0 setSelected true addformatmenutomenubarformatMenu add colorMenu formatMenu addSeparator createFontsubmenuStringfontNames Serif Monospaced SansSerif JMenufontMenu newJMenu Font fontMenu setMnemonic n fonts newJRadioButtonMenuItem fontNames length fontGroup newButtonGroup createFontradiobuttonmenuitemsfor intcount 0 count fonts length count fonts count newJRadioButtonMenuItem fontNames count fontMenu add fonts count fontGroup add fonts count fonts count addActionListener itemHandler selectfirstFontmenuitemfonts 0 setSelected true fontMenu addSeparator setupstylemenuitemsStringstyleNames Bold Italic styleItems newJCheckBoxMenuItem styleNames length StyleHandlerstyleHandler newStyleHandler createstylecheckboxmenuitemsfor intcount 0 count styleNames length count styleItems count newJCheckBoxMenuItem styleNames count fontMenu add styleItems count styleItems count addItemListener styleHandler putFontmenuinFormatmenuformatMenu add fontMenu addFormatmenutomenubarbar add formatMenu setuplabeltodisplaytextdisplayLabel newJLabel SampleText SwingConstants CENTER displayLabel setForeground colorValues 0 displayLabel setFont newFont Serif Font PLAIN 72 getContentPane setBackground Color cyan getContentPane add displayLabel BorderLayout CENTER setSize 500 200 setVisible true endconstructorpublicstaticvoidmain Stringargs MenuTestapplication newMenuTest application setDefaultCloseOperation JFrame DISPOSE ON CLOSE innerclasstohandleactioneventsfrommenuitemsprivateclassItemHandlerimplementsActionListener processcolorandfontselectionspublicvoidactionPerformed ActionEventevent processcolorselectionfor intcount 0 count colorItems length count if colorItems count isSelected displayLabel setForeground colorValues count break processfontselectionfor intcount 0 count fonts length count if event getSource fonts count displayLabel setFont newFont fonts count getText style 72 break repaint endmethodactionPerformed endclassItemHandler innerclasstohandleitemeventsfromcheckboxmenuitemsprivateclassStyleHandlerimplementsItemListener processfontstyleselectionspublicvoiditemStateChanged ItemEvente style 0 checkforboldselectionif styleItems 0 isSelected style Font BOLD checkforitalicselectionif styleItems 1 isSelected style Font ITALIC displayLabel setFont newFont displayLabel getFont getName style 72 repaint endclassStyleHandler endclassMenuTest 运行结果 14 8JPopupMenu Context sensitivepopupmenusJPopupMenuMenugenerateddependingonwhichcomponentisaccessed为特定的构件产生相应的弹出式触发事件 按下鼠标右键并释放时 发生弹出式触发事件 ActionListener ItemHandler actionPerformed ActionEventevent MouseAdapter 处理应用程序窗口的鼠标事件重载mousePressed方法 mouseReleased方法 JPopupMenu类的show方法 在屏幕的指定坐标位置显示弹出式菜单 例 popupMenu show event getComponent event getX event getY 14 8JPopupMenu importjava awt importjava awt event importjavax swing publicclassPopupTestextendsJFrame privateJRadioButtonMenuItemitems privatefinalColorcolorValues Color blue Color yellow Color red privateJPopupMenupopupMenu setupGUIpublicPopupTest super UsingJPopupMenus ItemHandlerhandler newItemHandler Stringcolors Blue Yellow Red setuppopupmenuanditsitemsButtonGroupcolorGroup newButtonGroup popupMenu newJPopupMenu items newJRadioButtonMenuItem 3 constructeachmenuitemandaddtopopupmenu also enableeventhandlingforeachmenuitemfor intcount 0 count items length count items count newJRadioButtonMenuItem colors count popupMenu add items count colorGroup add items count items count addActionListener handler getContentPane setBackground Color white declareaMouseListenerforthewindowthatdisplays aJPopupMenuwhenthepopuptriggereventoccursaddMouseListener newMouseAdapter handlemousepresseventpublicvoidmousePressed MouseEventevent checkForTriggerEvent event handlemousereleaseeventpublicvoidmouseReleased MouseEventevent checkForTriggerEvent event determinewhethereventshouldtriggerpopupmenuprivatevoidcheckForTriggerEvent MouseEventevent if event isPopupTrigger popupMenu show event getComponent event getX event getY endcalltoaddMouseListenersetSize 300 200 setVisible true endconstructorPopupTest publicstaticvoidmain Stringargs PopupTestapplication newPopupTest application setDefaultCloseOperation JFrame DISPOSE ON CLOSE privateinnerclasstohandlemenuitemeventsprivateclassItemHandlerimplementsActionListener processmenuitemselectionspublicvoidactionPerformed ActionEventevent determinewhichmenuitemwasselectedfor inti 0 i items length i if event getSource items i getContentPane setBackground colorValues i return endprivateinnerclassItemHandler endclassPopupTest 运行结果 14 9PluggableLook and Feel Pluggablelook and feelChangelook and feeldynamicallye g MicrosoftWindowslook and feeltoMotiflook and feelFlexible每种外观和风格实际上使用Java类来表示的 UIManager类 Javax swing包 包含了publicstatic内部类LookAndFeelInfo 维护外观和风格 包含了publicstatic内部类LookAndFeelInfo 维护外观和风格getClassName 得到外观和风格的名称 包含了static方法getInstalledLookAndFeelInfo 获取UIManager LookAndFeelInfo的对象 描述当前已安装的外观和风格 包含了static方法setLookFeel 改变外观和风格SwingUtilities类的static方法UpdateComponentTreeUI来改变参数中所有构件的外观和风格 14 9PluggableLook and Feel importjava awt importjava awt event
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 婚姻家庭法考试题及答案
- 海洋修复技术政策法规实施效果评估
- 联锁块工程施工方案
- 施工组织设计编制的原则和依据教学设计-2025-2026学年中职专业课-建筑施工组织与管理-建筑类-土木建筑大类
- 2025至2030中国航空航天个人防护装备行业市场深度研究与战略咨询分析报告
- 病案员基础知识考核试卷及答案
- 陶瓷碟盘营销策划方案
- 会计学考试题及答案解析
- 综合管廊专项施工方案
- Unit 3 Please Take Me to the Park (教学设计)-2023-2024学年教科版(广州)英语二年级下册
- 腹腔镜下肾癌根治术
- 医师多点执业注册申请表
- 《边坡稳定性分析》课件
- 刮板输送机-课件
- 深信服防火墙技术方案
- 福建省福州市各县区乡镇行政村村庄村名明细及行政区划代码
- 临床路径病种目录
- 车辆交接协议书(标准版)
- 完整版装饰装修试验检测方案
- 满族萨满教衰落原因探析论文
- DB32∕3920-2020 住宅设计标准
评论
0/150
提交评论