LinkedList and Iterators in Java #Programming Code Examples #Java/J2EE/J2ME #J2SE

/*
 * LinkedList.java
 *
 * Created on January 10, 2008, 8:51 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package linkedlist;

import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collections;
import java.util.Random;

/**
 *
 * @author Sayed
 */
public class LinkedListTest {
    
    /** Creates a new instance of LinkedList */
    public LinkedListTest() {
    }
    
    /**
     *Example operations using linked lists
     */
    
    public void linkedListOperation(){
        
        final int MAX = 10;
        int counter = 0;

        //create two linked lists
        List listA = new LinkedList();
        List listB = new LinkedList();

        //store data in the linked list A
        for (int i = 0; i < MAX; i++) {
            System.out.println("  - Storing Integer(" + i + ")");
            listA.add(new Integer(i));
        }
       
        //print data from the linked list using iterator 
        Iterator it = listA.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }

        //print data from the linked list using listIterator. 
        counter = 0;
        ListIterator liIt = listA.listIterator();
        while (liIt.hasNext()) {
            System.out.println("Element [" + counter + "] = " + liIt.next());
            System.out.println("  - hasPrevious    = " + liIt.hasPrevious());
            System.out.println("  - hasNext        = " + liIt.hasNext());
            System.out.println("  - previousIndex  = " + liIt.previousIndex());
            System.out.println("  - nextIndex      = " + liIt.nextIndex());
            System.out.println();
            counter++;
        }


        //retrieve data from the linked list using index
        for (int j=0; j < listA.size(); j++) {
            System.out.println("[" + j + "] - " + listA.get(j));
        }

        //find the location of an element
        int locationIndex = listA.indexOf("5");
        System.out.println("Index location of the String "5" is: " + locationIndex);  

        //find the first and the last location of an element
        System.out.println("First occurance search for String "5".  Index =  " + 
		listA.indexOf("5"));
        System.out.println("Last Index search for String "5".       Index =  " + 
		listA.lastIndexOf("5"));

        //create a sublist from the list 
        List listSub = listA.subList(10, listA.size());
        System.out.println("New Sub-List from index 10 to " + listA.size() + ": " + 
		listSub);

        //sort the sub-list
        System.out.println("Original List   : " + listSub);
        Collections.sort(listSub);
        System.out.println("New Sorted List : " + listSub);
        System.out.println();

        //reverse the new sub-list
        System.out.println("Original List     : " + listSub);
        Collections.reverse(listSub);
        System.out.println("New Reversed List : " + listSub);
        System.out.println();

        //check to see if the lists are empty
        System.out.println("Is List A empty?   " + listA.isEmpty());
        System.out.println("Is List B empty?   " + listB.isEmpty());
        System.out.println("Is Sub-List empty? " + listSub.isEmpty());
        
        //compare two lists
        System.out.println("A=B? " + listA.equals(listB));        
        System.out.println();

        //Shuffle the elements around in some Random order for List A
        Collections.shuffle(listA, new Random());

        //convert a list into an array
        Object[] objArray = listA.toArray();
        for (int j=0; j < objArray.length; j++) {
            System.out.println("Array Element [" + j + "] = " + objArray[j]);
        }

        //clear listA
        System.out.println("List A   (before) : " + listA);        
        System.out.println();
        listA.clear();
        System.out.println("List A   (after)  : " + listA);        
        System.out.println();
        
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        LinkedListTest listExample = new LinkedListTest();
        listExample.linkedListOperation();
    }
    
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10175
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

Multithreaded Graphics and Double Buffering #Programming Code Examples #Java/J2EE/J2ME #Java Threads

ShipSimulation.java  Illustrates the basic approach of multithreaded graphics whereas a thread adjusts parameters affecting the appearance of the graphics and then calls repaint to schedule an update of the display. 

import java.applet.Applet;
import java.awt.*;

public class ShipSimulation extends Applet implements Runnable {
  ...
  
  public void run() {
    Ship s;
    for(int i=0; i<ships .length; i++) {
      s = ships[i];
      s.move(); // Update location.
    }
    repaint();
  }

  ...
  
  public void paint(Graphics g) {
    Ship s;
    for(int i=0; i<ships.length; i++) {
      s = ships[i];
      g.draw(s); // Draw at current location.
    }
  }
}
*************************
DrawCircles.java An applet that draws a circle where the user clicks the mouse.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;

/** An applet that draws a small circle where you click.
 
public class DrawCircles extends Applet {

  private Vector circles;

  /** When you click the mouse, create a SimpleCircle,
   *  put it in the Vector, and tell the system
   *  to repaint (which calls update, which clears
   *  the screen and calls paint).
   */

  private class CircleDrawer extends MouseAdapter {
    public void mousePressed(MouseEvent event) {
      circles.addElement(
         new SimpleCircle(event.getX(),event.getY(),25));
      repaint();
    }
  }

  public void init() {
    circles = new Vector();
    addMouseListener(new CircleDrawer());
    setBackground(Color.white);
  }

  /** This loops down the available SimpleCircle objects,
   *  drawing each one.
   */

  public void paint(Graphics g) {
    SimpleCircle circle;
    for(int i=0; i<circles.size(); i++) {
      circle = (SimpleCircle)circles.elementAt(i);
      circle.draw(g);
    }
  }
}
******************************
SimpleCircle.java A class to store the x, y, and radius of a circle. Also, provides a draw method to paint the circle on the graphics object.
import java.awt.*;

/** A class to store an x, y, and radius, plus a draw method.
 //
public class SimpleCircle {
  private int x, y, radius;

  public SimpleCircle(int x, int y, int radius) {
    setX(x);
    setY(y);
    setRadius(radius);
  }

  /** Given a Graphics, draw the SimpleCircle
   *  centered around its current position.
   */

  public void draw(Graphics g) {
    g.fillOval(x - radius, y - radius,
               radius * 2, radius * 2);
  }

  public int getX() { return(x); }

  public void setX(int x) { this.x = x; }

  public int getY() { return(y); }

  public void setY(int y) { this.y = y; }

  public int getRadius() { return(radius); }

  public void setRadius(int radius) {
    this.radius = radius;
  }
}
//
Rubberband.java  Draws a rectangle where one corner is fixed (initial selection of the mouse) and the opposite corner is determined by the location of the dragged mouse. Illustrates drawing directly into the graphics object instead of performing the drawing in the paint method. The graphics object is obtained by calling getGraphics.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/** Draw "rubberband" rectangles when the user drags
 *  the mouse.
 *
  */

public class Rubberband extends Applet {
  private int startX, startY, lastX, lastY;

  public void init() {
    addMouseListener(new RectRecorder());
    addMouseMotionListener(new RectDrawer());
    setBackground(Color.white);
  }

  /** Draw the rectangle, adjusting the x, y, w, h
   *  to correctly accommodate for the opposite corner of the
   *  rubberband box relative to the start position.
   */

  private void drawRectangle(Graphics g, int startX, int startY,
                             int stopX, int stopY ) {
    int x, y, w, h;
    x = Math.min(startX, stopX);
    y = Math.min(startY, stopY);
    w = Math.abs(startX - stopX);
    h = Math.abs(startY - stopY);
    g.drawRect(x, y, w, h);
  }

  private class RectRecorder extends MouseAdapter {

    /** When the user presses the mouse, record the
     *  location of the top-left corner of rectangle.
     */

    public void mousePressed(MouseEvent event) {
      startX = event.getX();
      startY = event.getY();
      lastX = startX;
      lastY = startY;
    }

    /** Erase the last rectangle when the user releases
     *  the mouse.
     */

    public void mouseReleased(MouseEvent event) {
      Graphics g = getGraphics();
      g.setXORMode(Color.lightGray);
      drawRectangle(g, startX, startY, lastX, lastY);
    }
  } 

  private class RectDrawer extends MouseMotionAdapter {

    /** This draws a rubberband rectangle, from the location
     *  where the mouse was first clicked to the location
     *  where the mouse is dragged.
     */

    public void mouseDragged(MouseEvent event) {
      int x = event.getX();
      int y = event.getY();

      Graphics g = getGraphics();
      g.setXORMode(Color.lightGray);
      drawRectangle(g, startX, startY, lastX, lastY);
      drawRectangle(g, startX, startY, x, y);

      lastX = x;
      lastY = y;
    }
  } 
}
*//
Bounce.java An applet that contains moving circles that bounce off the walls. Illustrates overriding update to reduce animation flickering and performing incremental updating in the paint method. Here, to achieve animation, a single thread continuously calls repaint while subsequently sleeping for a 100 milliseconds
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;

/** Bounce circles around on the screen. Doesn't use double
 *  buffering, so has problems with overlapping circles.
 *  Overrides update to avoid flicker problems.
 *
 */

public class Bounce extends Applet implements Runnable,
                                              ActionListener {
  private Vector circles;
  private int width, height;
  private Button startButton, stopButton;
  private Thread animationThread = null;

  public void init() {
    setBackground(Color.white);
    width = getSize().width;
    height = getSize().height;
    circles = new Vector();
    startButton = new Button("Start a circle");
    startButton.addActionListener(this);
    add(startButton);
    stopButton = new Button("Stop all circles");
    stopButton.addActionListener(this);
    add(stopButton);
  }

  /** When the "start" button is pressed, start the animation
   *  thread if it is not already started. Either way, add a
   *  circle to the Vector of circles that are being bounced.
   *  

* When the "stop" button is pressed, stop the thread and * clear the Vector of circles. */ public void actionPerformed(ActionEvent event) { if (event.getSource() == startButton) { if (circles.size() == 0) { // Erase any circles from previous run. getGraphics().clearRect(0, 0, getSize().width, getSize().height); animationThread = new Thread(this); animationThread.start(); } int radius = 25; int x = radius + randomInt(width - 2 * radius); int y = radius + randomInt(height - 2 * radius); int deltaX = 1 + randomInt(10); int deltaY = 1 + randomInt(10); circles.addElement(new MovingCircle(x, y, radius, deltaX, deltaY)); } else if (event.getSource() == stopButton) { if (animationThread != null) { animationThread = null; circles.removeAllElements(); } } repaint(); } /** Each time around the loop, call paint and then take a * short pause. The paint method will move the circles and * draw them. */ public void run() { Thread myThread = Thread.currentThread(); // Really while animationThread not null while(animationThread==myThread) { repaint(); pause(100); } } /** Skip the usual screen-clearing step of update so that * there is no flicker between each drawing step. */ public void update(Graphics g) { paint(g); } /** Erase each circle's old position, move it, then draw it * in new location. */ public void paint(Graphics g) { MovingCircle circle; for(int i=0; i<circles .size(); i++) { circle = (MovingCircle)circles.elementAt(i); g.setColor(getBackground()); circle.draw(g); // Old position. circle.move(width, height); g.setColor(getForeground()); circle.draw(g); // New position. } } // Returns an int from 0 to max (inclusive), // yielding max + 1 possible values. private int randomInt(int max) { double x = Math.floor((double)(max + 1) * Math.random()); return((int)(Math.round(x))); } // Sleep for the specified amount of time. private void pause(int milliseconds) { try { Thread.sleep((long)milliseconds); } catch(InterruptedException ie) {} } } *// MovingCircle.java An extension of SimpleCircle that can be moved about and bounces off walls. /** An extension of SimpleCircle that can be moved around * according to deltaX and deltaY values. Movement will * continue in a given direction until the edge of the circle * reaches a wall, when it will "bounce" and move in the other * direction. * */ public class MovingCircle extends SimpleCircle { private int deltaX, deltaY; public MovingCircle(int x, int y, int radius, int deltaX, int deltaY) { super(x, y, radius); this.deltaX = deltaX; this.deltaY = deltaY; } public void move(int windowWidth, int windowHeight) { setX(getX() + getDeltaX()); setY(getY() + getDeltaY()); bounce(windowWidth, windowHeight); } private void bounce(int windowWidth, int windowHeight) { int x = getX(), y = getY(), radius = getRadius(), deltaX = getDeltaX(), deltaY = getDeltaY(); if ((x - radius < 0) && (deltaX windowWidth) && (deltaX > 0)) { setDeltaX(-deltaX); } if ((y -radius < 0) && (deltaY windowHeight) && (deltaY > 0)) { setDeltaY(-deltaY); } } public int getDeltaX() { return(deltaX); } public void setDeltaX(int deltaX) { this.deltaX = deltaX; } public int getDeltaY() { return(deltaY); } public void setDeltaY(int deltaY) { this.deltaY = deltaY; } } *// SimpleCircle.java A class to store the x, y, and radius of a circle. Also, provides a draw method to paint the circle on the graphics object. import java.awt.*; /** A class to store an x, y, and radius, plus a draw method. * */ public class SimpleCircle { private int x, y, radius; public SimpleCircle(int x, int y, int radius) { setX(x); setY(y); setRadius(radius); } /** Given a Graphics, draw the SimpleCircle * centered around its current position. */ public void draw(Graphics g) { g.fillOval(x - radius, y - radius, radius * 2, radius * 2); } public int getX() { return(x); } public void setX(int x) { this.x = x; } public int getY() { return(y); } public void setY(int y) { this.y = y; } public int getRadius() { return(radius); } public void setRadius(int radius) { this.radius = radius; } } *// DoubleBufferBounce.java An enhancement to the previous applet containing bouncing circles. In this case, double buffering is used to improve the animation; all incremental updating is done in an off-screen image and then the image is drawn to the screen. import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.util.Vector; /** Bounce circles around on the screen, using double buffering * for speed and to avoid problems with overlapping circles. * Overrides update to avoid flicker problems. * */ public class DoubleBufferBounce extends Applet implements Runnable, ActionListener { private Vector circles; private int width, height; private Image offScreenImage; private Graphics offScreenGraphics; private Button startButton, stopButton; private Thread animationThread = null; public void init() { setBackground(Color.white); width = getSize().width; height = getSize().height; offScreenImage = createImage(width, height); offScreenGraphics = offScreenImage.getGraphics(); // Automatic in some systems, not in others. offScreenGraphics.setColor(Color.black); circles = new Vector(); startButton = new Button("Start a circle"); startButton.addActionListener(this); add(startButton); stopButton = new Button("Stop all circles"); stopButton.addActionListener(this); add(stopButton); } /** When the "start" button is pressed, start the animation * thread if it is not already started. Either way, add a * circle to the Vector of circles that are being bounced. *

* When the "stop" button is pressed, stop the thread and * clear the Vector of circles. */ public void actionPerformed(ActionEvent event) { if (event.getSource() == startButton) { if (circles.size() == 0) { animationThread = new Thread(this); animationThread.start(); } int radius = 25; int x = radius + randomInt(width - 2 * radius); int y = radius + randomInt(height - 2 * radius); int deltaX = 1 + randomInt(10); int deltaY = 1 + randomInt(10); circles.addElement(new MovingCircle(x, y, radius, deltaX, deltaY)); repaint(); } else if (event.getSource() == stopButton) { if (animationThread != null) { animationThread = null; circles.removeAllElements(); } } } /** Each time around the loop, move each circle based on its * current position and deltaX/deltaY values. These values * reverse when the circles reach the edge of the window. */ public void run() { MovingCircle circle; Thread myThread = Thread.currentThread(); // Really while animationThread not null. while(animationThread==myThread) { for(int j=0; j<circles .size(); j++) { circle = (MovingCircle)circles.elementAt(j); circle.move(width, height); } repaint(); pause(100); } } /** Skip the usual screen-clearing step of update so that * there is no flicker between each drawing step. */ public void update(Graphics g) { paint(g); } /** Clear the off-screen pixmap, draw each circle onto it, then * draw that pixmap onto the applet window. */ public void paint(Graphics g) { offScreenGraphics.clearRect(0, 0, width, height); MovingCircle circle; for(int i=0; i<circles.size(); i++) { circle = (MovingCircle)circles.elementAt(i); circle.draw(offScreenGraphics); } g.drawImage(offScreenImage, 0, 0, this); } // Returns an int from 0 to max (inclusive), yielding max + 1 // possible values. private int randomInt(int max) { double x = Math.floor((double)(max + 1) * Math.random()); return((int)(Math.round(x))); } // Sleep for the specified amount of time. private void pause(int milliseconds) { try { Thread.sleep((long)milliseconds); } catch(InterruptedException ie) {} } } **// ImageAnimation.java Illustrates animation of images by using a thread to cycle through an array of images. See ImageAnimation.html. Uses the following class and images: import java.applet.Applet; import java.awt.*; public class ImageAnimation extends Applet { /** Sequence through an array of 15 images to perform the * animation. A separate Thread controls each tumbling Duke. * The Applet's stop method calls a public service of the * Duke class to terminate the thread. Override update to * avoid flicker problems. * */ private static final int NUMDUKES = 2; private Duke[] dukes; private int i; public void init() { dukes = new Duke[NUMDUKES]; setBackground(Color.white); } /** Start each thread, specifing a direction to sequence * through the array of images. */ public void start() { int tumbleDirection; for (int i=0; i<NUMDUKES ; i++) { tumbleDirection = (i%2==0) ? 1 :-1; dukes[i] = new Duke(tumbleDirection, this); dukes[i].start(); } } /** Skip the usual screen-clearing step of update so that * there is no flicker between each drawing step. */ public void update(Graphics g) { paint(g); } public void paint(Graphics g) { for (i=0 ; i<NUMDUKES ; i++) { if (dukes[i] != null) { g.drawImage(Duke.images[dukes[i].getIndex()], 200*i, 0, this); } } } /** When the Applet's stop method is called, use the public * service, setState, of the Duke class to set a flag and * terminate the run method of the thread. */ public void stop() { for (int i=0; i<NUMDUKES ; i++) { if (dukes[i] != null) { dukes[i].setState(Duke.STOP); } } } } *// Duke.java A subclass of Thread holding the images for the animation. import java.applet.Applet; import java.awt.*; /** Duke is a Thread that has knowledge of the parent applet * (highly coupled) and thus can call the parent's repaint * method. Duke is mainly responsible for changing an index * value into an image array. * */ public class Duke extends Thread { public static final int STOP = 0; public static final int RUN = 1; public static final int WAIT = 2; public static Image[] images; private static final int NUMIMAGES = 15; private static Object lock = new Object(); private int state = RUN; private int tumbleDirection; private int index = 0; private Applet parent; public Duke(int tumbleDirection, Applet parent) { this.tumbleDirection = tumbleDirection; this.parent = parent; synchronized(lock) { if (images==null) { // If not previously loaded. images = new Image[ NUMIMAGES ]; for (int i=0; i<NUMIMAGES; i++) { images[i] = parent.getImage( parent.getCodeBase(), "images/T" + i + ".gif"); } } } } /** Return current index into image array. */ public int getIndex() { return index; } /** Public method to permit setting a flag to stop or * suspend the thread. State is monitored through * corresponding checkState method. */ public synchronized void setState(int state) { this.state = state; if (state==RUN) { notify(); } } /** Returns the desired state (RUN, STOP, WAIT) of the * thread. If the thread is to be suspended, then the * thread method wait is continuously called until the * state is changed through the public method setState. */ private synchronized int checkState() { while (state==WAIT) { try { wait(); } catch (InterruptedException e) {} } return state; } /** The variable index (into image array) is incremented * once each time through the while loop, calls repaint, * and pauses for a moment. Each time through the loop the * state (flag) of the thread is checked. */ public void run() { while (checkState()!=STOP) { index += tumbleDirection; if (index = NUMIMAGES) { index = 0; } parent.repaint(); try { Thread.sleep(100); } catch (InterruptedException e) { break; // Break while loop. } } } } *// TimedAnimation.java An applet that demonstrates animation of an image by using a Timer. Note that Timer is located in the javax.swing package. import java.awt.*; import javax.swing.*; /** An example of performing animation through Swing timers. * Two timed Dukes are created with different timer periods. * */ public class TimedAnimation extends JApplet { private static final int NUMDUKES = 2; private TimedDuke[] dukes; private int i, index; public void init() { dukes = new TimedDuke[NUMDUKES]; setBackground(Color.white); dukes[0] = new TimedDuke( 1, 100, this); dukes[1] = new TimedDuke(-1, 500, this); } // Start each Duke timer. public void start() { for (int i=0; i<numdukes ; i++) { dukes[i].startTimer(); } } public void paint(Graphics g) { for (i=0 ; i<NUMDUKES ; i++) { if (dukes[i] != null) { index = dukes[i].getIndex(); g.drawImage(TimedDuke.images[index], 200*i, 0, this); } } } // Stop each Duke timer. public void stop() { for (int i=0; i<NUMDUKES ; i++) { dukes[i].stopTimer(); } } } **// TimedDuke.java Facilitates animation of Duke images by creating an internal timer. import java.applet.Applet; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** Duke facilitates animation by creating an internal timer. * When the timer fires, an actionPerformed event is * triggered, which in turn calls repaint on the parent * Applet. * */ public class TimedDuke implements ActionListener { private static final int NUMIMAGES = 15; private static boolean loaded = false; private static Object lock = new Object(); private int tumbleDirection; private int msec; private int index = 0; private Applet parent; private Timer timer; public static Image[] images = new Image[NUMIMAGES]; public TimedDuke(int tumbleDirection, int msec, Applet parent) { this.tumbleDirection = tumbleDirection; this.msec = msec; this.parent = parent; synchronized (lock) { if (!loaded) { MediaTracker tracker = new MediaTracker(parent); for (int i=0; i<NUMIMAGES; i++) { images[i] = parent.getImage(parent.getCodeBase(), "images/T" + i + ".gif"); tracker.addImage(images[i],0); } try { tracker.waitForAll(); } catch (InterruptedException ie) {} if (!tracker.isErrorAny()) { loaded = true; } } } timer = new Timer(msec, this); } // Return current index into image array. public int getIndex() { return index; } // Receives timer firing event. Increments the index into // image array and forces repainting of the new image. public void actionPerformed(ActionEvent event) { index += tumbleDirection; if (index = NUMIMAGES) { index = 0; } parent.repaint(); } // Public service to start the timer. public void startTimer() { timer.start(); } // Public service to stop the timer. public void stopTimer() { timer.stop(); } } **//

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

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

# StoppableThread.java A template to place a thread in a RUN, WAIT, or STOP state. #Programming Code Examples #Java/J2EE/J2ME #Java Threads


/** A template to control the state of a thread through setting
 *  an internal flag.

public class StoppableThread extends Thread {

   public static final int STOP    = 0;
   public static final int RUN     = 1;
   public static final int WAIT    = 2;
   private int state = RUN;

  /** Public method to permit setting a flag to stop or
   *  suspend the thread.  The state is monitored through the
   *  corresponding checkState method.
   */

   public synchronized void setState(int state) {
      this.state = state;
      if (state==RUN) {
         notify();
      }
   }

  /** Returns the desired state of the thread (RUN, STOP, WAIT).
   *  Normally, you may want to change the state or perform some
   *  other task if an InterruptedException occurs.
   */

   private synchronized int checkState() {
      while (state==WAIT) {
        try {
          wait();
        } catch (InterruptedException e) { }
      }
      return state;
   }

  /** An example of thread that will continue to run until
   *  the creating object tells the thread to STOP.
   */

   public void run() {
      while (checkState()!=STOP) {
         ...
      }
   }
}

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

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

DOM example that represents the basic structure of an XML document as a JTree #Programming Code Examples #Java/J2EE/J2ME #JavaScript

//XMLTree.java
//Uses the following files

Uses the following files:

    * XMLFrame.java:Swing application to select an XML document and display in a JTree.

ExtensionFileFilter.java Allows you to specify which file extensions will be displayed in a JFileChooser.

test.xml Default file loaded if none selected by user. 

perennials.xml and perennials.dtd Data on daylilies and corresponding DTD.

WindowUtilities.java  

ExitListener.java. 

//XMLTree.java as follows
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;

/** Given a filename or a name and an input stream,
 *  this class generates a JTree representing the
 *  XML structure contained in the file or stream.
 *  Parses with DOM then copies the tree structure
 *  (minus text and comment nodes).
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted. 
 */

public class XMLTree extends JTree {
  public XMLTree(String filename) throws IOException {
    this(filename, new FileInputStream(new File(filename)));
  }

  public XMLTree(String filename, InputStream in) {
    super(makeRootNode(in));
  }

  // This method needs to be static so that it can be called
  // from the call to the parent constructor (super), which
  // occurs before the object is really built.
  
  private static DefaultMutableTreeNode
                                 makeRootNode(InputStream in) {
    try {
      // Use JAXP's DocumentBuilderFactory so that there
      // is no code here that is dependent on a particular
      // DOM parser. Use the system property
      // javax.xml.parsers.DocumentBuilderFactory (set either
      // from Java code or by using the -D option to "java").
      // or jre_dir/lib/jaxp.properties to specify this.
      DocumentBuilderFactory builderFactory =
        DocumentBuilderFactory.newInstance();
      DocumentBuilder builder =
        builderFactory.newDocumentBuilder();
      // Standard DOM code from hereon. The "parse"
      // method invokes the parser and returns a fully parsed
      // Document object. We'll then recursively descend the
      // tree and copy non-text nodes into JTree nodes.
      Document document = builder.parse(in);
      document.getDocumentElement().normalize();
      Element rootElement = document.getDocumentElement();
      DefaultMutableTreeNode rootTreeNode =
        buildTree(rootElement);
      return(rootTreeNode);
    } catch(Exception e) {
      String errorMessage =
        "Error making root node: " + e;
      System.err.println(errorMessage);
      e.printStackTrace();
      return(new DefaultMutableTreeNode(errorMessage));
    }
  }

  private static DefaultMutableTreeNode
                              buildTree(Element rootElement) {
    // Make a JTree node for the root, then make JTree
    // nodes for each child and add them to the root node.
    // The addChildren method is recursive.
    DefaultMutableTreeNode rootTreeNode =
      new DefaultMutableTreeNode(treeNodeLabel(rootElement));
    addChildren(rootTreeNode, rootElement);
    return(rootTreeNode);
  }

  private static void addChildren
                       (DefaultMutableTreeNode parentTreeNode,
                        Node parentXMLElement) {
    // Recursive method that finds all the child elements
    // and adds them to the parent node. We have two types
    // of nodes here: the ones corresponding to the actual
    // XML structure and the entries of the graphical JTree.
    // The convention is that nodes corresponding to the
    // graphical JTree will have the word "tree" in the
    // variable name. Thus, "childElement" is the child XML
    // element whereas "childTreeNode" is the JTree element.
    // This method just copies the non-text and non-comment
    // nodes from the XML structure to the JTree structure.
    
    NodeList childElements =
      parentXMLElement.getChildNodes();
    for(int i=0; i<childelements .getLength(); i++) {
      Node childElement = childElements.item(i);
      if (!(childElement instanceof Text ||
            childElement instanceof Comment)) {
        DefaultMutableTreeNode childTreeNode =
          new DefaultMutableTreeNode
            (treeNodeLabel(childElement));
        parentTreeNode.add(childTreeNode);
        addChildren(childTreeNode, childElement);
      }
    }
  }

  // If the XML element has no attributes, the JTree node
  // will just have the name of the XML element. If the
  // XML element has attributes, the names and values of the
  // attributes will be listed in parens after the XML
  // element name. For example:
  // XML Element: 
  // JTree Node:  blah
  // XML Element: 
  // JTree Node:  blah (foo=bar, baz=quux)

  private static String treeNodeLabel(Node childElement) {
    NamedNodeMap elementAttributes =
      childElement.getAttributes();
    String treeNodeLabel = childElement.getNodeName();
    if (elementAttributes != null &&
        elementAttributes.getLength() > 0) {
      treeNodeLabel = treeNodeLabel + " (";
      int numAttributes = elementAttributes.getLength();
      for(int i=0; i 0) {
          treeNodeLabel = treeNodeLabel + ", ";
        }
        treeNodeLabel =
          treeNodeLabel + attribute.getNodeName() +
          "=" + attribute.getNodeValue();
      }
      treeNodeLabel = treeNodeLabel + ")";
    }
    return(treeNodeLabel);
  }
}

XMLFrame.java Swing application to select an XML document and display in a JTree.

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

/** Invokes an XML parser on an XML document and displays
 *  the document in a JTree. Both the parser and the
 *  document can be specified by the user. The parser
 *  is specified by invoking the program with
 *  java -Djavax.xml.parsers.DocumentBuilderFactory=xxx XMLFrame
 *  If no parser is specified, the Apache Xerces parser is used.
 *  The XML document can be supplied on the command
 *  line, but if it is not given, a JFileChooser is used
 *  to interactively select the file of interest.
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted. 
 */

public class XMLFrame extends JFrame {
  public static void main(String[] args) {
    String jaxpPropertyName =
      "javax.xml.parsers.DocumentBuilderFactory";
    // Pass the parser factory in on the command line with
    // -D to override the use of the Apache parser.
    if (System.getProperty(jaxpPropertyName) == null) {
      String apacheXercesPropertyValue =
        "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl";
      System.setProperty(jaxpPropertyName,
                         apacheXercesPropertyValue);
    }
    String filename;
    if (args.length > 0) {
      filename = args[0];
    } else {
      String[] extensions = { "xml", "tld" };
      WindowUtilities.setNativeLookAndFeel();
      filename = ExtensionFileFilter.getFileName(".",
                                                 "XML Files",
                                                 extensions);
      if (filename == null) {
        filename = "test.xml";
      }
    }
    new XMLFrame(filename);
  }

  public XMLFrame(String filename) {
    try {
      WindowUtilities.setNativeLookAndFeel();
      JTree tree = new XMLTree(filename);
      JFrame frame = new JFrame(filename);
      frame.addWindowListener(new ExitListener());
      Container content = frame.getContentPane();
      content.add(new JScrollPane(tree));
      frame.pack();
      frame.setVisible(true);
    } catch(IOException ioe) {
      System.out.println("Error creating tree: " + ioe);
    }
  }
}

ExtensionFileFilter.java Allows you to specify which file extensions will be displayed in a JFileChooser.

import java.io.File;
import java.util.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;

/** A FileFilter that lets you specify which file extensions 
 *  will be displayed. Also includes a static getFileName 
 *  method that users can call to pop up a JFileChooser for 
 *  a set of file extensions.
 *  

* Adapted from Sun SwingSet demo. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class ExtensionFileFilter extends FileFilter { public static final int LOAD = 0; public static final int SAVE = 1; private String description; private boolean allowDirectories; private Hashtable extensionsTable = new Hashtable(); private boolean allowAll = false; public ExtensionFileFilter(boolean allowDirectories) { this.allowDirectories = allowDirectories; } public ExtensionFileFilter() { this(true); } public static String getFileName(String initialDirectory, String description, String extension) { String[] extensions = new String[]{ extension }; return(getFileName(initialDirectory, description, extensions, LOAD)); } public static String getFileName(String initialDirectory, String description, String extension, int mode) { String[] extensions = new String[]{ extension }; return(getFileName(initialDirectory, description, extensions, mode)); } public static String getFileName(String initialDirectory, String description, String[] extensions) { return(getFileName(initialDirectory, description, extensions, LOAD)); } /** Pops up a JFileChooser that lists files with the * specified extensions. If the mode is SAVE, then the * dialog will have a Save button; otherwise, the dialog * will have an Open button. Returns a String corresponding * to the file's pathname, or null if Cancel was selected. */ public static String getFileName(String initialDirectory, String description, String[] extensions, int mode) { ExtensionFileFilter filter = new ExtensionFileFilter(); filter.setDescription(description); for(int i=0; i<extensions .length; i++) { String extension = extensions[i]; filter.addExtension(extension, true); } JFileChooser chooser = new JFileChooser(initialDirectory); chooser.setFileFilter(filter); int selectVal = (mode==SAVE) ? chooser.showSaveDialog(null) : chooser.showOpenDialog(null); if (selectVal == JFileChooser.APPROVE_OPTION) { String path = chooser.getSelectedFile().getAbsolutePath(); return(path); } else { JOptionPane.showMessageDialog(null, "No file selected."); return(null); } } public void addExtension(String extension, boolean caseInsensitive) { if (caseInsensitive) { extension = extension.toLowerCase(); } if (!extensionsTable.containsKey(extension)) { extensionsTable.put(extension, new Boolean(caseInsensitive)); if (extension.equals("*") || extension.equals("*.*") || extension.equals(".*")) { allowAll = true; } } } public boolean accept(File file) { if (file.isDirectory()) { return(allowDirectories); } if (allowAll) { return(true); } String name = file.getName(); int dotIndex = name.lastIndexOf('.'); if ((dotIndex == -1) || (dotIndex == name.length() - 1)) { return(false); } String extension = name.substring(dotIndex + 1); if (extensionsTable.containsKey(extension)) { return(true); } Enumeration keys = extensionsTable.keys(); while(keys.hasMoreElements()) { String possibleExtension = (String)keys.nextElement(); Boolean caseFlag = (Boolean)extensionsTable.get(possibleExtension); if ((caseFlag != null) && (caseFlag.equals(Boolean.FALSE)) && (possibleExtension.equalsIgnoreCase(extension))) { return(true); } } return(false); } public void setDescription(String description) { this.description = description; } public String getDescription() { return(description); } }

WindowUtilities.java

import javax.swing.*;
import java.awt.*;   // For Color and Container classes.

/** A few utilities that simplify using windows in Swing. 
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 * 
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class WindowUtilities {

  /** Tell system to use native look and feel, as in previous
   *  releases. Metal (Java) LAF is the default otherwise.
   */

  public static void setNativeLookAndFeel() {
    try {
     UIManager.setLookAndFeel(
       UIManager.getSystemLookAndFeelClassName());
    } catch(Exception e) {
      System.out.println("Error setting native LAF: " + e);
    }
  }

  public static void setJavaLookAndFeel() {
    try {
     UIManager.setLookAndFeel(
       UIManager.getCrossPlatformLookAndFeelClassName());
    } catch(Exception e) {
      System.out.println("Error setting Java LAF: " + e);
    }
  }

   public static void setMotifLookAndFeel() {
    try {
      UIManager.setLookAndFeel(
        "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
    } catch(Exception e) {
      System.out.println("Error setting Motif LAF: " + e);
    }
  }

  /** A simplified way to see a JPanel or other Container. Pops
   *  up a JFrame with specified Container as the content pane.
   */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height,
                                    String title,
                                    Color bgColor) {
    JFrame frame = new JFrame(title);
    frame.setBackground(bgColor);
    content.setBackground(bgColor);
    frame.setSize(width, height);
    frame.setContentPane(content);
    frame.addWindowListener(new ExitListener());
    frame.setVisible(true);
    return(frame);
  }

  /** Uses Color.white as the background color. */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height,
                                    String title) {
    return(openInJFrame(content, width, height,
                        title, Color.white));
  }

  /** Uses Color.white as the background color, and the
   *  name of the Container's class as the JFrame title.
   */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height) {
    return(openInJFrame(content, width, height,
                        content.getClass().getName(),
                        Color.white));
  }
}

EXITListener.java

import java.awt.*;
import java.awt.event.*;

/** A listener that you attach to the top-level JFrame of
 *  your application, so that quitting the frame exits the 
 *  application.
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted. 
 */
public class ExitListener extends WindowAdapter {
  public void windowClosing(WindowEvent event) {
    System.exit(0);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10199
Categories:Programming Code Examples, Java/J2EE/J2ME, JavaScript
Tags:Java/J2EE/J2MEJavaScript
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

PreparedStatements.java An example to test the timing differences resulting from repeated raw queries vs. repeated calls #Programming Code Examples #Java/J2EE/J2ME #JDBC

package cwp;

import java.sql.*;

/** An example to test the timing differences resulting
 *  from repeated raw queries vs. repeated calls to
 *  prepared statements. These results will vary dramatically
 *  among database servers and drivers. With my setup
 *  and drivers, Oracle prepared statements took only half
 *  the time that raw queries required when using a modem
 *  connection, and took only 70% of the time that
 *  raw queries required when using a fast LAN connection.
 *  Sybase times were identical in both cases.
 *  

*/ public class PreparedStatements { public static void main(String[] args) { if (args.length 5) && (args[5].equals("print"))) { print = true; } Connection connection = getConnection(driver, url, username, password); if (connection != null) { doPreparedStatements(connection, print); doRawQueries(connection, print); } } private static void doPreparedStatements(Connection conn, boolean print) { try { String queryFormat = "SELECT lastname FROM employees WHERE salary > ?"; PreparedStatement statement = conn.prepareStatement(queryFormat); long startTime = System.currentTimeMillis(); for(int i=0; i<40; i++) { statement.setFloat(1, i*5000); ResultSet results = statement.executeQuery(); if (print) { showResults(results); } } long stopTime = System.currentTimeMillis(); double elapsedTime = (stopTime - startTime)/1000.0; System.out.println("Executing prepared statement " + "40 times took " + elapsedTime + " seconds."); } catch(SQLException sqle) { System.out.println("Error executing statement: " + sqle); } } public static void doRawQueries(Connection conn, boolean print) { try { String queryFormat = "SELECT lastname FROM employees WHERE salary > "; Statement statement = conn.createStatement(); long startTime = System.currentTimeMillis(); for(int i=0; i<40; i++) { ResultSet results = statement.executeQuery(queryFormat + (i*5000)); if (print) { showResults(results); } } long stopTime = System.currentTimeMillis(); double elapsedTime = (stopTime - startTime)/1000.0; System.out.println("Executing raw query " + "40 times took " + elapsedTime + " seconds."); } catch(SQLException sqle) { System.out.println("Error executing query: " + sqle); } } private static void showResults(ResultSet results) throws SQLException { while(results.next()) { System.out.print(results.getString(1) + " "); } System.out.println(); } private static Connection getConnection(String driver, String url, String username, String password) { try { Class.forName(driver); Connection connection = DriverManager.getConnection(url, username, password); return(connection); } catch(ClassNotFoundException cnfe) { System.err.println("Error loading driver: " + cnfe); return(null); } catch(SQLException sqle) { System.err.println("Error connecting: " + sqle); return(null); } } private static void printUsage() { System.out.println("Usage: PreparedStatements host " + "dbName username password " + "oracle|sybase [print]."); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10210
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
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

extract relevant data from a DBResults #Programming Code Examples #Java/J2EE/J2ME #JDBC

package cwp;

import javax.swing.table.*;

/** Simple class that tells a JTable how to extract
 *  relevant data from a DBResults object (which is
 *  used to store the results from a database query).
 */

public class DBResultsTableModel extends AbstractTableModel {
  private DBResults results;

  public DBResultsTableModel(DBResults results) {
    this.results = results;
  }

  public int getRowCount() {
    return(results.getRowCount());
  }

  public int getColumnCount() {
    return(results.getColumnCount());
  }

  public String getColumnName(int column) {
    return(results.getColumnNames()[column]);
  }

  public Object getValueAt(int row, int column) {
    return(results.getRow(row)[column]);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10209
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
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

QueryViewer.java: An interactive database query viewer #Programming Code Examples #Java/J2EE/J2ME #JDBC

# QueryViewer.java  An interactive database query viewer. Connects to the specified Oracle or Sybase database, executes a query, and presents the results in a JTable. Uses the following file:

    * DBResultsTableModel.java Simple class that tells a JTable how to extract relevant data from a DBResults object (which is used to store the results from a database query). 
############################################################################

  package cwp;

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

/** An interactive database query viewer. Connects to
 *  the specified Oracle or Sybase database, executes a query,
 *  and presents the results in a JTable.
 *  

*/ public class QueryViewer extends JFrame implements ActionListener{ public static void main(String[] args) { new QueryViewer(); } private JTextField hostField, dbNameField, queryField, usernameField; private JRadioButton oracleButton, sybaseButton; private JPasswordField passwordField; private JButton showResultsButton; Container contentPane; private JPanel tablePanel; public QueryViewer () { super("Database Query Viewer"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); contentPane = getContentPane(); contentPane.add(makeControlPanel(), BorderLayout.NORTH); pack(); setVisible(true); } /** When the "Show Results" button is pressed or * RETURN is hit while the query textfield has the * keyboard focus, a database lookup is performed, * the results are placed in a JTable, and the window * is resized to accommodate the table. */ public void actionPerformed(ActionEvent event) { String host = hostField.getText(); String dbName = dbNameField.getText(); String username = usernameField.getText(); String password = String.valueOf(passwordField.getPassword()); String query = queryField.getText(); int vendor; if (oracleButton.isSelected()) { vendor = DriverUtilities.ORACLE; } else { vendor = DriverUtilities.SYBASE; } if (tablePanel != null) { contentPane.remove(tablePanel); } tablePanel = makeTablePanel(host, dbName, vendor, username, password, query); contentPane.add(tablePanel, BorderLayout.CENTER); pack(); } // Executes a query and places the result in a // JTable that is, in turn, inside a JPanel. private JPanel makeTablePanel(String host, String dbName, int vendor, String username, String password, String query) { String driver = DriverUtilities.getDriver(vendor); String url = DriverUtilities.makeURL(host, dbName, vendor); DBResults results = DatabaseUtilities.getQueryResults(driver, url, username, password, query, true); JPanel panel = new JPanel(new BorderLayout()); if (results == null) { panel.add(makeErrorLabel()); return(panel); } DBResultsTableModel model = new DBResultsTableModel(results); JTable table = new JTable(model); table.setFont(new Font("Serif", Font.PLAIN, 17)); table.setRowHeight(28); JTableHeader header = table.getTableHeader(); header.setFont(new Font("SansSerif", Font.BOLD, 13)); panel.add(table, BorderLayout.CENTER); panel.add(header, BorderLayout.NORTH); panel.setBorder (BorderFactory.createTitledBorder("Query Results")); return(panel); } // The panel that contains the textfields, checkboxes, // and button. private JPanel makeControlPanel() { JPanel panel = new JPanel(new GridLayout(0, 1)); panel.add(makeHostPanel()); panel.add(makeUsernamePanel()); panel.add(makeQueryPanel()); panel.add(makeButtonPanel()); panel.setBorder (BorderFactory.createTitledBorder("Query Data")); return(panel); } // The panel that has the host and db name textfield and // the driver radio buttons. Placed in control panel. private JPanel makeHostPanel() { JPanel panel = new JPanel(); panel.add(new JLabel("Host:")); hostField = new JTextField(15); panel.add(hostField); panel.add(new JLabel(" DB Name:")); dbNameField = new JTextField(15); panel.add(dbNameField); panel.add(new JLabel(" Driver:")); ButtonGroup vendorGroup = new ButtonGroup(); oracleButton = new JRadioButton("Oracle", true); vendorGroup.add(oracleButton); panel.add(oracleButton); sybaseButton = new JRadioButton("Sybase"); vendorGroup.add(sybaseButton); panel.add(sybaseButton); return(panel); } // The panel that has the username and password textfields. // Placed in control panel. private JPanel makeUsernamePanel() { JPanel panel = new JPanel(); usernameField = new JTextField(10); passwordField = new JPasswordField(10); panel.add(new JLabel("Username: ")); panel.add(usernameField); panel.add(new JLabel(" Password:")); panel.add(passwordField); return(panel); } // The panel that has textfield for entering queries. // Placed in control panel. private JPanel makeQueryPanel() { JPanel panel = new JPanel(); queryField = new JTextField(40); queryField.addActionListener(this); panel.add(new JLabel("Query:")); panel.add(queryField); return(panel); } // The panel that has the "Show Results" button. // Placed in control panel. private JPanel makeButtonPanel() { JPanel panel = new JPanel(); showResultsButton = new JButton("Show Results"); showResultsButton.addActionListener(this); panel.add(showResultsButton); return(panel); } // Shows warning when bad query sent. private JLabel makeErrorLabel() { JLabel label = new JLabel("No Results", JLabel.CENTER); label.setFont(new Font("Serif", Font.BOLD, 36)); return(label); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10208
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
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

EmployeeCreation.java: Make a simple "employees" table using the database utilities #Programming Code Examples #Java/J2EE/J2ME #JDBC

package cwp;

import java.sql.*;

/** Make a simple "employees" table using DatabaseUtilities.
 */

public class EmployeeCreation {
  public static Connection createEmployees(String driver,
                                           String url,
                                           String username,
                                           String password,
                                           boolean close) {
    String format =
      "(id int, firstname varchar(32), lastname varchar(32), " +
      "language varchar(16), salary float)";
    String[] employees =
      {"(1, 'Wye', 'Tukay', 'COBOL', 42500)",
       "(2, 'Britt', 'Tell',   'C++',   62000)",
       "(3, 'Max',  'Manager', 'none',  15500)",
       "(4, 'Polly', 'Morphic', 'Smalltalk', 51500)",
       "(5, 'Frank', 'Function', 'Common Lisp', 51500)",
       "(6, 'Justin', 'Timecompiler', 'Java', 98000)",
       "(7, 'Sir', 'Vlet', 'Java', 114750)",
       "(8, 'Jay', 'Espy', 'Java', 128500)" };
    return(DatabaseUtilities.createTable(driver, url,
                                         username, password,
                                         "employees",
                                         format, employees,
                                         close));    
  }

  public static void main(String[] args) {
    if (args.length < 5) {
      printUsage();
      return;
    }
    String vendorName = args[4];
    int vendor = DriverUtilities.getVendor(vendorName);
    if (vendor == DriverUtilities.UNKNOWN) {
      printUsage();
      return;
    }
    String driver = DriverUtilities.getDriver(vendor);
    String host = args[0];
    String dbName = args[1];
    String url =
      DriverUtilities.makeURL(host, dbName, vendor);
    String username = args[2];
    String password = args[3];
    createEmployees(driver, url, username, password, true);
  }

  private static void printUsage() {
    System.out.println("Usage: EmployeeCreation host dbName " +
                       "username password oracle|sybase.");
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10207
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
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

EmployeeTest2.java: A test case for the database utilities. Prints results formatted as an HTML table. #Programming Code Examples #Java/J2EE/J2ME #JDBC

package cwp;

import java.sql.*;

/** Connect to Oracle or Sybase and print "employees" table
 *  as an HTML table.
 *  

*/ public class EmployeeTest2 { public static void main(String[] args) { if (args.length < 5) { printUsage(); return; } String vendorName = args[4]; int vendor = DriverUtilities.getVendor(vendorName); if (vendor == DriverUtilities.UNKNOWN) { printUsage(); return; } String driver = DriverUtilities.getDriver(vendor); String host = args[0]; String dbName = args[1]; String url = DriverUtilities.makeURL(host, dbName, vendor); String username = args[2]; String password = args[3]; String query = "SELECT * FROM employees"; DBResults results = DatabaseUtilities.getQueryResults(driver, url, username, password, query, true); System.out.println(results.toHTMLTable("CYAN")); } private static void printUsage() { System.out.println("Usage: EmployeeTest2 host dbName " + "username password oracle|sybase."); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10206
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
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

EmployeeTest.java: A test case for the database utilities. Prints results in plain text. #Programming Code Examples #Java/J2EE/J2ME #JDBC


package cwp;

import java.sql.*;

/** Connect to Oracle or Sybase and print "employees" table.
 *  

*/ public class EmployeeTest { public static void main(String[] args) { if (args.length < 5) { printUsage(); return; } String vendorName = args[4]; int vendor = DriverUtilities.getVendor(vendorName); if (vendor == DriverUtilities.UNKNOWN) { printUsage(); return; } String driver = DriverUtilities.getDriver(vendor); String host = args[0]; String dbName = args[1]; String url = DriverUtilities.makeURL(host, dbName, vendor); String username = args[2]; String password = args[3]; DatabaseUtilities.printTable(driver, url, username, password, "employees", 12, true); } private static void printUsage() { System.out.println("Usage: EmployeeTest host dbName " + "username password oracle|sybase."); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10205
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
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