版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
AWTAWTswingGUI類庫。swingawt布局繪比如按鈕,文本框等ContainerComponent的子類,容器本身也是一個(gè)組件。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);}}像流水一樣向某方向自動(dòng)排列,遇到折回。默認(rèn)是向右packageimportimportstaticpublicclassTestFlowLayoutpublicstaticvoidmain(String[]args){Framef=newFrame("測(cè)試窗口");f.setLayout(newFlowLayout(LEFT205));for(inti=0;i<20;i++){f.add(newButton("按鈕}}}5個(gè)區(qū)域:東西南北中。packageimportimportstaticpublicclassTestFlowLayoutpublicstaticvoidmain(String[]args){Framef=newFrame("測(cè)試窗口");f.setLayout(newFlowLayout(LEFT205));for(inti=0;i<20;i++){f.add(newButton("按鈕}}}packageimportimportstaticpublicclasspublicstaticvoidmain(String[]{Framef=newFrame("測(cè)試窗口");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("測(cè)試窗口");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){}控制根據(jù)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("測(cè)試publicvoid{f.setLayout(newBoxLayout(fBoxLayout.Y_AXIS));f.add(newButton("第一個(gè)按鈕"));f.add(newButton("第二個(gè)按鈕}publicstaticvoidmain(String[]args)new}}另外,BoxLayoutBox容器一起使用,Boxpackagecom.lx.test2;importjava.awt.*;importpublicclassprivateFramefnewFrame("測(cè)試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 創(chuàng)建一個(gè)水平的Glue createVerticalGlue創(chuàng)建一個(gè)垂直的Glue可以在兩個(gè)方向同時(shí)拉伸間距createHorizontalStrut(intwidth)創(chuàng)建一個(gè)指定寬度水平的Strut可以在垂直方向上拉伸間距createVerticalStrut(intheight)創(chuàng)建一個(gè)指定高度的垂直Strut createRigidArea(Dimensiond)創(chuàng)建指定寬度和高度的RigidArea packageimportimportpublicclassTestBoxSpaceprivateFramefnewFrame("測(cè)試定義水平擺放組件的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("測(cè)試");ButtonoknewButton("確認(rèn)CheckboxGroupcbg=new//CheckboxmalenewCheckbox("男cbg//CheckboxfemalenewCheckbox("女cbg//CheckboxmarriednewCheckbox("是否已婚?ChoicecolorChooser=newListcolorList=newList(6,TextAreata=newTextArea(5,定義一個(gè)50TextFieldname=newpublicvoidinit(){創(chuàng)建一個(gè)裝載了文本框、按鈕的PanelPanelbottom=newPanel();f.add(bottom,創(chuàng)建一個(gè)裝載了下拉選擇框、三個(gè)Checkbox的PanelPanelcheckPanel=newPanel();創(chuàng)建一個(gè)垂直排列組件的Box,盛裝多行文本域、PanelBoxtopLeft=Box.createVerticalBox();創(chuàng)建一個(gè)垂直排列組件的Box,盛裝topLeft、colorListBoxtop=Box.createHorizontalBox();將topBox容器添加到窗口的中間}publicstaticvoidmain(String[]args) }}window類的子類,是一個(gè)容器,與普通窗口的用法完全一樣。它的構(gòu)造方法有三個(gè)參數(shù)分別是packageimportimportpublicclassTestDialog{FramefnewFrame("測(cè)試");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("測(cè)試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現(xiàn)(Implement)!我們把區(qū)分成是由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中提供兩個(gè)方法讓你知道到底是哪個(gè)組件觸發(fā)了,那就是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個(gè)方法都實(shí)現(xiàn),如果不想實(shí)*可用內(nèi)部類的方法編寫處理程序publicclassMouseDemo1extendsWindowAdapterimplementsMouseListener{JFramef=null;JButtonJLabelpublicf=newContainercontentPane=f.getContentPane();contentPane.setLayout(newGridLayout(2,1));b1=newJButton("按鈕");label=newJLabel("起始狀態(tài),還沒有鼠標(biāo)",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;//起始坐標(biāo)與終點(diǎn)坐標(biāo)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).鍵盤上每一個(gè)按鈕都有對(duì)應(yīng)碼(Code),可用來查知keyTyped()算是處理比較keyTyped()keyboadindependent,因?yàn)椴煌逆I盤可能有不WindowsU.S.keyboardwindowsFrenchkeyboardgetKeyCode()keyPressedkeyReleased()方法中才會(huì)有效,因?yàn)檫@兩個(gè)方法是處理比較低層的方法。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]按鈕數(shù)組,數(shù)字鍵doublesum=0,inti=0,j=0,p=0,l,action;JDialogabout;finalintslength30publicvoiddisp()listnewJFrame("簡易計(jì)算器");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關(guān)于計(jì)算器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等號(hào),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小數(shù)點(diǎn),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正負(fù)號(hào)切換,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(把計(jì)算結(jié)果顯示出來Strings=show.getText();chara=s.charAt((s.length()-charb=s.charAt((s.length()-if(a'0&&b如果是整數(shù),則去掉后面的小數(shù)點(diǎn)和0}}publicvoidwindowClosing(WindowEvente)if(e.getSource()==about)elseif(e.getSource()==list)}publicstaticvoidmain(Stringargs[])new}} 菜單 Item ItemShortcutpackageimportimportpublicclass privateFramefnewFrame("測(cè)試 Barmb=new file=new edit ItemnewItem=new ItemsaveItem= 創(chuàng)建exitItemCtrl+XItemexitItem Item("退出 ItemautoWrap=newCheckbox ItemcopyItem=new ItempasteItem format 創(chuàng)建commentItemCtrl+Shift+ItemcommentItem=new Item("注釋",new KeyEvent.VK_SLASH,true));ItemcancelItem privateTextAreata=newTextArea(6,publicvoidinit()//以內(nèi)部類的形式創(chuàng)建菜單 Listener=newActionListener()publicvoidactionPerformed(ActionEventeStringcmd= ta.append("單擊cmd菜單"\n");if(cmd.equals("退出")){}}//為commentItem、exitItem兩個(gè)菜單項(xiàng)添加了器。 為file菜單添加菜單項(xiàng)為edit使用addSeparator方法來添加菜單分隔線//為format菜單添加菜單項(xiàng)//使用添加new ////為f //以內(nèi)部類的形式來創(chuàng)建器對(duì)f.addWindowListener(newWindowAdapter()publicvoidwindowClosing(WindowEvente}}publicstaticvoidmain(String[]args)new }}packageimportimportpublicclass privateTextAreata=newTextArea(4,privateFramef=newFrame("測(cè)試"); pop=newPopup ItemautoWrap=newCheckbox ItemcopyItem=new ItempasteItem format 創(chuàng)建commentItemCtrl+Shift+ItemcommentItem=new Item("注釋",new KeyEvent.VK_SLASH,true));ItemcancelItem publicvoidinit()//以內(nèi)部類的形式創(chuàng)建菜單 Listener=newActionListener()publicvoidactionPerformed(ActionEventeStringcmd= ta.append("單擊cmd菜單"\n");if(cmd.equals("退出")){}} 為pop使用addSeparator方法來添加菜單分隔線//為format菜單添加菜單項(xiàng)//使用添加new //finalPanelp=newPanel();p.setPreferredSize(newDimension(300,160));//向p窗口中添加 對(duì)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)其實(shí),repaint調(diào)用 Graphics類,有這個(gè)類的對(duì)象就可以畫圖。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)設(shè)置shape屬性為RECT_SHAPEshape=RECT_SHAPE;//}oval.addActionListener(newActionListener()publicvoidactionPerformed(ActionEvente)設(shè)置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對(duì)象分別添加鍵盤器ActionListenertaskPerformer=newActionListener()publicvoidactionPerformed(ActionEventevt)if(ballX<=0||ballX>=TABLE_WIDTH-BALL_SIZE){xSpeed=-xSpeed;}//if(ballY>=RACKET_Y-&&(ballX<racketX||ballX>racketXRACKET_WIDTH))}
設(shè)置游戲是否結(jié)束的旗標(biāo)為true。isLose=true;//elseif(ballY<=&&ballX<=+RACKET_WIDTH))ySpeed=-}//小球座標(biāo)增加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("游戲已結(jié)束!",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保存了上一次鼠標(biāo)拖動(dòng)的鼠標(biāo)座privateintpreX=-privateintpreY=- pop=new ItemredItem=new ItemgreenItem=new ItemblueItem=new //BufferedImageimage=newBufferedImage(AREA_WIDTH,AREA_HEIGHT,獲取image對(duì)象的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("藍(lán)色foreColor=newColor(0,0,255);}}//為三個(gè)菜單添加器 將菜單項(xiàng)組合成右鍵菜單//g.fillRect(0,0,AREA_WIDTH,drawArea.setPreferredSize(newDimension(AREA_WIDTH,//鼠標(biāo)移動(dòng)動(dòng)drawArea.addMouseMotionListener(newMouseMotionAdapter()//實(shí)現(xiàn)按下鼠標(biāo)鍵并拖動(dòng)的處理publicvoidmouseDragged(MouseEvente)如果preX和preY大于if(preX>0&&preY>0)//繪制從上一次鼠標(biāo)拖動(dòng)點(diǎn)到本次鼠標(biāo)拖動(dòng)點(diǎn)的線g.drawLine(preX,preY,e.getX(),}//將當(dāng)前鼠標(biāo)點(diǎn)的X、Y座標(biāo)保存起preX=e.getX();preY=}
重繪drawArea//鼠標(biāo)drawArea.addMouseListener(newMouseAdapter()//實(shí)現(xiàn)鼠標(biāo)松開的處理publicvoidmouseReleased(MouseEvente)if(e.isPopupTrigger()){pop.show(drawArea,e.getX(),e.getY());}
//松開鼠標(biāo)鍵時(shí),把上一次鼠標(biāo)拖動(dòng)的X、Y座標(biāo)設(shè)為-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)設(shè)置是否是rollover狀addActionActionListeneractionPerformednameicon兩個(gè)屬性。Action不僅可以作為器,還能轉(zhuǎn)換成按鈕或菜單項(xiàng)。ActionActionAction對(duì)象創(chuàng) importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;importpublicclassTestJToolBarJFramejf=newJFrame("測(cè)試工具條");JTextAreajtanewJTextArea(635);JToolBarjtb=newJToolBar();JBarjmbnewJBar();JeditnewJ("編輯");Clipboardclipboard=//ActionpasteAction newImageIcon("ico/paste.png"))publicvoidactionPerformed(ActionEvente)//try//Stringcontent=(String) ceRange(content,jta.getSelectionStart(),}catch(Exceptionee){}}}//創(chuàng)建"ActioncopyAction= Action("",ImageIcon("ico/copy.png"))publicvoidactionPerformed(ActionEvente){StringSelectioncontents=newStringSelection(//clipboard.setContents(contents,//}}publicvoidinit()//pasteAction默認(rèn)處于不激活狀態(tài)jf.add(newJScrollPane(jta));//以Action創(chuàng)建按鈕,并將該按鈕添加到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用來創(chuàng)建簡單框,無序手動(dòng)添加組JOptionPane提供了4個(gè)方法創(chuàng)建框showMessageDialog與showInternalMessageDialog 件,類似javaScript的alert函數(shù)showConfirmDialog與showInternalMessageDialog showInputDialog與showInternalInputDialog showOptionDialog與showInternalOptionDialog自定義框
定義作為此框的父框的Component通過兩種方式使用此參數(shù):包含它的Frame可以用作框的父Frame,在框的位置使用其屏幕坐標(biāo)一般情況下將框緊靠組件置于其之下。nullFrame且框?qū)⒕又形挥谄聊簧希ㄈQ于L&F)。要置于框中的描述消息。在最常見的應(yīng)用中,message就是一StringStringObject。message(每個(gè)對(duì)象該Component在框中顯示該Icon被包裝在JLabel中并在框中顯示。toStringString。結(jié)果被包裝在JLabel中顯示。
定義message的樣式。外觀管理器根據(jù)此值對(duì)框進(jìn)行不同地
定義在框的底部顯示的選項(xiàng)按鈕的集合options
將在框底部顯示的選項(xiàng)按鈕集合的更詳細(xì)描述options參數(shù)StringObject創(chuàng)建的JButton以此圖標(biāo)作為其。ObjecttoString果作為JButton的。要置于框中的裝飾性圖標(biāo)。圖標(biāo)的默認(rèn)值由messageType參默認(rèn)選擇(輸入值)當(dāng)選擇更改時(shí),調(diào)用生成PropertyChangeEvent的setValuesetWantsInputJOptionPane,則還可以偵聽綁定屬性JOptionPane.INPUT_VALUE_PROPERTY,以確定何時(shí)用戶輸入或選擇了值。當(dāng)其中一個(gè)showXxxDialog顯示一個(gè)錯(cuò)誤框,該框顯示的message為'alert':JOptionPane.showMessageDialog(null,"alert","alert",顯示一個(gè)內(nèi)部信息框,其message為'information':JOptionPane.showInternalMessageDialog(frame,"information","information",options"yes/no",message'chooseone':"chooseone","chooseone",顯示一個(gè)內(nèi)部信息框,其options為"yes/no/cancel",message'pleasechooseone',并具有title"pleasechooseone","information",顯示一個(gè)警告框其options為OKCANCELtitle為'Warning'message為'ClickOKtoObject[]options={"OK","CANCEL"};JOptionPane.showOptionDialog(null,"ClickOKtocontinue",null,options,options[0]);顯示一個(gè)要求用戶鍵入String的框StringinputValue=JOptionPane.showInputDialog("Pleaseinputa顯示一個(gè)要求用戶選擇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]);}}}要直接創(chuàng)建和使用JOptionPane,標(biāo)準(zhǔn)模式大致如下: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("測(cè)試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("測(cè)試Tab頁面//創(chuàng)建一個(gè)Tab頁面的放在左邊,采用換行布局策略的JTabbedPaneJTabbedPanetabbedPanenewJTabbedPane(JTabbedPane.LEFT,String[]layouts={"換行布局","滾動(dòng)條布局"};String[positions左邊頂部右邊底部publicvoidinit(){Stringtip測(cè)試提示";組件為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);}//為指定頁加載內(nèi)privatevoidloadTab(intn)Stringtitle=//根據(jù)頁的標(biāo)題獲取對(duì)應(yīng)封}//定義改變頁的布局策略,放置位置的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);}}} 創(chuàng)建一個(gè)空的TabbedPane,使其具有以下指定選項(xiàng)卡布局中的一種: JTabbedPane.TOPTabbedPane創(chuàng)建一個(gè)空的創(chuàng)建一個(gè)空的) cement,intJTabbedPane.RIGHTtabcement,指定頁的放置位置。這里有四個(gè)位置:JTabbedPane.TOP、JTabbedPane.BOTTOM、JTabbedPane.LEFT或JTabbedPane.RIGHT。tabLayout是布局策略,換行還是滾動(dòng) 如果需要讓某個(gè)頁顯示,使setSelectedIndexaddChangeListener方法這個(gè)是代表一個(gè)有位置深度也就是有z軸的容器,可以實(shí)現(xiàn)組件。packagecom.langsin.test4;importjavax.swing.*;importjava.awt.*;publicclassTestJLayeredPaneJFramejf=newJFrame("測(cè)試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等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 汽車配件訂購協(xié)議
- 疫情防治藥品緊急采購協(xié)議
- 婚慶策劃合作細(xì)則
- 用功學(xué)習(xí)保證書
- 房屋買賣意向書簽訂注意事項(xiàng)詳解
- 采購代表合同樣式
- 生態(tài)休閑農(nóng)業(yè)項(xiàng)目規(guī)劃案
- 外墻裂紋修補(bǔ)涂料樣本
- 標(biāo)準(zhǔn)貸款合同格式
- 鋁合金建筑材料購銷協(xié)議
- 并購功夫:2015本土并購十大經(jīng)典案例詳解
- 宇通客車新媒體運(yùn)營與傳播方案
- 國家開放大學(xué)《行政組織學(xué)》形考1-5標(biāo)準(zhǔn)答案
- 租賃房屋交接清單49226
- 公司4M變更申請(qǐng)通知書
- 2014高考語文一輪復(fù)習(xí)課外文言訓(xùn)練-文天祥傳
- 國開作業(yè)《建筑制圖基礎(chǔ)》學(xué)習(xí)過程表現(xiàn)參考22
- 《愚公移山》比較閱讀16篇(歷年中考語文文言文閱讀試題匯編)(含答案與翻譯)(截至2021年)
- 食品安全BRCGS包裝材料全球標(biāo)準(zhǔn)第六版管理手冊(cè)及程序文件
- 物流公司人員配置及崗位職責(zé)(6篇)
- DB11-T1497-2017學(xué)校及托幼機(jī)構(gòu)飲水設(shè)備使用維護(hù)規(guī)范
評(píng)論
0/150
提交評(píng)論