RotationExample.java An example of translating and rotating the coordinate system prior to drawing #Programming Code Examples #Java/J2EE/J2ME #Drawing

import java.awt.*;

/** An example of translating and rotating the coordinate
 *  system before each drawing.
 *
 *******************************

public class RotationExample extends StrokeThicknessExample {
  private Color[] colors = { Color.white, Color.black };

  public void paintComponent(Graphics g) {
    clear(g);
    Graphics2D g2d = (Graphics2D)g;
    drawGradientCircle(g2d);
    drawThickCircleOutline(g2d);
    // Move the origin to the center of the circle.
    g2d.translate(185.0, 185.0);
    for (int i=0; i<16; i++) {
      // Rotate the coordinate system around current
      // origin, which is at the center of the circle.
      g2d.rotate(Math.PI/8.0);
      g2d.setPaint(colors[i%2]);
      g2d.drawString("Java", 0, 0);
    }
  }

public static void main(String[] args) {
    WindowUtilities.openInJFrame(new RotationExample(),
                                 380, 400);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10380
Categories:Programming Code Examples, Java/J2EE/J2ME, Drawing
Tags:Java/J2EE/J2MEDrawing
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

LineStyles.java Provides examples of the available styles for joining line segments #Programming Code Examples #Java/J2EE/J2ME #Drawing

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

/** A demonstration of different controls when joining two line
 *  segments. The style of the line end point is controlled
 *  through the capStyle parameter.
 *
 ************************************

public class LineStyles extends JPanel {
  private GeneralPath path;
  private static int x = 30, deltaX = 150, y = 300,
                     deltaY = 250, thickness = 40;
  private Circle p1Large, p1Small, p2Large, p2Small,
                 p3Large, p3Small;
  private int compositeType = AlphaComposite.SRC_OVER;
  private AlphaComposite transparentComposite =
    AlphaComposite.getInstance(compositeType, 0.4F);
  private int[] caps =
    { BasicStroke.CAP_SQUARE, BasicStroke.CAP_BUTT,
      BasicStroke.CAP_ROUND };
  private String[] capNames =
    { "CAP_SQUARE", "CAP_BUTT", "CAP_ROUND" };
  private int[] joins =
    { BasicStroke.JOIN_MITER, BasicStroke.JOIN_BEVEL,
      BasicStroke.JOIN_ROUND };
  private String[] joinNames =
    { "JOIN_MITER", "JOIN_BEVEL", "JOIN_ROUND" };

  public LineStyles() {
    path = new GeneralPath();
    path.moveTo(x, y);
    p1Large = new Circle(x, y, thickness/2);
    p1Small = new Circle(x, y, 2);
    path.lineTo(x + deltaX, y - deltaY);
    p2Large = new Circle(x + deltaX, y - deltaY, thickness/2);
    p2Small = new Circle(x + deltaX, y - deltaY, 2);
    path.lineTo(x + 2*deltaX, y);
    p3Large = new Circle(x + 2*deltaX, y, thickness/2);
    p3Small = new Circle(x + 2*deltaX, y, 2);
    setFont(new Font("SansSerif", Font.BOLD, 20));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.setColor(Color.lightGray);
    for(int i=0; i<caps .length; i++) {
      BasicStroke stroke =
        new BasicStroke(thickness, caps[i], joins[i]);
      g2d.setStroke(stroke);
      g2d.draw(path);
      labelEndPoints(g2d, capNames[i], joinNames[i]);
      g2d.translate(3*x + 2*deltaX, 0);
    }
  }

  // Draw translucent circles to illustrate actual end points.
  // Include text labels for cap/join style.
  private void labelEndPoints(Graphics2D g2d, String capLabel,
                              String joinLabel) {
    Paint origPaint = g2d.getPaint();
    Composite origComposite = g2d.getComposite();
    g2d.setPaint(Color.black);
    g2d.setComposite(transparentComposite);
    g2d.fill(p1Large);
    g2d.fill(p2Large);
    g2d.fill(p3Large);
    g2d.setPaint(Color.yellow);
    g2d.setComposite(origComposite);
    g2d.fill(p1Small);
    g2d.fill(p2Small);
    g2d.fill(p3Small);
    g2d.setPaint(Color.black);
    g2d.drawString(capLabel, x + thickness - 5, y + 5);
    g2d.drawString(joinLabel, x + deltaX + thickness - 5,
                   y - deltaY);
    g2d.setPaint(origPaint);
  }

  public static void main(String[] args) {
    WindowUtilities.openInJFrame(new LineStyles(),
                                 9*x + 6*deltaX, y + 60);
  }
}

class Circle extends Ellipse2D.Double {
  public Circle(double centerX, double centerY, double radius) {
    super(centerX - radius, centerY - radius, 2.0*radius,
          2.0*radius);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10379
Categories:Programming Code Examples, Java/J2EE/J2ME, Drawing
Tags:Java/J2EE/J2MEDrawing
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Demonstrates setting the pen width (in pixels) using a BasicStroke prior to drawing. Inherits from FontExample.java. #Programming Code Examples #Java/J2EE/J2ME #Drawing

StrokeThicknessExample.java 
>>>>>>>>>>>>>>>>>>>>>>>>>>>
import java.awt.*;

/** An example of controlling the Stroke (pen) widths when
 *  drawing.
 *
 ******************
 */

public class StrokeThicknessExample extends FontExample {
  public void paintComponent(Graphics g) {
    clear(g);
    Graphics2D g2d = (Graphics2D)g;
    drawGradientCircle(g2d);
    drawBigString(g2d);
    drawThickCircleOutline(g2d);
  }

  protected void drawThickCircleOutline(Graphics2D g2d) {
    g2d.setPaint(Color.blue);
    g2d.setStroke(new BasicStroke(8)); // 8-pixel wide pen
    g2d.draw(getCircle());
  }

  public static void main(String[] args) {
    WindowUtilities.openInJFrame(new StrokeThicknessExample(),
                                 380, 400);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10377
Categories:Programming Code Examples, Java/J2EE/J2ME, Drawing
Tags:Java/J2EE/J2MEDrawing
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Illustrates using a local font (Goudy Handtooled BT) to perform drawing in Java 2D #Programming Code Examples #Java/J2EE/J2ME #Drawing

import java.awt.*;

/** An example of using local fonts to perform drawing in
 *  Java 2D.
 *
 **********************

public class FontExample extends GradientPaintExample {
  public FontExample() {
    GraphicsEnvironment env =
      GraphicsEnvironment.getLocalGraphicsEnvironment();
    env.getAvailableFontFamilyNames();
    setFont(new Font("Goudy Handtooled BT", Font.PLAIN, 100));
  }

  protected void drawBigString(Graphics2D g2d) {
    g2d.setPaint(Color.black);
    g2d.drawString("Java 2D", 25, 215);
  }

  public void paintComponent(Graphics g) {
    clear(g);
    Graphics2D g2d = (Graphics2D)g;
    drawGradientCircle(g2d);
    drawBigString(g2d);
  }

  public static void main(String[] args) {
    WindowUtilities.openInJFrame(new FontExample(), 380, 400);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10376
Categories:Programming Code Examples, Java/J2EE/J2ME, Drawing
Tags:Java/J2EE/J2MEDrawing
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

ListFonts.java Lists all local fonts available for graphical drawing. #Programming Code Examples #Java/J2EE/J2ME #Drawing

ListFonts.java Lists all local fonts available for graphical drawing. 
***********************
import java.awt.*;

/** Lists the names of all available fonts. 
 *
 ******************

public class ListFonts {
  public static void main(String[] args) {
    GraphicsEnvironment env =
      GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontNames = env.getAvailableFontFamilyNames();
    System.out.println("Available Fonts:");
    for(int i=0; i>>>>>>>>>>>>>>>>>>>>>>>

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10375
Categories:Programming Code Examples, Java/J2EE/J2ME, Drawing
Tags:Java/J2EE/J2MEDrawing
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Illustrates the effect of different transparency #Programming Code Examples #Java/J2EE/J2ME #Drawing

~~~~~~~~~~~~~~~~~~~
TransparencyExample.java Illustrates the effect of different transparency (alpha) values when drawing a shape.
~~~~~~~~~~~~~~~~~~~
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

/** An illustration of the use of AlphaComposite to make
 *  partially transparent drawings.
 *
 **********************************

public class TransparencyExample extends JPanel {
  private static int gap=10, width=60, offset=20,
                     deltaX=gap+width+offset;
  private Rectangle
    blueSquare = new Rectangle(gap+offset, gap+offset, width,
                               width),
    redSquare = new Rectangle(gap, gap, width, width);

  private AlphaComposite makeComposite(float alpha) {
    int type = AlphaComposite.SRC_OVER;
    return(AlphaComposite.getInstance(type, alpha));
  }

  private void drawSquares(Graphics2D g2d, float alpha) {
    Composite originalComposite = g2d.getComposite();
    g2d.setPaint(Color.blue);
    g2d.fill(blueSquare);
    g2d.setComposite(makeComposite(alpha));
    g2d.setPaint(Color.red);
    g2d.fill(redSquare);
    g2d.setComposite(originalComposite);
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    for(int i=0; i<11; i++) {
      drawSquares(g2d, i*0.1F);
      g2d.translate(deltaX, 0);
    }
  }

  public static void main(String[] args) {
    String title = "Transparency example: alpha of the top " +
                   "(red) square ranges from 0.0 at the left " +
                   "to 1.0 at the right. Bottom (blue) square " + 
                   "is opaque.";
    WindowUtilities.openInJFrame(new TransparencyExample(),
                                 11*deltaX + 2*gap,
                                 deltaX + 3*gap,
                                 title, Color.lightGray);
  }
}
>>>>>>>>>>>>>>>>>>

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10374
Categories:Programming Code Examples, Java/J2EE/J2ME, Drawing
Tags:Java/J2EE/J2MEDrawing
Post Data:2017-01-02 16:04:35

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Demonstrates using a TexturePaint to fill an shape with a tiled image #Programming Code Examples #Java/J2EE/J2ME #Drawing

^^^^^^^^^^^^^^^^^
TiledImages.java Demonstrates using a TexturePaint to fill an shape with a tiled image. Uses the following class and images:

    * ImageUtilities.java Simplifies creating a BufferedImage from an image file. 
~~~~~~~~~~~~~~~~~~
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;

/** An example of using TexturePaint to fill objects with tiled
 *  images. Uses the getBufferedImage method of ImageUtilities 
 *  to load an Image from a file and turn that into a 
 *  BufferedImage.
 *
 ****************

public class TiledImages extends JPanel {
  private String dir = System.getProperty("user.dir");
  private String imageFile1 = dir + "/images/marty.jpg";
  private TexturePaint imagePaint1;
  private Rectangle imageRect;
  private String imageFile2 = dir + "/images/bluedrop.gif";
  private TexturePaint imagePaint2;
  private int[] xPoints = { 30, 700, 400 };
  private int[] yPoints = { 30, 30, 600 };
  private Polygon imageTriangle =
                    new Polygon(xPoints, yPoints, 3);
  public TiledImages() {
    BufferedImage image =
      ImageUtilities.getBufferedImage(imageFile1, this);
    imageRect = new Rectangle(235, 70, image.getWidth(),
                              image.getHeight());
    imagePaint1 = new TexturePaint(image, imageRect);
    image = ImageUtilities.getBufferedImage(imageFile2, this);
    imagePaint2 =
      new TexturePaint(image, new Rectangle(0, 0, 32, 32));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.setPaint(imagePaint2);
    g2d.fill(imageTriangle);
    g2d.setPaint(Color.blue);
    g2d.setStroke(new BasicStroke(5));
    g2d.draw(imageTriangle);
    g2d.setPaint(imagePaint1);
    g2d.fill(imageRect);
    g2d.setPaint(Color.black);
    g2d.draw(imageRect);
  }

  public static void main(String[] args) {
    WindowUtilities.openInJFrame(new TiledImages(), 750, 650);
  }
}
>>>>>>>>>>>>>>
ImageUtilities.java Simplifies creating a BufferedImage from an image file.
>>>>>>>>>>>>>>>
import java.awt.*;
import java.awt.image.*;

/** A class that simplifies a few common image operations, in
 *  particular, creating a BufferedImage from an image file and
 *  using MediaTracker to wait until an image or several images
 *  are done loading.
 *
 ********************

public class ImageUtilities {
  
  /** Create Image from a file, then turn that into a
   *  BufferedImage.
   */

  public static BufferedImage getBufferedImage(String imageFile,
                                               Component c) {
    Image image = c.getToolkit().getImage(imageFile);
    waitForImage(image, c);

    BufferedImage bufferedImage =
      new BufferedImage(image.getWidth(c), image.getHeight(c),
                        BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bufferedImage.createGraphics();
    g2d.drawImage(image, 0, 0, c);
    return(bufferedImage);
  }

  /** Take an Image associated with a file, and wait until it is
   *  done loading (just a simple application of MediaTracker).
   *  If you are loading multiple images, don't use this
   *  consecutive times; instead, use the version that takes
   *  an array of images.
   */

  public static boolean waitForImage(Image image, Component c) {
    MediaTracker tracker = new MediaTracker(c);
    tracker.addImage(image, 0);
    try {
      tracker.waitForAll();
    } catch(InterruptedException ie) {}
    return(!tracker.isErrorAny());
  }

  /** Take some Images associated with files, and wait until they
   *  are done loading (just a simple application of
   *  MediaTracker).
   */

  public static boolean waitForImages(Image[] images, Component c)   {
    MediaTracker tracker = new MediaTracker(c);
    for(int i=0; i<images .length; i++)
      tracker.addImage(images[i], 0);
    try {
      tracker.waitForAll();
    } catch(InterruptedException ie) {}
    return(!tracker.isErrorAny());
  }
}
<<<<<<<<<<<<<<<

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10373
Categories:Programming Code Examples, Java/J2EE/J2ME, Drawing
Tags:Java/J2EE/J2MEDrawing
Post Data:2017-01-02 16:04:35

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Draws a circle with a gradient fill #Programming Code Examples #Java/J2EE/J2ME #Drawing

GradientPaintExample.java Draws a circle with a gradient fill. Inherits from ShapeExample.java. 
**************************************
import java.awt.*;

/** An example of applying a gradient fill to a circle. The
 *  color definition starts with red at (0,0), gradually
 *  changing to yellow at (175,175).
 *
 **********************************

public class GradientPaintExample extends ShapeExample {
  private GradientPaint gradient =
    new GradientPaint(0, 0, Color.red, 175, 175, Color.yellow,
                      true); // true means to repeat pattern

  public void paintComponent(Graphics g) {
    clear(g);
    Graphics2D g2d = (Graphics2D)g;
    drawGradientCircle(g2d);
  }

  protected void drawGradientCircle(Graphics2D g2d) {
    g2d.setPaint(gradient);
    g2d.fill(getCircle());
    g2d.setPaint(Color.black);
    g2d.draw(getCircle());
  }

  public static void main(String[] args) {
    WindowUtilities.openInJFrame(new GradientPaintExample(),
                                 380, 400);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10372
Categories:Programming Code Examples, Java/J2EE/J2ME, Drawing
Tags:Java/J2EE/J2MEDrawing
Post Data:2017-01-02 16:04:35

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Draws a filled ellipse #Programming Code Examples #Java/J2EE/J2ME #Drawing

import javax.swing.*;   // For JPanel, etc.
import java.awt.*;      // For Graphics, etc.
import java.awt.geom.*; // For Ellipse2D, etc.

/** An example of drawing/filling shapes with Java 2D in
 *  Java 1.2 and later.
 *
**************************
public class ShapeExample extends JPanel {
  private Ellipse2D.Double circle =
    new Ellipse2D.Double(10, 10, 350, 350);
  private Rectangle2D.Double square =
    new Rectangle2D.Double(10, 10, 350, 350);

  public void paintComponent(Graphics g) {
    clear(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.fill(circle);
    g2d.draw(square);
  }

  // super.paintComponent clears off screen pixmap,
  // since we're using double buffering by default.
  protected void clear(Graphics g) {
    super.paintComponent(g);
  }

  protected Ellipse2D.Double getCircle() {
    return(circle);
  }

public static void main(String[] args) {
    WindowUtilities.openInJFrame(new ShapeExample(), 380, 400);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10371
Categories:Programming Code Examples, Java/J2EE/J2ME, Drawing
Tags:Java/J2EE/J2MEDrawing
Post Data:2017-01-02 16:04:35

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Example Java Programs #Programming Code Examples #Java/J2EE/J2ME #J2SE

Very Simple Java Example Programs
HelloWorld.java

public class HelloWorld {

    // method main(): ALWAYS the APPLICATION entry point
    public static void main (String[] args) {
	System.out.println ("Hello World!");
    }
}

// Print Today's Date
import java.util.*;

public class HelloDate {
    public static void main (String[] args) {
	System.out.println ("Hello, it's: ");
	System.out.println(new Date());
    }
}


//example: function call in Java
public class FunctionCall {

    public static void funct1 () {
	System.out.println ("Inside funct1");
    }

    public static void main (String[] args) {
	int val;

	System.out.println ("Inside main");

	funct1();

	System.out.println ("About to call funct2");

	val = funct2(8);

	System.out.println ("funct2 returned a value of " + val);

	System.out.println ("About to call funct2 again");

	val = funct2(-3);

	System.out.println ("funct2 returned a value of " + val);
    }

    public static int funct2 (int param) {
	System.out.println ("Inside funct2 with param " + param);
	return param * 2;
    }
}


//Array in Java
public class ArrayDemo {
    public static void main(String[] args) {
	int[] anArray;	        // DECLARE an array of integers

	anArray = new int[10];	// CREATE an array of integers

	// assign a value to each array element 
	for (int i = 0; i < anArray.length; i++) {
		anArray[i] = i;
	    }

	// print a value from each array element
	for (int i = 0; i < anArray.length; i++) {
	    System.out.print(anArray[i] + " ");
	}
	System.out.println();
    }
}


//class usage in Java
class Point2d {
    /* The X and Y coordinates of the point--instance variables */
    private double x;
    private double y;
    private boolean debug;	// A trick to help with debugging

    public Point2d (double px, double py) { // Constructor
	x = px;
	y = py;

	debug = false;		// turn off debugging
    }

    public Point2d () {		// Default constructor
	this (0.0, 0.0);        // Invokes 2 parameter Point2D constructor
    }
    // Note that a this() invocation must be the BEGINNING of
    // statement body of constructor

    public Point2d (Point2d pt) {	// Another consructor
	x = pt.getX();
	y = pt.getY();

	// a better method would be to replace the above code with
	//    this (pt.getX(), pt.getY());
	// especially since the above code does not initialize the
	// variable debug.  This way we are reusing code that is already
	// working.
    }

    public void dprint (String s) {
	// print the debugging string only if the "debug"
	// data member is true
	if (debug)
	    System.out.println("Debug: " + s);
    }

    public void setDebug (boolean b) {
	debug = b;
    }

    public void setX(double px) {
	dprint ("setX(): Changing value of X from " + x + " to " + px );
	x = px;
    }

    public double getX() {
	return x;
    }

    public void setY(double py)  {
	dprint ("setY(): Changing value of Y from " + y + " to " + py );
	y = py;
    }

    public double getY() {
	return y;
    }

    public void setXY(double px, double py) {
	setX(px);
	setY(py);
    }

    public double distanceFrom (Point2d pt) {
	double dx = Math.abs(x - pt.getX());
	double dy = Math.abs(y - pt.getY());

	// check out the use of dprint()
	dprint ("distanceFrom(): deltaX = " + dx);
	dprint ("distanceFrom(): deltaY = " + dy);

	return Math.sqrt((dx * dx) + (dy * dy));
    }

    public double distanceFromOrigin () {
	return distanceFrom (new Point2d ( ));
    }

    public String toStringForXY() {
	String str = "(" + x + ", " + y;
	return str;
    }

    public String toString() {
	String str = toStringForXY() + ")";
	return str;
    }
}



//read integer from Keyboard
import java.io.*;
import java.util.*;

public class KeyboardIntegerReader {

 public static void main (String[] args) throws java.io.IOException {
  String s1;
  String s2;
  int num = 0;

  // set up the buffered reader to read from the keyboard
  BufferedReader br = new BufferedReader (new InputStreamReader (
			System.in));

  boolean cont = true;

  while (cont)
     {
      System.out.print ("Enter an integer:");
      s1 = br.readLine();
      StringTokenizer st = new StringTokenizer (s1);
      s2 = "";

      while (cont && st.hasMoreTokens())
	 {
          try 
          {
           s2 = st.nextToken();
           num = Integer.parseInt(s2);
           cont = false;
          }
          catch (NumberFormatException n)
          {
           System.out.println("The value in "" + s2 + "" is not an 

integer");
          }
	}
     }

  System.out.println ("You entered the integer: " + num);
 }
}


//read data from keyboard
import java.io.*;
import java.util.*;

public class KeyboardReader
{

 public static void main (String[] args) throws java.io.IOException
 {

  String s1;
  String s2;

  double num1, num2, product;

  // set up the buffered reader to read from the keyboard
  BufferedReader br = new BufferedReader (new InputStreamReader (
			System.in));

  System.out.println ("Enter a line of input");

  s1 = br.readLine();

  System.out.println ("The line has " + s1.length() + " characters");

  System.out.println ();
  System.out.println ("Breaking the line into tokens we get:");

  int numTokens = 0;
  StringTokenizer st = new StringTokenizer (s1);

  while (st.hasMoreTokens())
     {
      s2 = st.nextToken();
      numTokens++;
      System.out.println ("    Token " + numTokens + " is: " + s2);
     }
 }
}


//read from file
import java.io.*;
import java.util.*;

public class MyFileReader
{

 public static void main (String[] args) throws java.io.IOException
 {

  String s1;
  String s2;

  // set up the buffered reader to read from the keyboard
  BufferedReader br = new BufferedReader (new FileReader 

("MyFileReader.txt"));

  s1 = br.readLine();

  System.out.println ("The line is " + s1);
  System.out.println ("The line has " + s1.length() + " characters");

  System.out.println ();
  System.out.println ("Breaking the line into tokens we get:");

  int numTokens = 0;
  StringTokenizer st = new StringTokenizer (s1);

  while (st.hasMoreTokens())
     {
      s2 = st.nextToken();
      numTokens++;
      System.out.println ("    Token " + numTokens + " is: " + s2);
     }
 }
}


//exception handling in Java

public class HelloWorldException {
    public static void main (String[] args) throws Exception {
        System.out.println("Bienvenitos!");
        throw new Exception("Generic Exception");
    }
}



//exception handling


import java.io.*;
import java.util.*;

/** Causes a compilation error due to an unhandled Exception
 */
public class KeyboardReaderError {

  public static void main (String[] args) { // throws java.io.IOException

    String s1;
    String s2;

    double num1, num2, product;

    // set up the buffered reader to read from the keyboard
    BufferedReader br = new BufferedReader (new InputStreamReader 

(System.in));

    System.out.println ("Enter a line of input");
    
    /* Following line triggers the error.  Error will show the type of
       unhandled exception and where the call occurs */
    s1 = br.readLine();

    System.out.println ("The line has " + s1.length() + " characters");

    System.out.println ();
    System.out.println ("Breaking the line into tokens we get:");

    int numTokens = 0;
    StringTokenizer st = new StringTokenizer (s1);

    while (st.hasMoreTokens()) {
	s2 = st.nextToken();
	numTokens++;
	System.out.println ("    Token " + numTokens + " is: " + s2);
    }
  }
}

//encounters an error

import java.io.*;

// This program shows a stack track that occurs when java
// encounters a terminal error when running a program.

public class DivBy0
{

 public static void funct1 ()
 {
  System.out.println ("Inside funct1()");

  funct2();
 }

 public static void main (String[] args)
 {
  int val;

  System.out.println ("Inside main()");

  funct1();

 }

 public static void funct2 ()
 {
  System.out.println ("Inside funct2()");
  int i, j, k;

  i = 10;
  j = 0;

  k = i/j;
 }

}



Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10198
Categories:Programming Code Examples, Java/J2EE/J2ME, J2SE
Tags:Java/J2EE/J2MEJ2SE
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada