PackageCom.graphics;Importjava.awt.*;ImportJava.awt.geom.Rectangle2D;Importjava.util.Date;Importjavax.swing.*;/** * * @authorBiexiansheng **/ Public classDrawStringextendsjframe{PrivateShape rect;//Rectangle Object PrivateFont font;//Font Object PrivateDate date;//Current Date Object Publicdrawstring () {rect=NewRectangle2d.double (10, 10, 200, 80); Font=NewFont ("Arial", font.bold,16); Date=NewDate (); This. SetSize (230,140);//set the size of a form//set how forms are closedsetdefaultcloseoperation (windowconstants.exit_on_close); Add (NewCanvaspanel ());//set the form panel as a drawing panel object This. Settitle ("drawing text");//set the form title } classCanvaspanelextendsjpanel{ Public voidPaint (Graphics g) {Super. Paint (g); Graphics2D G2= (graphics2d) g;//Forcing type conversionsG2.setcolor (Color.cyan);//set the current drawing colorG2.fill (rect);//Fill RectangleG2.setcolor (Color.Blue);//set the current drawing colorG2.setfont (font);//Set FontG2.drawstring ("The Time is now", 20, 30);//Draw TextG2.drawstring (String.Format ("%tr", date), 50, 60);//Draw Event Text } } Public Static voidMain (string[] args) {//TODO auto-generated Method StubDrawString ds=NewDrawString ();//Ds.setvisible (true); }}
The results of the instance run are
PackageCom.graphics;ImportJava.awt.Canvas;ImportJava.awt.Graphics;ImportJava.awt.Graphics2D;ImportJava.awt.Image;ImportJava.awt.Toolkit;ImportJava.net.URL;ImportJavax.swing.JFrame;Importjavax.swing.WindowConstants;/*** 1: Draw picture * Drawing class can not only draw graphics and text, but also use the DrawImage () method to display the picture resources in the drawing context * and to achieve various effects processing, slice scaling, flipping, etc. * syntax as follows *drawimage (Image Img,int x , int y,imageobserver observer); * This method puts the IMG image above the x, Y specified position, observer is the image viewer to be notified*/ Public classDrawImageextendsJFrame {Image img; PublicDrawImage () {URL URL=drawimage.class. GetResource ("1.jpg");//get the path to a picture resourceImg=toolkit.getdefaulttoolkit (). GetImage (URL);//Get Picture Resources This. setSize (250, 200);//set the size of a form//set how forms are closedsetdefaultcloseoperation (windowconstants.exit_on_close); Add (NewCanvaspanel ());//set the form panel as a drawing panel object This. Settitle ("Drawing Pictures"); } classCanvaspanelextendscanvas{ Public voidPaint (Graphics g) {Super. Paint (g); Graphics2D G2=(graphics2d) G; G2.drawimage (IMG,0,0, This);//Show Pictures } } Public Static voidMain (string[] args) {DrawImage di=NewDrawImage ();//Di.setvisible (true); }}
Drawing a picture instance runs the result as follows
Java Learning drawing colors and their stroke properties setting font display text