Showing posts with label Java 2D Programming. Show all posts
Showing posts with label Java 2D Programming. Show all posts

Monday, September 19, 2011

Drawing a Ractangle with rounded corners using Java 2D Graphics API

package org.best.example;


import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.RoundRectangle2D;
/**
 * Displays a JFrame and draws a rounded ractangle on it using the Java 2D Graphics API
 *
 * */

public class Java2DFrame extends javax.swing.JFrame {
   
    /**
     * Creates a new instance of Java2DFrame
     */

    public Java2DFrame() {
        initComponents();
    }
   
    /**
     * This is the method where the rounded rectangle is drawn.
     *
     * @param g The graphics object
     */

    public void paint(Graphics g) {
        Graphics2D graphics2 = (Graphics2D) g;
        RoundRectangle2D roundedRectangle = new RoundRectangle2D.Float(100, 100, 240, 160, 10, 10);
        graphics2.draw(roundedRectangle);
    }
   
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 300, Short.MAX_VALUE)
        );
        pack();
    }// </editor-fold>
   
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Java2DFrame().setVisible(true);
            }
        });
    }
}

Sunday, September 18, 2011

GeneralPaths

package org.best.example;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

public class GeneralPaths extends Frame {
  public static void main( String[] argv ) {
    GeneralPaths myExample = new GeneralPaths( "General Paths" );
  }

  public GeneralPaths( String title ) {
    super( title );
    setSize( 300, 180 );
    addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent we ) {
        dispose();
        System.exit( 0 );
      }
    } );
    setVisible( true );
  }

  public void paint( Graphics g ) {
    Graphics2D g2d = (Graphics2D) g;
    GeneralPath gp1 = new GeneralPath( GeneralPath.WIND_EVEN_ODD );
    GeneralPath gp2 = new GeneralPath( GeneralPath.WIND_EVEN_ODD );
    gp1.moveTo( 20, 30 );
    gp1.lineTo( 150, 30 );
    gp1.lineTo( 150, 130 );
    gp1.closePath();
    gp2.moveTo( 180, 30 );
    gp2.lineTo( 290, 30 );
    gp2.quadTo( 200, 75, 180, 130 );
    gp2.curveTo( 110, 50, 220, 100, 180, 30 );
    g2d.setPaint( loadTextureResource( "1.gif" ) );
    g2d.fill( gp1 );
    g2d.fill( gp2 );

  }


  public TexturePaint loadTextureResource( String absfilename ) {
    MediaTracker tracker = new MediaTracker( this );
    Image imtexture = Toolkit.getDefaultToolkit().getImage( absfilename );
    tracker.addImage( imtexture, 0 );
    try {
      tracker.waitForID( 0 );
      int width = imtexture.getWidth( this );
      int height = imtexture.getHeight( this );
      System.out.println( "width" + width + " height =" + height );
      BufferedImage buffImg = new
          BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
      Graphics g = buffImg.getGraphics();
      g.drawImage( imtexture, 0, 0, this );
      return new TexturePaint( buffImg, new Rectangle2D.Double( 0, 0, width, height ) );
    }
    catch( Exception e ) {
      System.out.println( "Exception on Image-Texture Loading" );
    }
    return null;
  }
}

Saturday, September 17, 2011

FontLister

package org.best.example;

import java.awt.*;

public class FontLister {

  public static void main( String[] argv ) {
    Font fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
    for( int i = 0; i < fonts.length; i++ ) {
      System.out.println( i + " font=" + fonts[i] );
    }
    Font myFont = fonts[2].deriveFont( Font.BOLD, 32 );
  }
}

Friday, September 16, 2011

Drawing two rectangles

package org.best.example;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;

public class DrawingTwoRectangles extends Frame {
  public static void main( String[] argv ) {
    DrawingTwoRectangles myExample = new DrawingTwoRectangles( "Drawing rectangles using the 2D api" );
  }

  public DrawingTwoRectangles( String title ) {
    super( title );
    setSize( 300, 180 );
    addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent we ) {
        dispose();
        System.exit( 0 );
      }
    } );
    setVisible( true );
  }

  public void paint( Graphics g ) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor( Color.red );
    Rectangle2D rect1 = new Rectangle2D.Double( 32, 42, 100, 100 );
    Rectangle2D rect2 = new Rectangle2D.Double( 164, 42, 100, 100 );
    g2d.fill( rect1 );
    g2d.draw( rect2 );
  }
}

Thursday, September 15, 2011

Drawing Shapes in Java

package org.best.example;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;

public class Shapes2 extends JFrame
    {
     public Shapes2()
         {
         super( "Drawing 2D Shapes" );
         setBackground( Color.yellow );
         setSize( 400, 400 );
         show();
     }
   
     public void paint( Graphics g )
         {
         int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
         int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
       
         Graphics2D g2d = ( Graphics2D ) g;
       
         // create a star from a series of points
         GeneralPath star = new GeneralPath();
       
         // set the initial coordinate of the General Path
         star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );
       
         // create the star--this does not draw the star
         for ( int k = 1; k < xPoints.length; k++ )
         star.lineTo( xPoints[ k ], yPoints[ k ] );
       
         // close the shape
         star.closePath();
       
         // translate the origin to (200, 200)
         g2d.translate( 200, 200 );
       
         // rotate around origin and draw stars in random colors
         for ( int j = 1; j <= 20; j++ )
             {
             g2d.rotate( Math.PI / 10.0 );
             g2d.setColor(new Color( ( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ),
             ( int ) ( Math.random() * 256 ) ) );
             g2d.fill( star ); // draw a filled star
         }
     }
   
     public static void main( String args[] )
         {
         Shapes2 app = new Shapes2();
       
         app.addWindowListener(new WindowAdapter()
             {
             public void windowClosing( WindowEvent e )
                 {
                 System.exit( 0 );
             }
         });
     }
}

Wednesday, September 14, 2011

Demonstrating some Java2D shapes

package org.best.example;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;

public class Shapes extends JFrame
     {
     public Shapes()
         {
         super( "Drawing 2D shapes" );
       
         setSize( 425, 160 );
         show();
     }
   
     public void paint( Graphics g )
         {
         // create 2D by casting g to Graphics2D
         Graphics2D g2d = ( Graphics2D ) g;
       
         // draw 2D ellipse filled with a blue-yellow gradient
         g2d.setPaint( new GradientPaint( 5, 30, // x1, y1
         Color.blue, // initial Color
         35, 100, // x2, y2
         Color.yellow, // end Color
         true ) ); // cyclic
         g2d.fill( new Ellipse2D.Double( 5, 30, 65, 100 ) );
       
         // draw 2D rectangle in red
         g2d.setPaint( Color.red );
         g2d.setStroke( new BasicStroke( 10.0f ) );
         g2d.draw( new Rectangle2D.Double( 80, 30, 65, 100 ) );
       
         // draw 2D rounded rectangle with a buffered background
         BufferedImage buffImage = new BufferedImage( 10, 10, BufferedImage.TYPE_INT_RGB );
       
         Graphics2D gg = buffImage.createGraphics();
         gg.setColor( Color.yellow ); // draw in yellow
         gg.fillRect( 0, 0, 10, 10 ); // draw a filled rectangle
         gg.setColor( Color.black ); // draw in black
         gg.drawRect( 1, 1, 6, 6 ); // draw a rectangle
         gg.setColor( Color.blue ); // draw in blue
         gg.fillRect( 1, 1, 3, 3 ); // draw a filled rectangle
         gg.setColor( Color.red ); // draw in red
         gg.fillRect( 4, 4, 3, 3 ); // draw a filled rectangle
       
         // paint buffImage onto the JFrame
         g2d.setPaint( new TexturePaint( buffImage, new Rectangle( 10, 10 ) ) );
         g2d.fill( new RoundRectangle2D.Double( 155, 30, 75, 100, 50, 50 ) );
       
         // draw 2D pie-shaped arc in white
         g2d.setPaint( Color.white );
         g2d.setStroke( new BasicStroke( 6.0f ) );
         g2d.draw( new Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) );
       
         // draw 2D lines in green and yellow
         g2d.setPaint( Color.green );
         g2d.draw( new Line2D.Double( 395, 30, 320, 150 ) );
       
         float dashes[] = { 10 };
       
         g2d.setPaint( Color.yellow );
         g2d.setStroke( new BasicStroke( 4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10, dashes, 0 ) );
         g2d.draw( new Line2D.Double( 320, 30, 395, 150 ) );
     }
   
     public static void main( String args[] )
         {
         Shapes app = new Shapes();
       
         app.addWindowListener( new WindowAdapter()
             {
             public void windowClosing( WindowEvent e )
                 {
                 System.exit( 0 );
             }
         });
     }
}

Tuesday, September 13, 2011

Draw or Delete lines from JPanel

package org.best.example;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Line2D;
import javax.swing.*;

public class LineUnder extends JFrame
    {
     LinePanel linePanel = new LinePanel();
     LineUnder()
         {
         setDefaultCloseOperation(EXIT_ON_CLOSE);
         initContentPane();
         pack();
         setLocationRelativeTo(null);
         setVisible(true);
     }
     private void initContentPane()
         {
         linePanel.line.setLine(0d, 0d, 300d, 300d);
         getContentPane().add(linePanel);
     }
   
     class LinePanel extends JPanel
         {
         Point lineStart = new Point(0, 0);
         Point lineEnd = new Point(0, 0);
         Line2D line = new Line2D.Double(lineStart, lineEnd);
         //width of line
         private Stroke stroke = new BasicStroke(2.0f);
         private LineListener lis = null;
         LinePanel()
             {
             super();
             addMouseListener(lis = new LineListener(this, line));
         }
         //draw and delete line
         public void paintComponent(Graphics g)
             {
             super.paintComponent(g);
             Graphics2D g2 = (Graphics2D) g;
             g2.setStroke(stroke);
             if (lis.deleteLine)
                 {
                 g2.setColor(getBackground());
                 lis.deleteLine = false;
             }
             else
             g2.setColor(Color.RED);
             //draw shape of line
             g2.draw(line);
         }
         //define panel's size
       
         public Dimension getPreferredSize()
             {
             return new Dimension(400, 350);
         }
     }
   
     class LineListener extends MouseAdapter
         {
         private Line2D line = null;
         private JComponent parent = null;
         boolean deleteLine = false;
         LineListener(JComponent parent, Line2D line)
             {
             this.parent = parent;
             this.line = line;
         }
         public void mouseClicked(MouseEvent e)
             {
             Point p = e.getPoint();
             //this does it!
             if (line.ptSegDist(p) == 0.0)
                 {
                 System.out.println("Hit!");
                 deleteLine = true;
             }
             else
             System.out.println("Point: " + p + "\nDistance: " + line.ptSegDist(p));
             parent.repaint();
         }
     }
   
     public static void main(String[] args)
         {
         new LineUnder();
     }
}

Monday, September 12, 2011

Compositing Shapes

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

public class Compositing extends Frame {
  public static void main( String[] argv ) {
    Compositing myExample = new Compositing( "Compositing Shapes" );
  }

  public Compositing( String title ) {
    super( title );
    setSize( 300, 180 );
    addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent we ) {
        dispose();
        System.exit( 0 );
      }
    } );
    setVisible( true );
  }

  public void paint( Graphics g ) {
    Graphics2D g2d = (Graphics2D) g;
    Rectangle2D rect1 = new Rectangle2D.Double( 32, 42, 200, 130 );
    Rectangle2D rect2 = new Rectangle2D.Double( 164, 42, 100, 100 );
    g2d.setColor( Color.cyan );
    g2d.fill( rect1 );
    g2d.setPaint( loadTextureResource( "1.gif" ) );
    g2d.setComposite( AlphaComposite.getInstance( AlphaComposite.SRC_OVER, .5f ) );
    g2d.fill( rect2 );

  }

  public TexturePaint loadTextureResource( String absfilename ) {
    MediaTracker tracker = new MediaTracker( this );
    Image imtexture = Toolkit.getDefaultToolkit().getImage( absfilename );
    tracker.addImage( imtexture, 0 );
    try {
      tracker.waitForID( 0 );
      int width = imtexture.getWidth( this );
      int height = imtexture.getHeight( this );
      System.out.println( "width" + width + " height =" + height );
      BufferedImage buffImg = new
          BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
      Graphics g = buffImg.getGraphics();
      g.drawImage( imtexture, 0, 0, this );
      return new TexturePaint( buffImg, new Rectangle2D.Double( 0, 0, width, height ) );
    }
    catch( Exception e ) {
      System.out.println( "Exception on Image-Texture Loading" );
    }
    return null;
  }
}

Sunday, September 11, 2011

Applet that demonstrates a Java2D GeneralPath

package org.best.example;

import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

    public class ShapesApplet extends JApplet {
   
     // initialize the applet
     public void init()
         {
         // obtain color parameters from XHTML file
             try {
             int red = Integer.parseInt( getParameter( "red" ) );
             int green = Integer.parseInt( getParameter( "green" ) );
             int blue = Integer.parseInt( getParameter( "blue" ) );
           
             Color backgroundColor = new Color( red, green, blue );
           
             setBackground( backgroundColor );
         }
       
         // if there is an exception while processing the color
         // parameters, catch it and ignore it
             catch ( Exception exception ) {
             // do nothing
         }
     }
   
     public void paint( Graphics g )
         {
         // create arrays of x and y coordinates
         int xPoints[] =
         { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
         int yPoints[] =
         { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
       
         // obtain reference to a Graphics2D object
         Graphics2D g2d = ( Graphics2D ) g;
       
         // create a star from a series of points
         GeneralPath star = new GeneralPath();
       
         // set the initial coordinate of the GeneralPath
         star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );
       
         // create the star--this does not draw the star
         for ( int k = 1; k < xPoints.length; k++ )
         star.lineTo( xPoints[ k ], yPoints[ k ] );
       
         // close the shape
         star.closePath();
       
         // translate the origin to (200, 200)
         g2d.translate( 200, 200 );
       
         // rotate around origin and draw stars in random colors
             for ( int j = 1; j <= 20; j++ ) {
             g2d.rotate( Math.PI / 10.0 );
           
             g2d.setColor(
             new Color( ( int ) ( Math.random() * 256 ),
             ( int ) ( Math.random() * 256 ),
             ( int ) ( Math.random() * 256 ) ) );
           
             g2d.fill( star ); // draw a filled star
         }
     }
}

Saturday, September 10, 2011

Affine transformations with images

package org.best.example;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;

public class AffineTransformationsWithImages extends Frame {

  Dimension size = new Dimension( 600, 600 );
  Image image;
  Point origin = new Point( size.width / 2, size.height / 2 );
  AffineTransform tx = new AffineTransform();
  float scalingFactor = 1.0f;

  public AffineTransformationsWithImages( String title ) {
    super( title );
    setSize( size );
    addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent we ) {
        dispose();
        System.exit( 0 );
      }
    } );
    setVisible( true );
    image = Toolkit.getDefaultToolkit().getImage( "3.gif" );
    tx.translate( origin.x, origin.y );
    for( int x = 0; x < 100; x++ ) {
      scalingFactor += 0.0003;
      pause( 50 );
      tx.scale( scalingFactor, scalingFactor );
      tx.rotate( scalingFactor );
      repaint();
    }
  }

  public static void main( String[] args ) {
    AffineTransformationsWithImages affineTransformationsWithImages1 =
        new AffineTransformationsWithImages( "Affine Transformations With Images Example" );
  }

  public void update( Graphics g ) {
    paint( g );
  }

  public void paint( Graphics g ) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.drawImage( image, tx, this );
  }

  private void pause( int mil ) {
    try {
      Thread.currentThread().sleep( mil );
    }
    catch( Exception ex ) {
      ex.printStackTrace();
    }
  }

}