SaleEntry2.jsp Page that uses the SaleEntry bean, using the param attribute to read request parameters and assign them to bean properties #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics


SaleEntry2.jsp Page that uses the SaleEntry bean, using the param attribute to read request parameters and assign them to bean properties


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Example of using jsp:setProperty and an explicity association
with an input parameter. See SaleEntry1.jsp
and SaleEntry3.jsp for alternatives. 
   
Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>Using jsp:setProperty</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>

<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
  <TR><TH CLASS="TITLE">
      Using jsp:setProperty</TABLE>
<jsp:useBean id="entry" class="cwp.SaleEntry" />
<jsp:setProperty 
    name="entry"
    property="itemID"
    param="itemID" />
<jsp:setProperty 
    name="entry"
    property="numItems"
    param="numItems" />
<%-- WARNING! Both the JSWDK 1.0.1 and the Java Web Server
              have a bug that makes them fail on double
              type conversions of the following sort.
--%>
<jsp:setProperty 
    name="entry"
    property="discountCode"
    param="discountCode" />
<BR>
<TABLE ALIGN="CENTER" BORDER=1>
<TR CLASS="COLORED">
  <TH>Item ID<TH>Unit Price<TH>Number Ordered<TH>Total Price
<TR ALIGN="RIGHT">
  <TD><jsp:getProperty name="entry" property="itemID" />
  <TD>$<jsp:getProperty name="entry" property="itemCost" />
  <TD><jsp:getProperty name="entry" property="numItems" />
  <TD>$<jsp:getProperty name="entry" property="totalCost" />
</TABLE>     
</BODY>
</HTML>


SaleEntry.java //SaleEntry Bean

package cwp;

/** Simple bean to illustrate the various forms
 *  of jsp:setProperty.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SaleEntry {
  private String itemID = "unknown";
  private double discountCode = 1.0;
  private int numItems = 0;

  public String getItemID() {
    return(itemID);
  }

  public void setItemID(String itemID) {
    if (itemID != null) {
      this.itemID = itemID;
    } else {
      this.itemID = "unknown";
    }
  }

  public double getDiscountCode() {
    return(discountCode);
  }

  public void setDiscountCode(double discountCode) {
    this.discountCode = discountCode;
  }

  public int getNumItems() {
    return(numItems);
  }

  public void setNumItems(int numItems) {
    this.numItems = numItems;
  }

  // In real life, replace this with database lookup.

  public double getItemCost() {
    double cost;
    if (itemID.equals("a1234")) {
      cost = 12.99*getDiscountCode();
    } else {
      cost = -9999;
    }
    return(roundToPennies(cost));
  }

  private double roundToPennies(double cost) {
    return(Math.floor(cost*100)/100.0);
  }

  public double getTotalCost() {
    return(getItemCost() * getNumItems());
  }
}



Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10268
Categories:Programming Code Examples, Java/J2EE/J2ME, Applets and Basic Graphics
Tags:Java/J2EE/J2MEApplets and Basic Graphics
Post Data:2017-01-02 16:04:28

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

SaleEntry1.jsp Page that uses the SaleEntry bean, using explicit Java code to read request parameters and assign them to bean properties. #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics

SaleEntry1.jsp Page that uses the SaleEntry bean, using explicit Java code to read request parameters and assign them to bean properties.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Example of using jsp:setProperty with an explicit value
supplied to the "value" attribute. See SaleEntry2.jsp
and SaleEntry3.jsp for alternatives. 

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>Using jsp:setProperty</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>

<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
  <TR><TH CLASS="TITLE">
      Using jsp:setProperty</TABLE>
<jsp:useBean id="entry" class="cwp.SaleEntry" />
<jsp:setProperty 
    name="entry" 
    property="itemID"
    value='<%= request.getParameter("itemID") %>' />
<%
int numItemsOrdered = 1;
try {
  numItemsOrdered = 
    Integer.parseInt(request.getParameter("numItems"));
} catch(NumberFormatException nfe) {}
%>
<jsp:setProperty 
    name="entry" 
    property="numItems"
    value="<%= numItemsOrdered %>" />
<% 
double discountCode = 1.0;
try {
  String discountString = 
    request.getParameter("discountCode");
  // Double.parseDouble not available in JDK 1.1.
  discountCode = 
    Double.valueOf(discountString).doubleValue();
} catch(NumberFormatException nfe) {}
%>
<jsp:setProperty 
    name="entry" 
    property="discountCode"
    value="<%= discountCode %>" />
<BR>
<TABLE ALIGN="CENTER" BORDER=1>
<TR CLASS="COLORED">
  <TH>Item ID<TH>Unit Price<TH>Number Ordered<TH>Total Price
<TR ALIGN="RIGHT">
  <TD><jsp:getProperty name="entry" property="itemID" />
  <TD>$<jsp:getProperty name="entry" property="itemCost" />
  <TD><jsp:getProperty name="entry" property="numItems" />
  <TD>$<jsp:getProperty name="entry" property="totalCost" />
</TABLE>       
</BODY>
</HTML>


SaleEntry.Java //sale entry bean

package cwp;

/** Simple bean to illustrate the various forms
 *  of jsp:setProperty.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SaleEntry {
  private String itemID = "unknown";
  private double discountCode = 1.0;
  private int numItems = 0;

  public String getItemID() {
    return(itemID);
  }

  public void setItemID(String itemID) {
    if (itemID != null) {
      this.itemID = itemID;
    } else {
      this.itemID = "unknown";
    }
  }

  public double getDiscountCode() {
    return(discountCode);
  }

  public void setDiscountCode(double discountCode) {
    this.discountCode = discountCode;
  }

  public int getNumItems() {
    return(numItems);
  }

  public void setNumItems(int numItems) {
    this.numItems = numItems;
  }

  // In real life, replace this with database lookup.

  public double getItemCost() {
    double cost;
    if (itemID.equals("a1234")) {
      cost = 12.99*getDiscountCode();
    } else {
      cost = -9999;
    }
    return(roundToPennies(cost));
  }

  private double roundToPennies(double cost) {
    return(Math.floor(cost*100)/100.0);
  }

  public double getTotalCost() {
    return(getItemCost() * getNumItems());
  }
}



Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10267
Categories:Programming Code Examples, Java/J2EE/J2ME, Applets and Basic Graphics
Tags:Java/J2EE/J2MEApplets and Basic Graphics
Post Data:2017-01-02 16:04:28

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

SaleEntry.java Bean used to demonstrate the various approaches to reading request parameters and stuffing them into Java objects. #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics

package cwp;

/** Simple bean to illustrate the various forms
 *  of jsp:setProperty.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SaleEntry {
  private String itemID = "unknown";
  private double discountCode = 1.0;
  private int numItems = 0;

  public String getItemID() {
    return(itemID);
  }

  public void setItemID(String itemID) {
    if (itemID != null) {
      this.itemID = itemID;
    } else {
      this.itemID = "unknown";
    }
  }

  public double getDiscountCode() {
    return(discountCode);
  }

  public void setDiscountCode(double discountCode) {
    this.discountCode = discountCode;
  }

  public int getNumItems() {
    return(numItems);
  }

  public void setNumItems(int numItems) {
    this.numItems = numItems;
  }

  // In real life, replace this with database lookup.

  public double getItemCost() {
    double cost;
    if (itemID.equals("a1234")) {
      cost = 12.99*getDiscountCode();
    } else {
      cost = -9999;
    }
    return(roundToPennies(cost));
  }

  private double roundToPennies(double cost) {
    return(Math.floor(cost*100)/100.0);
  }

  public double getTotalCost() {
    return(getItemCost() * getNumItems());
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10266
Categories:Programming Code Examples, Java/J2EE/J2ME, Applets and Basic Graphics
Tags:Java/J2EE/J2MEApplets and Basic Graphics
Post Data:2017-01-02 16:04:28

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

StringBean.jsp Page that manipulates the StringBean bean with both jsp:useBean (i.e., XML-style) syntax #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics

StringBean.jsp Page that manipulates the StringBean bean with both jsp:useBean (i.e., XML-style) syntax


package cwp;

/** Simple bean to illustrate sharing beans through
 *  use of the scope attribute of jsp:useBean.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class AccessCountBean {
  private String firstPage;
  private int accessCount = 1;

  public String getFirstPage() {
    return(firstPage);
  }

  public void setFirstPage(String firstPage) {
    this.firstPage = firstPage;
  }

  public int getAccessCount() {
    return(accessCount++);
  }
}


Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10265
Categories:Programming Code Examples, Java/J2EE/J2ME, Applets and Basic Graphics
Tags:Java/J2EE/J2MEApplets and Basic Graphics
Post Data:2017-01-02 16:04:28

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

The class that actually gets the strings over the network by means of an ObjectInputStream via HTTP tunneling. #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics

import java.net.*;
import java.io.*;

/** When this class is built, it returns a value
 *  immediately, but this value returns false for isDone
 *  and null for getQueries. Meanwhile, it starts a Thread
 *  to request an array of query strings from the server,
 *  reading them in one fell swoop by means of an
 *  ObjectInputStream. Once they've all arrived, they
 *  are placed in the location getQueries returns,
 *  and the isDone flag is switched to true.
 *  Used by the ShowQueries applet.
 *  

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * May be freely used or adapted. */ public class QueryCollection implements Runnable { private String[] queries; private String[] tempQueries; private boolean isDone = false; private URL dataURL; public QueryCollection(String urlSuffix, URL currentPage) { try { // Only the URL suffix need be supplied, since // the rest of the URL is derived from the current page. String protocol = currentPage.getProtocol(); String host = currentPage.getHost(); int port = currentPage.getPort(); dataURL = new URL(protocol, host, port, urlSuffix); Thread queryRetriever = new Thread(this); queryRetriever.start(); } catch(MalformedURLException mfe) { isDone = true; } } public void run() { try { tempQueries = retrieveQueries(); queries = tempQueries; } catch(IOException ioe) { tempQueries = null; queries = null; } isDone = true; } public String[] getQueries() { return(queries); } public boolean isDone() { return(isDone); } private String[] retrieveQueries() throws IOException { URLConnection connection = dataURL.openConnection(); // Make sure browser doesn't cache this URL, since // I want different queries for each request. connection.setUseCaches(false); // Use ObjectInputStream so I can read a String[] // all at once. ObjectInputStream in = new ObjectInputStream(connection.getInputStream()); try { // The return type of readObject is Object, so // I need a typecast to the actual type. String[] queryStrings = (String[])in.readObject(); return(queryStrings); } catch(ClassNotFoundException cnfe) { return(null); } } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10264
Categories:Programming Code Examples, Java/J2EE/J2ME, Applets and Basic Graphics
Tags:Java/J2EE/J2MEApplets and Basic Graphics
Post Data:2017-01-02 16:04:28

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

An applet that reads arrays of strings packaged inside a QueryCollection and places them in a scrolling TextArea. #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics

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

/** Applet reads arrays of strings packaged inside
 *  a QueryCollection and places them in a scrolling
 *  TextArea. The QueryCollection obtains the strings
 *  by means of a serialized object input stream
 *  connected to the QueryGenerator servlet.
 *  

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * May be freely used or adapted. */ public class ShowQueries extends Applet implements ActionListener, Runnable { private TextArea queryArea; private Button startButton, stopButton, clearButton; private QueryCollection currentQueries; private QueryCollection nextQueries; private boolean isRunning = false; private String address = "/servlet/cwp.QueryGenerator"; private URL currentPage; public void init() { setBackground(Color.white); setLayout(new BorderLayout()); queryArea = new TextArea(); queryArea.setFont(new Font("Serif", Font.PLAIN, 14)); add(queryArea, BorderLayout.CENTER); Panel buttonPanel = new Panel(); Font buttonFont = new Font("SansSerif", Font.BOLD, 16); startButton = new Button("Start"); startButton.setFont(buttonFont); startButton.addActionListener(this); buttonPanel.add(startButton); stopButton = new Button("Stop"); stopButton.setFont(buttonFont); stopButton.addActionListener(this); buttonPanel.add(stopButton); clearButton = new Button("Clear TextArea"); clearButton.setFont(buttonFont); clearButton.addActionListener(this); buttonPanel.add(clearButton); add(buttonPanel, BorderLayout.SOUTH); currentPage = getCodeBase(); // Request a set of sample queries. They // are loaded in a background thread, and // the applet checks to see if they have finished // loading before trying to extract the strings. currentQueries = new QueryCollection(address, currentPage); nextQueries = new QueryCollection(address, currentPage); } /** If you press the "Start" button, the system * starts a background thread that displays * the queries in the TextArea. Pressing "Stop" * halts the process, and "Clear" empties the * TextArea. */ public void actionPerformed(ActionEvent event) { if (event.getSource() == startButton) { if (!isRunning) { Thread queryDisplayer = new Thread(this); isRunning = true; queryArea.setText(""); queryDisplayer.start(); showStatus("Started display thread..."); } else { showStatus("Display thread already running..."); } } else if (event.getSource() == stopButton) { isRunning = false; showStatus("Stopped display thread..."); } else if (event.getSource() == clearButton) { queryArea.setText(""); } } /** The background thread takes the currentQueries * object and every half-second places one of the queries * the object holds into the bottom of the TextArea. When * all of the queries have been shown, the thread copies * the value of the nextQueries object into * currentQueries, sends a new request to the server * in order to repopulate nextQueries, and repeats * the process. */ public void run() { while(isRunning) { showQueries(currentQueries); currentQueries = nextQueries; nextQueries = new QueryCollection(address, currentPage); } } private void showQueries(QueryCollection queryEntry) { // If request has been sent to server but the result // isn't back yet, poll every second. This should // happen rarely but is possible with a slow network // connection or an overloaded server. while(!queryEntry.isDone()) { showStatus("Waiting for data from server..."); pause(1); } showStatus("Received data from server..."); String[] queries = queryEntry.getQueries(); String linefeed = "n"; // Put a string into TextArea every half-second. for(int i=0; i<queries .length; i++) { if (!isRunning) { return; } queryArea.append(queries[i]); queryArea.append(linefeed); pause(0.5); } } public void pause(double seconds) { try { Thread.sleep((long)(seconds*1000)); } catch(InterruptedException ie) {} } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10263
Categories:Programming Code Examples, Java/J2EE/J2ME, Applets and Basic Graphics
Tags:Java/J2EE/J2MEApplets and Basic Graphics
Post Data:2017-01-02 16:04:28

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

A class the encapsulates the URLs used by various search engines. #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics

SearchSpec.java
*******************
/** Small class that encapsulates how to construct a
 *  search string for a particular search engine.
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,

 *  May be freely used or adapted.
 */

public class SearchSpec {
  private String name, baseURL, numResultsSuffix;

  private static SearchSpec[] commonSpecs =
    { new SearchSpec("google",
                     "http://www.google.com/search?q=",
                     "&num="),
      new SearchSpec("infoseek",
                     "http://infoseek.go.com/Titles?qt=",
                     "&nh="),
      new SearchSpec("lycos",
                     "http://lycospro.lycos.com/cgi-bin/" +
                        "pursuit?query=",
                     "&maxhits="),
      new SearchSpec("hotbot",
                     "http://www.hotbot.com/?MT=",
                     "&DC=")
    };

  public SearchSpec(String name,
                    String baseURL,
                    String numResultsSuffix) {
    this.name = name;
    this.baseURL = baseURL;
    this.numResultsSuffix = numResultsSuffix;
  }

  public String makeURL(String searchString,
                        String numResults) {
    return(baseURL + searchString +
           numResultsSuffix + numResults);
  }

  public String getName() {
    return(name);
  }

  public static SearchSpec[] getCommonSpecs() {
    return(commonSpecs);
  }
}

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

An applet that searches multiple search engines, displaying the results in side-by-side frame cells. #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics

Using Applets as Front Ends to Server-Side Programs
**************************************************
SearchApplet.java An applet that searches multiple search engines,
 displaying the results in side-by-side frame cells. Uses the following files: 
SearchSpec.javaParallelSearches.htmlSearchAppletFrame.htmlGoogleResultsFrame.htmlInfoseekResultsFrame.htmlLycosResultsFrame.html
***************************************************
//
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
//

/** An applet that reads a value from a TextField,
 *  then uses it to build three distinct URLs with embedded
 *  GET data: one each for Google, Infoseek, and Lycos.
 *  The browser is directed to retrieve each of these
 *  URLs, displaying them in side-by-side frame cells.
 *  Note that standard HTML forms cannot automatically
 *  perform multiple submissions in this manner.
 *  

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * May be freely used or adapted. */ public class SearchApplet extends Applet implements ActionListener { private TextField queryField; private Button submitButton; public void init() { setBackground(Color.white); setFont(new Font("Serif", Font.BOLD, 18)); add(new Label("Search String:")); queryField = new TextField(40); queryField.addActionListener(this); add(queryField); submitButton = new Button("Send to Search Engines"); submitButton.addActionListener(this); add(submitButton); } /** Submit data when button is pressed or * user presses Return in the TextField. */ public void actionPerformed(ActionEvent event) { String query = URLEncoder.encode(queryField.getText()); SearchSpec[] commonSpecs = SearchSpec.getCommonSpecs(); // Omitting HotBot (last entry), as they use JavaScript to // pop result to top-level frame. Thus the length-1 below. for(int i=0; i<commonspecs .length-1; i++) { try { SearchSpec spec = commonSpecs[i]; // The SearchSpec class builds URLs of the // form needed by some common search engines. URL searchURL = new URL(spec.makeURL(query, "10")); String frameName = "results" + i; getAppletContext().showDocument(searchURL, frameName); } catch(MalformedURLException mue) {} } } }

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

Custom AWT Slider #Programming Code Examples #Java/J2EE/J2ME #AWT Components

*****************
Custom AWT Slider 

    * LabeledCostSlider.java. A numeric slider class with attached label.
    * CostSlider.java. A slider class that lets you read numeric values. Used in the LabeledCostSlider class.
    * Slider.java. A slider class: a combination of Scrollbar and TextField. Used in the CostSlider class.
    * ScrollbarPanel.java A Panel with adjustable top and bottom insets, used by the Slider class to change the thickness of the Slider.
*****************
LabeledCostSlider.java. A numeric slider class with attached label. 
>>>>>>>>>>>>>>>>>
import java.awt.*;

/** A CostSlider with a label centered above it. 
 *************
 

public class LabeledCostSlider extends Panel {
  public LabeledCostSlider(String labelString,
                           Font labelFont,
                           int minValue, int maxValue,
                           int initialValue,
                           Everest app) {
    setLayout(new BorderLayout());
    Label label = new Label(labelString, Label.CENTER);
    if (labelFont != null) {
      label.setFont(labelFont);
    }
    add(label, BorderLayout.NORTH);
    CostSlider slider = new CostSlider(minValue, 
                                       maxValue, 
                                       initialValue,
                                       app);
    add(slider, BorderLayout.CENTER);
  }
}  
< <<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>
CostSlider.java. A slider class that lets you read numeric values. Used in the LabeledCostSlider class. 
>>>>>>>>>>>>>>>>>>>
/** A Slider that takes an Everest applet as an argument,
 *  calling back to its setCostField when the slider value
 *  changes.
 *
 *******************

public class CostSlider extends Slider {
  private Everest app;

  public CostSlider(int minValue, int maxValue,
                    int initialValue, Everest app) {
    super(minValue, maxValue, initialValue);
    this.app = app;
  }

  public void doAction(int value) {
    app.setCostField(value);
  }
}
< <<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>
Slider.java. A slider class: a combination of Scrollbar and TextField. Used in the CostSlider class. 
>>>>>>>>>>>>>>>>>>>>>
import java.awt.*;
import java.awt.event.*;

/** A class that combines a horizontal Scrollbar and a TextField
 *  (to the right of the Scrollbar). The TextField shows the
 *  current scrollbar value, plus, if setEditable(true) is set,
 *  it can be used to change the value as well.
 *
 ********************

public class Slider extends Panel implements ActionListener,
                                             AdjustmentListener {
  private Scrollbar scrollbar;
  private TextField textfield;
  private ScrollbarPanel scrollbarPanel;
  private int preferredWidth = 250;

  /** Construct a slider with the specified min, max and initial
   *  values. The "bubble" (thumb) size is set to 1/10th the
   *  scrollbar range.
   */

  public Slider(int minValue, int maxValue, int initialValue) {
    this(minValue, maxValue, initialValue,
         (maxValue - minValue)/10);
  }

  /** Construct a slider with the specified min, max,and initial
   *  values, plus the specified "bubble" (thumb) value. This
   *  bubbleSize should be specified in the units that min and
   *  max use, not in pixels. Thus, if min is 20 and max is 320,
   *  then a bubbleSize of 30 is 10% of the visible range.
   */

  public Slider(int minValue, int maxValue, int initialValue,
                int bubbleSize) {
    setLayout(new BorderLayout());
    maxValue = maxValue + bubbleSize;
    scrollbar = new Scrollbar(Scrollbar.HORIZONTAL,
                              initialValue, bubbleSize,
                              minValue, maxValue);
    scrollbar.addAdjustmentListener(this);
    scrollbarPanel = new ScrollbarPanel(6);
    scrollbarPanel.add(scrollbar, BorderLayout.CENTER);
    add(scrollbarPanel, BorderLayout.CENTER);
    textfield = new TextField(numDigits(maxValue) + 1);
    textfield.addActionListener(this);
    setFontSize(12);
    textfield.setEditable(false);
    setTextFieldValue();
    add(textfield, BorderLayout.EAST);
  }

  /** A place holder to override for action to be taken when
   *  scrollbar changes.
   */

  public void doAction(int value) {
  }

  /** When textfield changes, sets the scrollbar */

  public void actionPerformed(ActionEvent event) {
    String value = textfield.getText();
    int oldValue = getValue();
    try {
      setValue(Integer.parseInt(value.trim()));
    } catch(NumberFormatException nfe) {
      setValue(oldValue);
    }
  }

  /** When scrollbar changes, sets the textfield */

  public void adjustmentValueChanged(AdjustmentEvent event) {
    setTextFieldValue();
    doAction(scrollbar.getValue());
  }

  /** Returns the Scrollbar part of the Slider. */

  public Scrollbar getScrollbar() {
    return(scrollbar);
  }

  /** Returns the TextField part of the Slider */

  public TextField getTextField() {
    return(textfield);
  }

  /** Changes the preferredSize to take a minimum width, since
   *  super-tiny scrollbars are hard to manipulate.
   */

  public Dimension getPreferredSize() {
    Dimension d = super.getPreferredSize();
    d.height = textfield.getPreferredSize().height;
    d.width = Math.max(d.width, preferredWidth);
    return(d);
  }

  /** This just calls preferredSize */

  public Dimension getMinimumSize() {
    return(getPreferredSize());
  }

  /** To keep scrollbars legible, a minimum width is set. This
   *  returns the current value (default is 150).
   */

  public int getPreferredWidth() {
    return(preferredWidth);
  }

  /** To keep scrollbars legible, a minimum width is set. This
   *  sets the current value (default is 150).
   */

  public void setPreferredWidth(int preferredWidth) {
    this.preferredWidth = preferredWidth;
  }

  /** This returns the current scrollbar value */

  public int getValue() {
    return(scrollbar.getValue());
  }

  /** This assigns the scrollbar value. If it is below the
   *  minimum value or above the maximum, the value is set to
   *  the min and max value, respectively.
   */

  public void setValue(int value) {
    scrollbar.setValue(value);
    setTextFieldValue();
  }

  /** Sometimes horizontal scrollbars look odd if they are very
   *  tall. So empty top/bottom margins can be set. This returns
   *  the margin setting. The default is four.
   */

  public int getMargins() {
    return(scrollbarPanel.getMargins());
  }

  /** Sometimes horizontal scrollbars look odd if they are very
   *  tall. So empty top/bottom margins can be set. This sets
   *  the margin setting.
   */

  public void setMargins(int margins) {
    scrollbarPanel.setMargins(margins);
  }

  /** Returns the current textfield string. In most cases this
   *  is just the same as a String version of getValue, except
   *  that there may be padded blank spaces at the left.
   */

  public String getText() {
    return(textfield.getText());
  }

  /** This sets the TextField value directly. Use with extreme
   *  caution since it does not right-align or check if value
   *  is numeric.
   */

  public void setText(String text) {
    textfield.setText(text);
  }

  /** Returns the Font being used by the textfield.
   *  Courier bold 12 is the default.
   */

  public Font getFont() {
    return(textfield.getFont());
  }

  /** Changes the Font being used by the textfield. */

  public void setFont(Font textFieldFont) {
    textfield.setFont(textFieldFont);
  }

  /** The size of the current font */

  public int getFontSize() {
    return(getFont().getSize());
  }

  /** Rather than setting the whole font, you can just set the
   *  size (Monospaced bold will be used for the family/face).
   */

  public void setFontSize(int size) {
    setFont(new Font("Monospaced", Font.BOLD, size));
  }

  /** Determines if the textfield is editable. If it is, you can
   *  enter a number to change the scrollbar value. In such a
   *  case, entering a value outside the legal range results in
   *  the min or max legal value. A non-integer is ignored.
   */

  public boolean isEditable() {
    return(textfield.isEditable());
  }

  /** Determines if you can enter values directly into the
   *  textfield to change the scrollbar.
   */

  public void setEditable(boolean editable) {
    textfield.setEditable(editable);
  }

  // Sets a right-aligned textfield number.

  private void setTextFieldValue() {
    int value = scrollbar.getValue();
    int digits = numDigits(scrollbar.getMaximum());
    String valueString = padString(value, digits);
    textfield.setText(valueString);
  }

  // Repeated String concatenation is expensive, but this is
  // only used to add a small amount of padding, so converting
  // to a StringBuffer would not pay off.

  private String padString(int value, int digits) {
    String result = String.valueOf(value);
    for(int i=result.length(); i<digits ; i++) {
      result = " " + result;
    }
    return(result + " ");
  }

  // Determines the number of digits in a decimal number.

  private static final double LN10 = Math.log(10.0);

  private static int numDigits(int num) {
    return(1 + (int)Math.floor(Math.log((double)num)/LN10));
  }
}
<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>
ScrollbarPanel.java A Panel with adjustable top and bottom insets, used by the Slider class to change the thickness of the Slider.
>>>>>>>>>>>>>>>>>>>
import java.awt.*;

/** A Panel with adjustable top/bottom insets value.
 *  Used to hold a Scrollbar in the Slider class.
 *
 *******************

public class ScrollbarPanel extends Panel {
  private Insets insets;

  public ScrollbarPanel(int margins) {
    setLayout(new BorderLayout());
    setMargins(margins);
  }

  public Insets insets() {
    return(insets);
  }

  public int getMargins() {
    return(insets.top);
  }

  public void setMargins(int margins) {
    this.insets = new Insets(margins, 0, margins, 0);
  }
}
< <<<<<<<<<<<<<<<<<<<<

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

Create PopupMenu and add MenuItems #Programming Code Examples #Java/J2EE/J2ME #AWT Components

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
************************
/** Simple demo of pop-up menus. 
 *
 ********************

public class ColorPopupMenu extends Applet
                            implements ActionListener {
 private String[] colorNames =
   { "White", "Light Gray", "Gray", "Dark Gray", "Black" };
  private Color[] colors =
    { Color.white, Color.lightGray, Color.gray,
      Color.darkGray, Color.black };
  private PopupMenu menu;

  /** Create PopupMenu and add MenuItems. */
                              
  public void init() {
    setBackground(Color.gray);
    menu = new PopupMenu("Background Color");
    enableEvents(AWTEvent.MOUSE_EVENT_MASK);
    MenuItem colorName;
    for(int i=0; i<colornames .length; i++) {
      colorName = new MenuItem(colorNames[i]);
      menu.add(colorName);
      colorName.addActionListener(this);
      menu.addSeparator();
    }
    add(menu);
  }

  /** Don't use a MouseListener, since in Win95/98/NT
   *  you have to check isPopupTrigger in
   *  mouseReleased, but do it in mousePressed in
   *  Solaris (boo!).
   /././././././.**
  public void processMouseEvent(MouseEvent event) {
    if (event.isPopupTrigger()) {
      menu.show(event.getComponent(), event.getX(), 
                event.getY());
    }
    super.processMouseEvent(event);
  }
  
  public void actionPerformed(ActionEvent event) {
    setBackground(colorNamed(event.getActionCommand()));
    repaint();
  }

  private Color colorNamed(String colorName) {
    for(int i=0; i<colorNames.length; i++) {
      if(colorNames[i].equals(colorName)) {
        return(colors[i]);
      }
    }
    return(Color.white);
  }
}

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