讲义说明教案java宁_第1页
讲义说明教案java宁_第2页
讲义说明教案java宁_第3页
讲义说明教案java宁_第4页
讲义说明教案java宁_第5页
已阅读5页,还剩96页未读 继续免费阅读

下载本文档

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

文档简介

AWTAWTswingGUI类库。swingawt布局绘比如按钮,文本框等ContainerComponent的子类,容器本身也是一个组件。AWTpackagecom.lx.test1;importjava.awt.Frame;publicclassTest1{publicstaticvoidmain(String[]args){Framef=newFrame();f.setBounds(50,50,400,300);}}packageimportjava.awt.Button;importjava.awt.Frame;importjava.awt.Panel;importjava.awt.TextField;publicclassTest2publicstaticvoidmain(String[]args){Framef=newFrame();Panelp=newPanel();p.add(newTextField(10));p.add(newButton("ok"));f.setBounds(50,50,400,300);}}像流水一样向某方向自动排列,遇到折回。默认是向右packageimportimportstaticpublicclassTestFlowLayoutpublicstaticvoidmain(String[]args){Framef=newFrame("测试窗口");f.setLayout(newFlowLayout(LEFT205));for(inti=0;i<20;i++){f.add(newButton("按钮}}}5个区域:东西南北中。packageimportimportstaticpublicclassTestFlowLayoutpublicstaticvoidmain(String[]args){Framef=newFrame("测试窗口");f.setLayout(newFlowLayout(LEFT205));for(inti=0;i<20;i++){f.add(newButton("按钮}}}packageimportimportstaticpublicclasspublicstaticvoidmain(String[]{Framef=newFrame("测试窗口");f.setLayout(newBorderLayout(305));f.add(newButton("南"),SOUTH);f.add(newButton("北Panelp=newPanel();p.add(newTextField(20));p.add(newButton("OK"));f.add(newButton("东}}packageimportimportpublicclassTestCardLayout{FramefnewFrame("测试窗口");String[names第一张第二张第三张第四张第五张Panelpl=newPanel();CardLayoutc=newCardLayout();publicvoidinit(){for(inti=0;i<names.length;i++)pl.add(names[i],new}Panelp=newButtonprevious=newButton("上一张");previous.addActionListener(newActionListener(publicvoidactionPerformed(ActionEvente){}Buttonnext=newButton("下一张");next.addActionListener(newActionListener(publicvoidactionPerformed(ActionEvente){}Buttonfirst=newButton("第一张");first.addActionListener(newActionListener(publicvoidactionPerformed(ActionEvente){}Buttonlast=newButton("最后一张");last.addActionListener(newActionListener(publicvoidactionPerformed(ActionEvente){}控制根据CardButtonthird=newButton("第三张");third.addActionListener(newActionListener(publicvoidactionPerformed(ActionEventec.show(pl,"第三张");}f.add(p,BorderLayout.SOUTH);}publicstaticvoidmain(String[]args)new}}packagecom.lx.test2;importjava.awt.*;importjavax.swing.*;publicclassprivateFramefnewFrame("测试publicvoid{f.setLayout(newBoxLayout(fBoxLayout.Y_AXIS));f.add(newButton("第一个按钮"));f.add(newButton("第二个按钮}publicstaticvoidmain(String[]args)new}}另外,BoxLayoutBox容器一起使用,Boxpackagecom.lx.test2;importjava.awt.*;importpublicclassprivateFramefnewFrame("测试privateBoxhorizontal=privateBoxvertical=publicvoid{horizontal.add(newButton("水平按钮一"));horizontal.add(newButton("水平按钮二"));vertical.add(newButton("垂直按钮一"));vertical.add(newButton("垂直按钮二"));f.add(horizontal,BorderLayout.NORTH);}publicstaticvoidmain(String[]args)new}}5 创建一个水平的Glue createVerticalGlue创建一个垂直的Glue可以在两个方向同时拉伸间距createHorizontalStrut(intwidth)创建一个指定宽度水平的Strut可以在垂直方向上拉伸间距createVerticalStrut(intheight)创建一个指定高度的垂直Strut createRigidArea(Dimensiond)创建指定宽度和高度的RigidArea packageimportimportpublicclassTestBoxSpaceprivateFramefnewFrame("测试定义水平摆放组件的BoxprivateBoxhorizontal=定义垂直摆放组件的BoxprivateBoxvertical=publicvoidinit()horizontal.add(newButton("水平按钮一"));horizontal.add(newButton("水平按钮二"));horizontal.add(newButton("水平按钮三"));vertical.add(newButton("垂直按钮一"));vertical.add(newButton("垂直按钮二"));vertical.add(newButton("垂直按钮三"));f.add(horizontal,BorderLayout.NORTH);}publicstaticvoidmain(String[]args)new}}packageimportimportpublicclass ponent{FramefnewFrame("测试");ButtonoknewButton("确认CheckboxGroupcbg=new//CheckboxmalenewCheckbox("男cbg//CheckboxfemalenewCheckbox("女cbg//CheckboxmarriednewCheckbox("是否已婚?ChoicecolorChooser=newListcolorList=newList(6,TextAreata=newTextArea(5,定义一个50TextFieldname=newpublicvoidinit(){创建一个装载了文本框、按钮的PanelPanelbottom=newPanel();f.add(bottom,创建一个装载了下拉选择框、三个Checkbox的PanelPanelcheckPanel=newPanel();创建一个垂直排列组件的Box,盛装多行文本域、PanelBoxtopLeft=Box.createVerticalBox();创建一个垂直排列组件的Box,盛装topLeft、colorListBoxtop=Box.createHorizontalBox();将topBox容器添加到窗口的中间}publicstaticvoidmain(String[]args) }}window类的子类,是一个容器,与普通窗口的用法完全一样。它的构造方法有三个参数分别是packageimportimportpublicclassTestDialog{FramefnewFrame("测试");Dialogd1=newDialog(f,"模式框",Dialogd2=newDialog(f,"非模式框",false);Buttonb1=newButton("打开模式框");Buttonb2=newButton("打开非模式框publicvoidinit(){d1.setBounds(20,30,300,d2.setBounds(20,30,300,400);b1.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){}b2.addActionListener(newActionListener()publicvoidactionPerformed(ActionEvente){}f.add(b2,BorderLayout.SOUTH);}publicstaticvoidmain(String[]args)new}}packageimportimportpublicclassTestFileDialogFramefnewFrame("测试FileDialogd1newFileDialog(f选择需要打开文件FileDialog.LOAD);FileDialogd2=newFileDialog(f,"选择保存文件的路径",Buttonb1newButton("打开文件");Buttonb2newButton("保存文件publicvoidinit()b1.addActionListener(newActionListener()publicvoidactionPerformed(ActionEvente){System.out.println(d1.getDirectory()+d1.getFile());}b2.addActionListener(newActionListener()publicvoidactionPerformed(ActionEvente){System.out.println(d2.getDirectory()+d2.getFile());}f.add(b2,BorderLayout.SOUTH);}publicstaticvoidmain(String[]args)new}} Event

J

Event PopupEventPopup

底层式,如:利用innerclass的类方法classimplementsEventListener现(Implement)!我们把区分成是由Swing或是AWT所Swing caretUpdate(CaretEvente)editingCanceled(ChangeEventeditingStopped(ChangeEventstateChanged(ChangeEvente)changedUpdate(EventinsertUpdate(EventremoveUpdate(EventhyperlinkUpdate(HyperlinkEvente)contentsChanged(ListdataEvente)intervalAdded(ListDataEvente)intervalRemoved(ListDataEvente)valueChanged(ListSelectionEvente)DragMouseDragged(DragMouseEvent DragMouseEventDragMouseExited(DragMouseEvente)DragMouseReleased(DragMouseEvente)KeyPressed(KeyEventKeyReleased(KeyEvente)KeyTyped(KeyEvente)Canceled(Evente)Deselected(Evente)Selected(Evente)popupCanceled(PopupEvente)eInvisible(PopupEvente)eVisible(PopupEvente)columnAdded(TableColumnModelEvente)columnMarginChanged(ChangeEvente)columnMoved(TableColumnModelEvente)columnRemoved(TableColumnModelEvente)columnSelectionChanged(ListSelectionEvente)tableChanged(TableModelEventtreeCollapsed(TreeExpansionEventtreeExpanded(TreeExpansionEventtreeNodesChanged(TreeModelEvente)treeNodesInserted(TreeModelEvente)treeNodesRemoved(TreeModelEvente)treeStructureChanged(TreeModelEvente)valueChanged(TreeSelectionEvente)treeWillCollapse(TreeExpansionEventevent)treeWillExpand(TreeExpansionEventundoableEditHappened(UndoableEditEvente)AWT actionPerformed(ActionEvente)adjustmentValueChanged(AdjustmentEvente)componentHidden(ComponentEventcomponentMoved(ComponentEvente)componentResized(ComponentEvente)componentShown(ComponentEvente)componentAdded(ContainerEvente)componentRemoved(ContainerEventfocusGained(FocusEvente)focusLost(FocusEventitemStateChanged(ItemEvente)keyPressed(KeyEventkeyReleased(KeyEvente)keyTyped(KeyEvente)mouseClicked(MouseEventmouseEntered(MouseEvente)mouseExited(MouseEvente)mousePressed(MouseEvente)mouseReleased(MouseEventmouseDragged(MouseEvente)mouseMoved(MouseEventwindowActivated(WindowEvente)windowClosed(WindowEvente)windowClosing(WindowEventwindowDeactivated(WindowEvente)windowDeiconified(WindowEvente)windowIconified(WindowEvente)windowOpened(WindowEventAdapter 在java中提供两个方法让你知道到底是哪个组件触发了,那就是getSource()与 importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassEventDemo5extendsWindowAdapterimplements{JButtonb1=JButtonb2=public{JFramef=newJFrame("EventDemo5");ContainercontentPanef.getContentPane();contentPane.setLayout(newGridLayout(1,2));b1=newJButton("按我有声音喔");b2newJButton("按我可开新窗口");}publicvoidactionPerformed(ActionEvent{{JFramenewFnewJFrame("新窗口");}}publicvoidwindowClosing(WindowEvent{}publicstaticvoidmain(String{new}}importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassEventDemo6extendsWindowAdapterimplements{JButtonb1=JButtonb2=public{JFramef=newJFrame("EventDemo6");ContainercontentPanef.getContentPane();contentPane.setLayout(newGridLayout(1,2));b1=newJButton("按我有声音喔");b2newJButton("按我可开新窗口");}publicvoidactionPerformed(ActionEvent{ 方返回按钮上的文字字符串 {JFramenewFnewJFrame("新窗口");}}publicvoidwindowClosing(WindowEvent{}publicstaticvoidmain(String{new}}MouseListenermouseClicked(MouseEventmouseEntered(MouseEvente)mouseExited(MouseEvente)mousePressed(MouseEvente)mouseReleased(MouseEventimportjava.awt.*;importjava.awt.event.*;importjavax.swing.*;/*WindowAdapterMouseListener*因此须把MouseListener中的5个方法都实现,如果不想实*可用内部类的方法编写处理程序publicclassMouseDemo1extendsWindowAdapterimplementsMouseListener{JFramef=null;JButtonJLabelpublicf=newContainercontentPane=f.getContentPane();contentPane.setLayout(newGridLayout(2,1));b1=newJButton("按钮");label=newJLabel("起始状态,还没有鼠标",JLabel.CENTER);}publicvoidmousePressed(MouseEvente){}publicvoidmouseReleased(MouseEvente){}publicvoidmouseEntered(MouseEvente){}publicvoidmouseExited(MouseEvente){}publicvoidmouseClicked(MouseEvente){}publicvoidwindowClosing(WindowEvente){}publicstaticvoidmain(String[]args){newMouseDemo1();}}mouseDragged(MouseEvente)mouseMoved(MouseEventimportjava.awt.*;importjava.awt.event.*;import/*implementsMouseListenerpublicclassMouseDemo3extendsJFrameimplementsintflag;//flag=1MouseMoved,flag=2MouseDraggedintx=0;intintstartx,starty,endx,endy;//起始坐标与终点坐标publicMouseDemo3(){ContainercontentPane=getContentPane();newpublicvoidwindowClosing(WindowEvente){}}}publicvoidmousePressed(MouseEvente){}publicvoidmouseReleased(MouseEvente){}publicvoidmouseEntered(MouseEvent}publicvoidmouseExited(MouseEvent}publicvoidmouseClicked(MouseEvent}publicvoidmouseMoved(MouseEvente){}publicvoidmouseDragged(MouseEvente){}publicvoidupdate(Graphicsg){}publicvoidpaint(Graphicsg){if(flag==1){}if}}publicstaticvoidmain(String[]args){newMouseDemo3();}}键盘处理keyPressed(KeyEventkeyReleased(KeyEvente)keyTyped(KeyEvente)importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassKeyDemoextendsKeyAdapterimplementsActionListener{JFramef=null;JLabellabel=null;JTextFieldtField=null;StringkeyString="";publicf=newContainercontentPane=f.getContentPane();contentPane.setLayout(newGridLayout(3,1));label=newJLabel();tField=newJTextField();JButtonb=newJButton("清除");newpublicvoidwindowClosing(WindowEvente){}}}publicvoidactionPerformed(ActionEvente){}publicvoidkeyTyped(KeyEvente){charc=e.getKeyChar();/*getKeyChar()的用法*/if(c=='o'){JFramenewF=newJFrame("新窗口");}}publicstaticvoidmain(String[]args){newKeyDemo();}}getKeyCode()getKeyModifiersText(intmodifiers).键盘上每一个按钮都有对应码(Code),可用来查知keyTyped()算是处理比较keyTyped()keyboadindependent,因为不同的键盘可能有不WindowsU.S.keyboardwindowsFrenchkeyboardgetKeyCode()keyPressedkeyReleased()方法中才会有效,因为这两个方法是处理比较低层的方法。getKeyModifiersText()方法可返回修饰键的字符串,如返回“Shift”字符串或是“Ctrl+Shift”packageimportjava.awt.Color;importjava.awt.FlowLayout;importimportimportimportjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjavax.swing.JButton;importjavax.swing.JDialog;importjavax.swing.JFrame;importjavax.swing.JTextField;import{JFramelist;JTextFieldshow;JButtonbc,c,ce,ab,jia,jian,cheng,chu,equ,point,sqrt,ds,JButtonb[newJButton[10]按钮数组,数字键doublesum=0,inti=0,j=0,p=0,l,action;JDialogabout;finalintslength30publicvoiddisp()listnewJFrame("简易计算器");list.setSize(360,230);list.setLocation(380,260);list.setLayout(newFlowLayout(FlowLayout.CENTER));show=newJTextField(31);PaneldispTop=newPanel();dispTop.setLayout(newGridLayout(1,4,3,3));bc=newJButton("Back ce=newJButton("CE");c=newJButton("C");ab=newJButton("About");aboutnewJDialog(list关于计算器Labelct=newLabel("http://w ",1);about.add(ct,"Center");about.setSize(200,about.setLocation(500,300);PaneldispMain=newPanel();dispMain.setLayout(newGridLayout(1,2,10,10));PaneldispLeft=newPanel();dispLeft.setLayout(newGridLayout(4,3,3,3));PaneldispRight=newPanel();dispRight.setLayout(newGridLayout(4,2,3,3));for(l=9;l>=0;l--){b[l]=newJButton(String.valueOf(l));}jia=newJButton("+");jian=newJButton("-");cheng=newJButton("*");chu=newJButton("/");equ=newJButton("=");point=newJButton(".");zf=newJButton("+/-sqrt=newJButton("sqrt");bfh=newJButton("%");ds=newJButton("1/x");}publicvoidactionPerformed(ActionEvente)getValue=if(e.getSource(jiaif(j==0)sum=}elseif(action==1){sum+=getValue;}p=i=action=elseif(e.getSource(jianif(j==0)sum=}elseif(action==2){sum-=getValue;}p=i=action=elseif(e.getSource(chengif(j==0)sum=}elseif(action==3){sum*=getValue;}p=i=action=elseif(e.getSource(chuif(j==sum=elseif(action==4){sum/=getValue;}p=i=action=elseif(e.getSource(equ等号,switch(action)caseshow.setText(String.valueOf(sum+=case2:show.setText(String.valueOf(sum-=case3:show.setText(String.valueOf(sum*=caseshow.setText(String.valueOf(sum/=

i=j=action=elseif(e.getSource(point小数点,if(p==show.setText(show.getText()+ p=1;elseif(e.getSource(c||e.getSource(cei=j=p=sum=action=0;elseif(e.getSource(bcStrings=if(s.length()>1)for(l0ls.length(1l++按一下,chara=s.charAt(l);show.setText(show.getText()+a);}}elseif(e.getSource(abelseif(e.getSource(sqrt开2次sum=Math.sqrt(getValue);i=elseif(e.getSource(dssum=1/getValue;i=elseif(e.getSource(bfhsum=getValue/100;i=elseif(e.getSource(zf正负号切换,Strings=chara=if(a=='-')for(l1ls.length()l++show.setText(show.getText()+}elseif(getValue0show.setText("-"+}}for(l0l10l++0~9if(e.getSource()==b[l])if(i==Strings=show.getText();if(s.length()<slength) if(e.getSource()==b[0]&&getValue==0&&p==0)if(e.getSource()!=b[0]&&getValue==0&&p==0) i++;/i}}}publicvoidsetSum(把计算结果显示出来Strings=show.getText();chara=s.charAt((s.length()-charb=s.charAt((s.length()-if(a'0&&b如果是整数,则去掉后面的小数点和0}}publicvoidwindowClosing(WindowEvente)if(e.getSource()==about)elseif(e.getSource()==list)}publicstaticvoidmain(Stringargs[])new}} 菜单 Item ItemShortcutpackageimportimportpublicclass privateFramefnewFrame("测试 Barmb=new file=new edit ItemnewItem=new ItemsaveItem= 创建exitItemCtrl+XItemexitItem Item("退出 ItemautoWrap=newCheckbox ItemcopyItem=new ItempasteItem format 创建commentItemCtrl+Shift+ItemcommentItem=new Item("注释",new KeyEvent.VK_SLASH,true));ItemcancelItem privateTextAreata=newTextArea(6,publicvoidinit()//以内部类的形式创建菜单 Listener=newActionListener()publicvoidactionPerformed(ActionEventeStringcmd= ta.append("单击cmd菜单"\n");if(cmd.equals("退出")){}}//为commentItem、exitItem两个菜单项添加了器。 为file菜单添加菜单项为edit使用addSeparator方法来添加菜单分隔线//为format菜单添加菜单项//使用添加new ////为f //以内部类的形式来创建器对f.addWindowListener(newWindowAdapter()publicvoidwindowClosing(WindowEvente}}publicstaticvoidmain(String[]args)new }}packageimportimportpublicclass privateTextAreata=newTextArea(4,privateFramef=newFrame("测试"); pop=newPopup ItemautoWrap=newCheckbox ItemcopyItem=new ItempasteItem format 创建commentItemCtrl+Shift+ItemcommentItem=new Item("注释",new KeyEvent.VK_SLASH,true));ItemcancelItem publicvoidinit()//以内部类的形式创建菜单 Listener=newActionListener()publicvoidactionPerformed(ActionEventeStringcmd= ta.append("单击cmd菜单"\n");if(cmd.equals("退出")){}} 为pop使用addSeparator方法来添加菜单分隔线//为format菜单添加菜单项//使用添加new //finalPanelp=newPanel();p.setPreferredSize(newDimension(300,160));//向p窗口中添加 对p.addMouseListener(newMouseAdapter()publicvoidmouseReleased(MouseEvente)if(e.isPopupTrigger()){pop.show(p,e.getX(),e.getY());}}f.add(ta,BorderLayout.NORTH);f.addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){}}publicstaticvoidmain(String[]args)new }}componentpaint(Graphicsg)其实,repaint调用 Graphics类,有这个类的对象就可以画图。new出来吗?paintupdateBufferedImage也可以获得画笔。Canvas类Jpanelpaintrepaint方法即可。packageimportjava.awt.*;importjava.awt.event.*;importpublicclassSimpleDrawprivatefinalStringRECT_SHAPE=privatefinalStringOVAL_SHAPE="oval";privateFramef=newFrame("简单绘图");privateButtonrectnewButton("绘制矩形");privateButtonovalnewButton("绘制圆形");privateMyCanvasdrawArea=newMyCanvas();//privateStringshape=publicvoidinit(){Panelp=newPanel();rect.addActionListener(newActionListener()publicvoidactionPerformed(ActionEvente)设置shape属性为RECT_SHAPEshape=RECT_SHAPE;//}oval.addActionListener(newActionListener()publicvoidactionPerformed(ActionEvente)设置shape属性为OVAL_SHAPEshape=OVAL_SHAPE;//}drawArea.setPreferredSize(newDimension(250,180));f.add(p,BorderLayout.SOUTH);}publicstaticvoidmain(String[]args)new}classMyCanvasextendsCanvas//publicvoidpaint(Graphicsg){Randomrand=newRandom();if(shape.equals(RECT_SHAPE))

g.setColor(newColor(220,100,g.drawRect(rand.nextInt(200),rand.nextInt(120),}

if(shape.equals(OVAL_SHAPE))g.setColor(newColor(80,100,g.fillOval(rand.nextInt(200),rand.nextInt(120),}}}}packageimportjava.awt.*;importjava.awt.event.*;importimportpublicclassPinBallprivatefinalintTABLE_WIDTH=privatefinalintTABLE_HEIGHT=privatefinalintRACKET_Y=privatefinalintRACKET_HEIGHT=privatefinalintRACKET_WIDTH=privatefinalintBALL_SIZE=16;privateFramefnewFrame("弹球游戏");Randomrand=newRandom();privateintySpeed=//privatedoublexyRate=rand.nextDouble()-privateintxSpeed=(int)(ySpeed*xyRate*ballX和ballYprivateintballX=rand.nextInt(200)+privateintballY=rand.nextInt(10)+racketXprivateintracketX=privateMyCanvastableArea=new//privateStringshape="";Timertimer;privatebooleanisLose=publicvoidinit()tableArea.setPreferredSize(newDimension(TABLE_WIDTH,//定义键盘KeyAdapterkeyProcessor=newKeyAdapter()publicvoidkeyPressed(KeyEventke)//if(ke.getKeyCode()==KeyEvent.VK_LEFT)if(racketX>0)racketX-=10;}if(ke.getKeyCode()==KeyEvent.VK_RIGHT)if(racketX<TABLE_WIDTH-racketX+=}}//为窗口和tableArea对象分别添加键盘器ActionListenertaskPerformer=newActionListener()publicvoidactionPerformed(ActionEventevt)if(ballX<=0||ballX>=TABLE_WIDTH-BALL_SIZE){xSpeed=-xSpeed;}//if(ballY>=RACKET_Y-&&(ballX<racketX||ballX>racketXRACKET_WIDTH))}

设置游戏是否结束的旗标为true。isLose=true;//elseif(ballY<=&&ballX<=+RACKET_WIDTH))ySpeed=-}//小球座标增加ballYySpeed;ballX}timer=newTimer(100,taskPerformer);}publicstaticvoidmain(String[]args)new}classMyCanvasextendsCanvas//publicvoidpaint(Graphicsg)if(isLose)g.setColor(newColor(255,0,0));g.setFont(newFont("Times"Font.BOLD30));g.drawString("游戏已结束!",50,200);}elseg.setColor(newColor(240,240,80));g.fillOval(ballX,ballY,BALL_SIZE,BALL_SIZE);g.setColor(newColor(80,80,200));g.fillRect(racketX,RACKET_Y,RACKET_WIDTH,}}}}packagecom.langsin.test4;importjava.awt.Color;publicclassHandDraw{privatefinalintAREA_WIDTH=privatefinalintAREA_HEIGHT=//下面的preX、preY保存了上一次鼠标拖动的鼠标座privateintpreX=-privateintpreY=- pop=new ItemredItem=new ItemgreenItem=new ItemblueItem=new //BufferedImageimage=newBufferedImage(AREA_WIDTH,AREA_HEIGHT,获取image对象的Graphicsg=privateJFramefnewJFrame("简单手绘程序privateDrawCanvasdrawArea=new//privateStringshape=privateColorforeColor=newColor(255,0,publicvoidinit()//定义右键菜单的器 Listener=newActionListener()publicvoidactionPerformed(ActionEvente)if( mand().equals("绿色foreColor=newColor(0,255,0);}if( mand().equals("红色foreColor=newColor(255,0,0);}if( mand().equals("蓝色foreColor=newColor(0,0,255);}}//为三个菜单添加器 将菜单项组合成右键菜单//g.fillRect(0,0,AREA_WIDTH,drawArea.setPreferredSize(newDimension(AREA_WIDTH,//鼠标移动动drawArea.addMouseMotionListener(newMouseMotionAdapter()//实现按下鼠标键并拖动的处理publicvoidmouseDragged(MouseEvente)如果preX和preY大于if(preX>0&&preY>0)//绘制从上一次鼠标拖动点到本次鼠标拖动点的线g.drawLine(preX,preY,e.getX(),}//将当前鼠标点的X、Y座标保存起preX=e.getX();preY=}

重绘drawArea//鼠标drawArea.addMouseListener(newMouseAdapter()//实现鼠标松开的处理publicvoidmouseReleased(MouseEvente)if(e.isPopupTrigger()){pop.show(drawArea,e.getX(),e.getY());}

//松开鼠标键时,把上一次鼠标拖动的X、Y座标设为-1preX=-preY=-}publicstaticvoidmain(String[]args)new}classDrawCanvasextendsJPanel//publicvoidpaint(Graphicsg)g.drawImage(image,0,0,}}}SwingJButtonadd(Actiona)voidaddSeparator(Dimensionsize)向的末尾添加指定大小的分隔voidsetFloatable(booleanb)voidsetMargin(Insetsm)voidsetOrientation(into)voidsetRollover(booleanrollover)设置是否是rollover状addActionActionListeneractionPerformednameicon两个属性。Action不仅可以作为器,还能转换成按钮或菜单项。ActionActionAction对象创 importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;importpublicclassTestJToolBarJFramejf=newJFrame("测试工具条");JTextAreajtanewJTextArea(635);JToolBarjtb=newJToolBar();JBarjmbnewJBar();JeditnewJ("编辑");Clipboardclipboard=//ActionpasteAction newImageIcon("ico/paste.png"))publicvoidactionPerformed(ActionEvente)//try//Stringcontent=(String) ceRange(content,jta.getSelectionStart(),}catch(Exceptionee){}}}//创建"ActioncopyAction= Action("",ImageIcon("ico/copy.png"))publicvoidactionPerformed(ActionEvente){StringSelectioncontents=newStringSelection(//clipboard.setContents(contents,//}}publicvoidinit()//pasteAction默认处于不激活状态jf.add(newJScrollPane(jta));//以Action创建按钮,并将该按钮添加到Panel中JButtoncopyBn=newJButton(copyAction);JButtonpasteBnnewJButton(pasteAction);JPaneljp=newJPanel();jf.add(jp,////将edit jtb.setMargin(newInsets(20,10,5,jf.add(jtb,BorderLayout.NORTH);}publicstaticvoidmain(String[]args)new}}JColorChooserJOptionPane用来创建简单框,无序手动添加组JOptionPane提供了4个方法创建框showMessageDialog与showInternalMessageDialog 件,类似javaScript的alert函数showConfirmDialog与showInternalMessageDialog showInputDialog与showInternalInputDialog showOptionDialog与showInternalOptionDialog自定义框

定义作为此框的父框的Component通过两种方式使用此参数:包含它的Frame可以用作框的父Frame,在框的位置使用其屏幕坐标一般情况下将框紧靠组件置于其之下。nullFrame且框将居中位于屏幕上(取决于L&F)。要置于框中的描述消息。在最常见的应用中,message就是一StringStringObject。message(每个对象该Component在框中显示该Icon被包装在JLabel中并在框中显示。toStringString。结果被包装在JLabel中显示。

定义message的样式。外观管理器根据此值对框进行不同地

定义在框的底部显示的选项按钮的集合options

将在框底部显示的选项按钮集合的更详细描述options参数StringObject创建的JButton以此图标作为其。ObjecttoString果作为JButton的。要置于框中的装饰性图标。图标的默认值由messageType参默认选择(输入值)当选择更改时,调用生成PropertyChangeEvent的setValuesetWantsInputJOptionPane,则还可以侦听绑定属性JOptionPane.INPUT_VALUE_PROPERTY,以确定何时用户输入或选择了值。当其中一个showXxxDialog显示一个错误框,该框显示的message为'alert':JOptionPane.showMessageDialog(null,"alert","alert",显示一个内部信息框,其message为'information':JOptionPane.showInternalMessageDialog(frame,"information","information",options"yes/no",message'chooseone':"chooseone","chooseone",显示一个内部信息框,其options为"yes/no/cancel",message'pleasechooseone',并具有title"pleasechooseone","information",显示一个警告框其options为OKCANCELtitle为'Warning'message为'ClickOKtoObject[]options={"OK","CANCEL"};JOptionPane.showOptionDialog(null,"ClickOKtocontinue",null,options,options[0]);显示一个要求用户键入String的框StringinputValue=JOptionPane.showInputDialog("Pleaseinputa显示一个要求用户选择String的框Object[]possibleValues={"First","Second","Third"};ObjectselectedValue=JOptionPane.showInputDialog(null,"Chooseone","Input",JOptionPane.INFORMATION_MESSAGE,null,possibleValues,possibleValues[0]);packageimportimportimportjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JOptionPane;publicclassTestJOptionPanepublicstaticvoidmain(String[]args){finalJFramejf=newJFrame();JButtonjb=newJButton("ok");jb.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente)//TODOAuto-generatedmethod// "information", inti "chooseone","chooseone", "pleasechooseone", Object[]options={"OK","CANCEL" null,options, StringinputValue=JOptionPane.showInputDialog("Pleaseinputavalue");"Chooseone","Input",JOptionPane.INFORMATION_MESSAGE,null,possibleValues,possibleValues[0]);}}}要直接创建和使用JOptionPane,标准模式大致如下:JOptionPanepanenewJOptionPane(arguments);pane.set.Xxxx(...);//ConfigureJDialogdialog=pane.createDialog( ObjectselectedValue=pane.getValue();if(selectedValue==null)return//Ifthereisnotanarrayofoptionif(options==null)if(selectedValueinstanceofreturn((Integer)selectedValue).intValue();returnCLOSED_OPTION;}//Ifthereisanarrayofoptionfor(intcounter=0,maxCounter=options.length;counter<maxCounter;counter++){returncounter;}returnJSplitPanejsnewJSplitPane(方向,左|上组件,右|下组件newContinusLayoutpackageimportimportpublicclassTestSplitPane{JPaneljp1=newJPanel();JPaneljp2=newJPanel();JPaneljp3=newpublicvoidinit()JFramejfnewJFrame("测试jp1.setPreferredSize(newDimension(150,jp2.setPreferredSize(newDimension(300,jp3.setPreferredSize(newDimension(300,}

new打开“一触即展”////publicstaticvoidmain(String[]args)new}}packageimportjava.awt.*;importjava.awt.event.*;importjava.util.*;importjavax.swing.*;importpublicclassTestJTabbedPaneJPaneljp1=newJPanel();JPaneljp2=newJPanel();JPaneljp3=newJPanel();JPaneljp4=newJPanel();JPaneljp5=newJFramejfnewJFrame("测试Tab页面//创建一个Tab页面的放在左边,采用换行布局策略的JTabbedPaneJTabbedPanetabbedPanenewJTabbedPane(JTabbedPane.LEFT,String[]layouts={"换行布局","滚动条布局"};String[positions左边顶部右边底部publicvoidinit(){Stringtip测试提示";组件为tabbedPane.addTab("jp1",null,null,tip);tabbedPane.addTab("jp2",null,null,tip);tabbedPane.addTab("jp3",null,null,tip);tabbedPane.addTab("jp4",null,null,tip);tabbedPane.addTab("jp5",null,null,tip);jf.add(tabbedPane,BorderLayout.CENTER);tabbedPane.addChangeListener(newChangeListener()publicvoidstateChanged(ChangeEventevent)if ponent()==null)获取所选Tabintn=}}tabbedPane.setPreferredSize(newDimension(500,//增加控制布局、位置的单选按JPanelbuttonPanel=newJPanel();ChangeActionaction=newChangeAction();buttonPanel.add(newButtonPanel(action,"选择布局策略buttonPanel.add(newButtonPanel(action,"选择位置",jf.add(buttonPanel,BorderLayout.SOUTH);}//为指定页加载内privatevoidloadTab(intn)Stringtitle=//根据页的标题获取对应封}//定义改变页的布局策略,放置位置的classChangeActionimplementsActionListenerpublicvoidactionPerformed(ActionEventevent){JRadioButtonsource=(JRadioButton)event.getSource();Stringselection=s if(selection.equals(layouts[0]))}elseif(selection.equals(layouts[1])) }elseif(selection.equals(positions[0])){ }elseif(selection.equals(positions[1])){ }elseif(selection.equals(positions[2])){ }elseif(selection.equals(positions[3])){}}}publicstaticvoidmain(String[]args)new}}////classButtonPanelextendsJPanelprivateButtonGrouppublicButtonPanel(TestJTabbedPane.ChangeActionaction,StringString[]labels){BorderFactory.createEtchedBorder(),title));setLayout(newBoxLayout(this,BoxLayout.X_AXIS));group=newButtonGroup();for(inti=0;labels!=null&&i<labels.length;i++){JRadioButtonb=newJRadioButton(labels[i]);//添加器b.setSelected(i==0);}}} 创建一个空的TabbedPane,使其具有以下指定选项卡布局中的一种: JTabbedPane.TOPTabbedPane创建一个空的创建一个空的) cement,intJTabbedPane.RIGHTtabcement,指定页的放置位置。这里有四个位置:JTabbedPane.TOP、JTabbedPane.BOTTOM、JTabbedPane.LEFT或JTabbedPane.RIGHT。tabLayout是布局策略,换行还是滚动 如果需要让某个页显示,使setSelectedIndexaddChangeListener方法这个是代表一个有位置深度也就是有z轴的容器,可以实现组件。packagecom.langsin.test4;importjavax.swing.*;importjava.awt.*;publicclassTestJLayeredPaneJFramejf=newJFrame("测试JLayeredPane");JLayeredPanelayeredPanenewJLayeredPane();publicvoidinit()JPaneljp1newMyPanel(1020面板1面板1面板1面板1");jp1.add(newJButton("OK"));JPaneljp2newMyPanel(10060面板2面板2面板2面板2");jp2.add(newJButton("OK"));JPaneljp3newMyPanel(190100面板3面板3面板3面板3");jp3.ad

温馨提示

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

评论

0/150

提交评论