Calculator by using Swings



Web Technologies MaterialCalculator by using Swingsimport java.awt.FlowLayout;import java.awt.GridLayout;import java.awt.Panel;import javax.swing.*;import java.awt.event.*;public class calc{ static JFrame frame=new JFrame("Calculator");static Panel pan=new Panel();static JButton[] but=new JButton[15];static JTextField txt=new JTextField(15);static String str1="";static String str2="";static char op;public static void main(String[] args) {// TODO code application logic herefor(inti=0;i<=9;i++)but[i]=new JButton(i+"");but[10]=new JButton("+");but[11]=new JButton("-");but[12]=new JButton("*");but[13]=new JButton("/");but[14]=new JButton("=");Handler handler=new Handler();pan.setLayout(new GridLayout(5,3));for(inti=0;i<15;i++){but[i].addActionListener(handler);pan.add(but[i]);}frame.setLayout(new FlowLayout());frame.add(txt);frame.add(pan);frame.setVisible(true);frame.setSize(200, 250);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }public static class Handler implements ActionListener{public void actionPerformed(ActionEventae) { //throw new UnsupportedOperationException("Not supported yet.");for(inti=0;i<=9;i++)if(ae.getSource()==but[i])txt.setText(txt.getText()+i);if(ae.getSource()==but[10]) {str1=txt.getText();op='+';txt.setText(""); }if(ae.getSource()==but[11]) {str1=txt.getText();op='-';txt.setText(""); }if(ae.getSource()==but[12]) { str1=txt.getText();op='*';txt.setText(""); }if(ae.getSource()==but[13]) {str1=txt.getText();op='/';txt.setText(""); }if(ae.getSource()==but[14]) { str2=txt.getText();if(op=='+')txt.setText(""+(Integer.parseInt(str1)+Integer.parseInt(str2)));if(op=='-')txt.setText(""+(Integer.parseInt(str1)-Integer.parseInt(str2)));if(op=='*')txt.setText(""+(Integer.parseInt(str1)*Integer.parseInt(str2)));if(op=='/')txt.setText(""+(Integer.parseInt(str1)/Integer.parseInt(str2)));} } }}Basic Calculator using Appletsimport java.awt.*; import java.applet.*;import java.awt.event.*; import java.lang.NullPointerException;public class Applet2 extends Applet implements ActionListener {TextField tf1,tf2,tf3;Label l1,l2,l3,l4;Button b1,b2,b3,b4;int num1,num2,res=0;public void init() {l1=new Label("Enter Number 1:");add(l1);tf1=new TextField(5); add(tf1);l2=new Label("Enter Number 2:");add(l2);tf2=new TextField(5);add(tf2);b1= new Button("+");add(b1);b2= new Button("-");add(b2);b3= new Button("*");add(b3);b4= new Button("/");add(b4);tf3=new TextField(5);add(tf3);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this); }public void actionPerformed(ActionEvent ae) {try {num1 = Integer.parseInt(tf1.getText());num2 = Integer.parseInt(tf2.getText());String s = ae.getActionCommand();if(s.equals("+"))res = num1+num2;else if(s.equals("-"))res = num1-num2;else if(s.equals("*"))res = num1*num2;else if(s.equals("/"))res = num1/num2;tf3.setText(Integer.toString(res));}catch(NullPointerException e) { }catch(Exception rse) { }}public void destroy() { }}Multithreading in Java:Java provides built-in support for?multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than multitasking processes.I need to define another term related to threads:?process:?A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.Creating a Thread:Java defines two ways in which this can be accomplished:You can implement the Runnable interface.You can extend the Thread class, itself.Create Thread by Implementing Runnable:The easiest way to create a thread is to create a class that implements the?Runnable?interface.To implement Runnable, a class need only implement a single method called?run( ), which is declared like this:public void run( )You will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can.After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:Thread (Runnable threadOb, String threadName);Here?threadOb?is an instance of a class that implements the Runnable interface and the name of the new thread is specified by?threadName.After the new thread is created, it will not start running until you call its?start( )?method, which is declared within Thread. The start( ) method is shown here:void start( );Example:Here is an example that creates a new thread and starts it running:class AThread implements Runnable{ String name; Thread th; AThread( String threadName){ name = threadName; th = new Thread(this, name); System.out.println("A Thread: " + th); th.start(); } public void run() // entry point for the thread { try{ for(int k = 3; k > 0; k--){ System.out.println(name + ":" + k); Thread.sleep(1000);} } catch(InterruptedException e){ System.out.println(name + "Interrupted"); } System.out.println(name + " exiting"); } }public class MThreadRunnable { public static void main(String[] args) { // create multiple threads new AThread("One"); // start threads new AThread("Two"); new AThread("Three"); try{ Thread.sleep(10000); // wait for others to end } catch(InterruptedException e){ System.out.println("Main thread Interrupted");} System.out.println("Main thread exiting"); } }What is Exception?An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:A user has entered invalid data.A file that needs to be opened cannot be found.A network connection has been lost in the middle of communications, or the JVM has run out of memory.Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.To understand how exception handling works in Java, you need to understand the three categories of exceptions:Checked exceptions:?A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.Runtime exceptions:?A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.Errors:?These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.Exception handling in Java:classTestException extends Exception {TestException() { super(); }TestException(String s) { super(s); }}class Test {public static void main(String[] args) {for (String arg :args) {try {thrower(arg);System.out.println("Test \"" + arg +"\" didn't throw an exception");} catch (Exception e) {System.out.println("Test \"" + arg +"\" threw a " + e.getClass() +"\n with message: " + e.getMessage()); } }}staticint thrower(String s) throws TestException {try {if (s.equals("divide")) {inti = 0;returni/i;}if (s.equals("null")) {s = null;returns.length();}if (s.equals("test"))throw new TestException("Test message");return 0;} finally {System.out.println("[thrower(\"" + s + "\") done]"); } }}Differences between html and dhtml:HTML1. It is referred as a static HTML and static in nature.?2. A plain page without any styles and Scripts called as HTML.?3. HTML sites will be slow upon client-side technologies.?4. Hypertext markup language: a set of tags and rules (conforming to SGML) for using them in developing hypertext documents.DHTML1.It is referred as a dynamic HTML and dynamic in nature.?2.A page with HTML, CSS, DOM and Scripts called as DHTML.?3.DHTML sites will be fast enough upon client-side technologies.4.Dynamic Hypertext Markup Language: is a collection of technologies used together to create interactive and animated web sites by using a combinationJava I/O package:Byte streams are defined by using two class hierarchies. At the top are two abstract classes:InputStream and OutputStream.Each of these abstract classes has several concrete subclasses that handle the differences between various devices, such as disk files, network connections, and even memory buffers. The byte stream classes are shown in Table 13-1. A few of these classes are discussed later in this section. Others are described in Part II. Remember, to use the stream classes, you must import java.io.The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two of the most important are read( ) and write( ), which, respectively, read and write bytes of data. Both methods are declared as abstract inside InputStream and OutputStream. They are overridden by derived stream classes.In Java, console input is accomplished by reading from System.in. To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object. BufferedReader supports a buffered input stream. Its most commonly used constructor is shown here:BufferedReader (Reader inputReader)Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor:InputStreamReader(InputStreaminputStream)Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard:BufferedReader br = new BufferedReader (new InputStreamReader (System.in));After this statement executes, br is a character-based stream that is linked to the console through System.in.Reading CharactersTo read a character from a BufferedReader, use read( ). The version of read( ) that we will be using is int read( ) throws IOException Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns –1 when the end of the stream is encountered. As you can see, it can throw an IOException.Console output is most easily accomplished with print( ) and println( ), described earlier, which are used in most of the examples in this book. These methods are defined by the class PrintStream (which is the type of object referenced by System.out). Even though System.out is a byte stream, using it for simple program output is still acceptable. However, a character-based alternative is described in the next section.Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method write( ). Thus, write( ) can be used to write to the console. The simplest form of write( ) defined by PrintStream is shown here:void write(int byteval)This method writes to the stream the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written. Here is a short example that uses write( ) to output the character “A” followed by a newline to the screen:// Demonstrate System.out.write().classWriteDemo {public static void main(String args[]) {int b;b = 'A';System.out.write(b);System.out.write('\n'); } }You will not often use write( ) to perform console output (although doing so might be useful in some situations), because print( ) and println( ) are substantially easier to use. I?have 2 examples for you; the first is reading from a text file, the second is writing to one.import java.io.*;class FileRead {? ? public static void main(String args[]) {? ? ? ? try{? ? ? ? ? ? // Open the file that is the first ? ? ? ? ? ? // command line parameter? ? ? ? ? ? FileInputStream fstream = new FileInputStream("textfile.txt");? ? ? ? ? ? // Get the object of DataInputStream? ? ? ? ? ? DataInputStream in = new DataInputStream(fstream);? ? ? ? ? ? BufferedReader br = new BufferedReader (new InputStreamReader(in));? ? ? ? ? ? String strLine;? ? ? ? ? ? //Read File Line By Line? ? ? ? ? ? while ((strLine = br.readLine()) != null) ? {? ? ? ? ? ? ? ?// Print the content on the console? ? ? ? ? ? ? ?System.out.println (strLine); }? ? ? ? ? ? //Close the input stream? ? ? ? ? ? in.close(); ??} catch (Exception e){//Catch exception if any? ? ? ? ? ? ?System.err.println("Error: " + e.getMessage()); ? ??} ? ? ?}?}import java.io.*;class FileWrite {? ? public static void main(Stringargs[]) {? ? ? ? Stringvar = "var";? ? ? ? try {? ? ? ? ? ? // Create file ? ? ? ? ? ? FileWriter fstream = new FileWriter("out.txt");? ? ? ? ? ? BufferedWriter out = new BufferedWriter(fstream);? ? ? ? ? ? out.write(var);? ? ? ? ? ? //Close the output stream? ? ? ? ? ? out.close(); } catch (Exception e){//Catch exception if any? ? ? ? ? ? System.err.println("Error: " + e.getMessage());? } ? ? }}What is java script?JavaScript was designed to add interactivity to HTML pages??JavaScript is a scripting language??A scripting language is a lightweight programming language??A JavaScript consists of lines of executable computer code??A JavaScript is usually embedded directly into HTML pages??JavaScript is an interpreted language (means that scripts execute without preliminary compilation)??Everyone can use JavaScript without purchasing a licenseHow to implement java script?The HTML <script> tag is used to insert a JavaScript into an HTML page.Examples Write text with JavascriptThe example demonstrates how to use JavaScript to write text on a web page.Write HTML with JavascriptThe example demonstrates how to use JavaScript to write HTML tags on a web page.How to Put a JavaScript into an HTML Page<html><body><script type="text/javascript">document.write("Hello World!");</script></body></html>Example:<html><head><title> MAX </title><script language="javascript">var a,b,c,n1,n2,n3,m1,m2,sum,avg;a=prompt("enter 1st no="," ");b=prompt("enter 2nd no="," ");c=prompt("enter 3rd no="," ");n1=parseInt(a);n2=parseInt(b);n3=parseInt(c);sum=n1+n2+n3;avg=sum/3;m1=Math.max(n1,n2);m2=Math.max(n3,m1);alert("the sum is= "+sum);alert("the avg is= "+m2);alert("the max no is "+m2);</script></head></html>JavaScript Validationfunction form1_validation() {var flag=0;var uname=document.f1.username.value;var rname=new RegExp("^[a-z A-Z]+\. ?[A-Z a-z]+$");if(!(rname.test(uname))) {alert("Enter valid name");flag=1; }if(f1.username.value.length<3) {alert("User Name must consist of atleast 3 characters");f1.username.focus();flag=1; }var pwd=document.f1.password.value;if(pwd.length<6) {alert("Enter valid password");flag=1; }var x=document.f1.email.value;var y=new RegExp("^[a-zA-Z0-9_]+@[a-z]+.com$");if(!(y.test(x))) {alert("Enter valid e-mail ID");flag=1; }var ph=document.f1.phno.value;var rph=new RegExp("^\\d{10}$");if(!(rph.test(ph))){alert("Enter valid Phone no.");flag=1;}//Validating DOBvar m=document.getElementById("mm");var d=document.getElementById("dd");var y=document.getElementById("yyyy");if(m.options[m.selectedIndex].text==4 || m.options[m.selectedIndex].text==6 || m.options[m.selectedIndex].text==9 || m.options[m.selectedIndex].text==11 )if(d.options[d.selectedIndex].text>30){alert("Invalid date");flag=1;}if(m.options[m.selectedIndex].text==2)if(d.options[d.selectedIndex].text>28){alert("Invalid date");flag=1;}if(flag==0)alert("Successfully Registered");}SAXDOMBoth SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation.Parses node by nodeStores the entire XML document into memory before processingSAX is an ad-hoc (but very popular) standardDOM is a W3C standardDoesn’t store the XML in memoryOccupies more memoryWe cant insert or delete a nodeWe can insert or delete nodesTop to bottom traversingTraverse in any direction.SAX is an event based parserDOM is a tree model parserSAX is a Simple API for XMLDocument Object Model (DOM) APISAX reads the document and calls handler methods for each element or block of text that it encountersDOM reads the entire document into memory and stores it as a tree data structureSAX provides only sequential access to the documentSAX is fast and requires very little memory, so it can be used for huge documentsThis makes SAX much more popular for web sitesDOM provides "random access" into the documentDOM is slow and requires huge amount of memory, so it cannot be used for large documentsimport javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.*;import javax.xml.parsers.*;import org.w3c.dom.*;doesn’t preserve commentspreserves commentsSAX generally runs a little faster than DOMSAX generally runs a little faster than DOMIf we need to find a node and doesn’t need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.Parsing with SAXSAX uses the source-listener-delegate model for parsing XML documentsSource is XML data consisting of a XML elementsA listener written in Java is attached to the document which listens for an eventWhen event is thrown, some method is delegated for handling the codeSAX works through callbacks: The program calls the parser The parser calls methods provided by the programSample SAXimport javax.xml.parsers.*; // for both SAX and DOMimport org.xml.sax.*;import org.xml.sax.helpers.*;// For simplicity, we let the operating system handle exceptions// In "real life" this is poor programming practicepublic class Sample { public static void main(String args[]) throws Exception { // Create a parser factory SAXParserFactory factory = SAXParserFactory.newInstance(); // Tell factory that the parser must understand namespaces factory.setNamespaceAware(true); // Make the parser SAXParser saxParser = factory.newSAXParser(); XMLReader parser = saxParser.getXMLReader// Create a handler Handler handler = new Handler(); // Tell the parser to use this handler parser.setContentHandler(handler); // Finally, read and parse the document parser.parse("hello.xml"); } // end of Sample classDOMDOM represents the XML document as a treeHierarchical nature of tree maps well to hierarchical nesting of XML elementsTree contains a global view of the documentMakes navigation of document easyAllows to modify any subtree Easier processing than SAX but memory intensive!As well as SAX, DOM is an API onlyDoes not specify a parserLists the API and requirements for the parserDOM parsers typically use SAX parsing Sample 1 DOM DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder(); //An XML file hello.xml will be be parsed <?xml version="1.0"?> <display>Hello World!</display> //To read this file, we add the following line : Document document = builder.parse("hello.xml"); //document contains the entire XML file as a tree //The following code finds the content of the root element and prints it Element root = document.getDocumentElement(); Node textNode = root.getFirstChild(); System.out.println(textNode.getNodeValue()); //The output of the program is: Hello World! Ex2 DOM:import javax.xml.parsers.*;import org.w3c.dom.Document;try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument();}catch (ParserConfigurationException e) { ... }XML filesStudent.xml<?xml version="1.0" ?><student xmlns:xsi="xmlschema-instance" xsi:SchemaLocation="student.xsd"><roll_no>08A01D2501</roll_no><name><first_name>A</first_name><Last_name>Aruna</Last_name></name><father_name><first_name>Venkateswara</first_name><Last_name>Rao</Last_name></father_name><branch>software engineering</branch><year>1ST Year</year><address><door-no>32-15/1-44</door-no><street>B.R.Nagar-1</street><city>Hyderabad</city></address><email>iaaruna@</email><phno>9949643372</phno><roll_no>08A01D2501</roll_no></student>Student.dtd:<!ELEMENT student(rollnum,name,parntname,branch,year,addr,email,phno)><!ELEMENTroll_no(#PCDATA)><!ELEMENT name(first_name,last_name)><!ELEMENTfirst_name(#PCDATA)><!ELEMENTlast_name(#PCDATA)><!ELEMENTfather_name(fname,mname,lname)><!ELEMENTfirst_name(#PCDATA)><!ELEMENTlast_name(#PCDATA)><!ELEMENT branch(#PCDATA)><!ELEMENT year(#PCDATA)><!ELEMENT address(door_no,street,city)><!ELEMENTdoor_no(#PCDATA)><!ELEMENT street(#PCDATA)><!ELEMENT city(#PCDATA)><!ELEMENT email(#PCDATA)><!ELEMENTphno(#PCDATA)>Student.xsd:<xs:schema><xs:element name="student"><xs:complextype><xs:sequence><xs:element name="roll_no" type="xs:string"/><xs:element name="name"><xs:complextype><xs:sequence><xs:element name="first_name" type="xs:string"/><xs:element name="last_name" type="xs:string"/></xs:sequence></xs:complextype></xs:element><xs:element name="father-name"><xs:complextype><xs:sequence><xs:element name="first_name" type="xs:string"/><xs:element name="last_name" type="xs:string"/></xs:sequence></xs:complextype></xs:element><xs:element name="branch" type="xs:string"/><xs:element name="year" type="xs:integer"/><xs:element name="addr"><xs:complextype><xs:sequence><xs:element name="door-no" type="xs:string"/><xs:element name="street" type="xs:string"/><xs:element name="city" type="xs:string"/></xs:sequence></xs:complextype></xs:element><xs:element name="email" type="xs:string"/><xs:element name="phno" type="xs:integer"/></xs:sequence></xs:complextype></xs:element></xs:schema>Cascading style sheets:Inline sheets:<html><head><title>CSS Inline style sheet</title></head><body><p style="color:sienna;margin-left:20px">This is a paragraph.</p></body></html>Internal stylesheets:<html><head><title>CSS Internal style sheet</title><style type="text/css">h1{color:sienna;}p{margin-left:20px;}body{background-image:url('F:\project\Blue_Stars_Glitter_Graphics.jpg');}</style></head><body><h1>this is h1 heading</h1><p>This is a paragraph.</p></body></html>External stylesheets:<html><head><title>CSS External style sheet</title><link rel="stylesheet" type="text/css" href="mystyle.css"/></head><body><h1>this is h1 heading</h1><p style="color:sienna;margin-left:20px">This is a paragraph.</p></body></html>mystyle.css containsH1{color:sienna;}p{margin-left:20px;}body {background-image:url("F:\project\Blue_Stars_Glitter_Graphics.jpg");} ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download