You are on page 1of 56

APPLET

Theory and concepts


A Java applet is an applet delivered to the users in the form of Java byte code. Java applets can run in a Web browser using a Java Virtual Machine (JVM), or in Sun's Applet Viewer, a stand-alone tool for testing applets. Java applets were introduced in the first version of the Java language in 1995. Applets are used to provide interactive features to web applications that cannot be provided by HTML alone. They can capture mouse input (like rotating 3D object) and also have controls like buttons or check boxes. In response to the user action an applet can change the provided graphic content. This makes applets well suitable for demonstration, visualization and teaching. There are online applet collections for studying various subjects, from differential equations[10] to heart physiology.[3] Applets are also used to create online game collections that allow players to compete against live opponents in real-time.

Advantages of Applet:

Applets are cross platform and can run on Windows, Mac OS and Linux platform Applets can work all the version of Java Plugin Applets runs in a sandbox, so the user does not need to trust the code, so it can work without security approval Applets are supported by most web browsers Applets are cached in most web browsers, so will be quick to load when returning to a web page User can also have full access to the machine if user allows

Disadvantages of Java Applet:


Java plug-in is required to run applet Java applet requires JVM so first time it takes significant startup time If applet is not already cached in the machine, it will be downloaded from internet and will take time Its difficult to design and build good user interface in applets compared to HTML technology

CODE:

/*APPLET*/
import java.awt.*; import java.applet.*; /* <applet code="Outer.class" width=200 height=200></applet> */ public class Outer extends Applet { TextField t; public void init() { t=new TextField(8); add(t); t.setText("0"); } public void paint(Graphics g) { int x=0,y=50,z=100; String s; g.drawString("Input a Number:",100,20); try { s=t.getText(); x=Integer.parseInt(s); } catch(Exception e){ } for(int i=1;i<=x;i++) { for(int j=1;j<=x;j++) { if(i%2!=0) { if(j%2!=0) g.drawOval(y,z,20,20); else g.fillOval(y,z,20,20); } else { if(j%2==0) g.drawOval(y,z,20,20); else

g.fillOval(y,z,20,20); } z+=30; } y+=30; z=100; } } public boolean action(Event e,Object o) { repaint(); return true; } }

LAYOUTS Theory and concepts


ABSTRACT WINDOWING TOOLKIT
In Java AWT (Abstract Windowing Toolkit) there are three things are very important, these are: Components. Containers. Layout Managers.

Let us understand the relation between these three components. Java components get their look and feel from the underlying hardware where the Java Virtual Machine (JVM) is running. This is called getting the look and feel from the PEER CLASSES.

LAYOUT MANAGERS:
Layout Manager BorderLayout CardLayout FlowLayout GridLayout GridBagLayout Implementing Interface LayoutManager2 LayoutManager2 LayoutManager LayoutManager LayoutManager2

Default Layout Managers:

Container Applet Frame Panel Dialog

Layout Manager FlowLayout BorderLayout FlowLayout BorderLayout

a) FLOW LAYOUT
FLOWLAYOUT MANAGER The FlowLayout manager arrange components in its container horizontally left to right and top to bottom starting from center by default. If you try to add more components in a single row then the row splits into second row. Justification - FlowLayout.LEFT, FlowLayout.CENTER or FlowLayout.RIGHT. Default is FlowLayout.CENTER. The components added to a container using FlowLayout manager, even if you resize the window, component does not change it's original size. FlowLayout honors the preferred size of the component.

Example 1:public class TestFlow extends Frame { public static void main(String args[]) { Panel p = new Panel(); Button b = new Button("NORTH"); Button b1 = new Button("SOUTH"); Button b2 = new Button("CENTER"); TestFlow t = new TestFlow(); t.setSize(150,150); t.setVisible(true); t.add(p); p.add(b); p.add(b1); p.add(b2); }}

Output:

If you resize the window to smaller size then the top row splits into second row but the the size of the component does not change, which means Flow Layout manager honors the component preferred size.

b) BORDER LAYOUT

BORDERLAYOUT MANAGER
The BorderLayout manager is a default layout manager for frames. This layout manager divides container in to five regions where you can place components, called "North", "South", "East", "West", and "Center". The center region occupies leftover space if you did not place any component in other regions.

Example 1:import java.awt.*; public class TestBorder extends Frame { public static void main(String args[]) { Button b = new Button("Hello"); TestBorder t = new TestBorder(); t.setSize(150,150); t.setVisible(true); t.add(b); } }

Output:

If you don't specify the location of the component, then the center is the default location of the component in the BorderLayout, and component occupies all the leftover space. While adding a component you can use "North", "South" , "East", "West", "Center" or the following constants to specify the location of the component. You can also specify mixing of both.

Example 2:import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class BorderLayoutDemo { public static boolean RIGHT_TO_LEFT = false; public static void addComponentsToPane(Container contentPane) { // Use BorderLayout. Default empty constructor with no horizontal and vertical // gaps contentPane.setLayout(new BorderLayout(5,5)); if (!(contentPane.getLayout() instanceof BorderLayout)) { contentPane.add(new JLabel("Container doesn't use BorderLayout!")); return; } if (RIGHT_TO_LEFT) { contentPane.setComponentOrientation( java.awt.ComponentOrientation.RIGHT_TO_LEFT); } JButton jbnSampleButtons = new JButton("Button 1 (PAGE_START)"); contentPane.add(jbnSampleButtons, BorderLayout.PAGE_START); jbnSampleButtons = new JButton("Button 2 (CENTER)"); jbnSampleButtons.setPreferredSize(new Dimension(200, 100)); contentPane.add(jbnSampleButtons, BorderLayout.CENTER); jbnSampleButtons = new JButton("Button 3 (LINE_START)"); contentPane.add(jbnSampleButtons, BorderLayout.LINE_START); jbnSampleButtons = new JButton("Long-Named Button 4 (PAGE_END)"); contentPane.add(jbnSampleButtons, BorderLayout.PAGE_END); jbnSampleButtons = new JButton("5 (LINE_END)"); contentPane.add(jbnSampleButtons, BorderLayout.LINE_END); } private static void createAndShowGUI() {

JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("BorderLayout Source Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane and add swing components to it addComponentsToPane(frame.getContentPane()); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }

Output:-

c)

GRID LAYOUT

GRIDLAYOUT MANAGER
The GridLayout manager divides the space in the container in to ROWS AND COLUMNS specified in the constructor. Basically it divides the region into number of rows and columns which you specified while setting the layout manager for the container.

Example 1:public class TestGrid extends Frame { public static void main(String args[]) { Panel p = new Panel(); Button b1 = new Button("Button1"); Button b2 = new Button("Button2"); Button b3 = new Button("Button3"); Button b4 = new Button("Button4"); TestGrid t = new TestGrid(); t.setSize(150,150); t.setVisible(true); t.add(p); p.setLayout(new GridLayout(2,2)); p.add(b1 ); p.add(b2); p.add(b3); p.add(b4); } }

Output:

If you use GridLayout manager and when you resize the window all the components in the container also resized.

Example 2:import java.awt.*; import javax.swing.*; public class GridLayoutDemo { public final static boolean RIGHT_TO_LEFT = false; public static void addComponentsToPane(Container contentPane) { if (RIGHT_TO_LEFT) { contentPane.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT); } // Any number of rows and 2 columns contentPane.setLayout(new GridLayout(0,2)); contentPane.add(new JLabel("JLabel 1")); contentPane.add(new JButton("JButton 2")); contentPane.add(new JCheckBox("JCheckBox 3")); contentPane.add(new JTextField("Long-Named JTextField 4")); contentPane.add(new JButton("JButton 5")); } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("GridLayout Source Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane and components in GridLayout addComponentsToPane(frame.getContentPane()); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }

Output

d)

GRIDBAG LAYOUT

GRIDBAGLAYOUT MANAGER
GridBagLayout determines the number of rows and columns from the constraints placed upon the components it lays out. It does not require providing the rows and columns as in the GridLayout. It allows spanning the components to more than one grid cell.

Example 2:import java.awt.*; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JTextField; public class GridBagLayoutDemo { public static void addComponentsToPane(Container pane) { JButton jbnButton; pane.setLayout(new GridBagLayout()); GridBagConstraints gBC = new GridBagConstraints(); gBC.fill = GridBagConstraints.HORIZONTAL;

jbnButton = new JButton("Button 1"); gBC.weightx = 0.5; gBC.gridx = 0; gBC.gridy = 0; pane.add(jbnButton, gBC); JTextField jtf = new JTextField("TextField 1"); gBC.gridx = 2; gBC.gridy = 0; jtf.setEditable(false); pane.add(jtf, gBC); jbnButton = new JButton("Button 3"); gBC.gridx = 2; gBC.gridy = 0; pane.add(jbnButton, gBC); jbnButton = new JButton("Button 4"); gBC.ipady = 40; //This component has more breadth compared to other buttons gBC.weightx = 0.0; gBC.gridwidth = 3; gBC.gridx = 0; gBC.gridy = 1; pane.add(jbnButton, gBC);

JComboBox jcmbSample = new JComboBox(new String[]{"ComboBox 1", "hi", "hello"}); gBC.ipady = 0; gBC.weighty = 1.0; gBC.anchor = GridBagConstraints.PAGE_END; gBC.insets = new Insets(10,0,0,0); //Padding gBC.gridx = 1; gBC.gridwidth = 2; gBC.gridy = 2; pane.add(jcmbSample, gBC); } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("GridBagLayout Source Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane. addComponentsToPane(frame.getContentPane()); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }

Output

After Expanding the Frame

AWT CONTROLS
Theory and concepts

a) SCROLL BAR
Scroll bars are used to select continuous values between a specified minimum and maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is actually a composite of several individual parts. Each end has an arrow that you can click to move the current value of the scroll bar one unit in the direction of the arrow. The current value of the scroll bar relative to its minimum and maximum values is indicated by the slider box (or thumb) for the scroll bar. The slider box can be dragged by the user to a new position. The scroll bar will then reflect this value. In the background space on either side of the thumb, the user can click to cause the thumb to jump in that direction by some increment larger than 1. Typically, this action translates into some form of page up and page down. Scroll bars are encapsulated by the Scrollbar class. Scrollbar defines the following constructors: Scrollbar( ) Scrollbar(int style) Scrollbar(int style, int initialValue, int thumbSize, int min, int max) Handling Scroll Bars To process scroll bar events, you need to implement the AdjustmentListener interface. Each time a user interacts with a scroll bar, an AdjustmentEvent object is generated. Its getAdjustmentType( ) method can be used to determine the type of the adjustment. The types of adjustment events are as follows: BLOCK_DECREMENT A page-down event has been generated. BLOCK_INCREMENT A page-up event has been generated. TRACK An absolute tracking event has been generated. UNIT_DECREMENT The line-down button in a scroll bar has been pressed. UNIT_INCREMENT The line-up button in a scroll bar has been pressed. The following example creates both a vertical and a horizontal scroll bar. The current settings of the scroll bars are displayed. If you drag the mouse while inside the window, the coordinates of each drag event are used to update the scroll bars. An asterisk is

displayed at the current drag position.

// Demonstrate scroll bars. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="SBDemo" width=300 height=200> </applet> */ public class SBDemo extends Applet implements AdjustmentListener, MouseMotionListener { String msg = ""; Scrollbar vertSB, horzSB; public void init() { int width = Integer.parseInt(getParameter("width")); int height = Integer.parseInt(getParameter("height")); vertSB = new Scrollbar(Scrollbar.VERTICAL,0, 1, 0, height); horzSB = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, width); add(vertSB); add(horzSB); // register to receive adjustment events vertSB.addAdjustmentListener(this); horzSB.addAdjustmentListener(this); addMouseMotionListener(this); } public void adjustmentValueChanged(AdjustmentEvent ae) { repaint(); } // Update scroll bars to reflect mouse dragging. public void mouseDragged(MouseEvent me) { int x = me.getX(); int y = me.getY(); vertSB.setValue(y); horzSB.setValue(x); repaint(); } // Necessary for MouseMotionListener public void mouseMoved(MouseEvent me) { } // Display current value of scroll bars.

public void paint(Graphics g) { msg = "Vertical: " + vertSB.getValue(); msg += ", Horizontal: " + horzSB.getValue(); g.drawString(msg, 6, 160); // show current mouse drag position g.drawString("*", horzSB.getValue(), vertSB.getValue()); } }

OUTPUT:-

b) Choice Controls
Theory and concepts
The Choice class is used to create a pop-up list of items from which the user may choose. Thus, a Choice control is a form of menu. When inactive, a Choice component takes up only enough space to show the currently selected item. When the user clicks on it, the whole list of choices pops up, and a new selection can be made. Each item in the list is a string that appears as a left-justified label in the order it is added to the Choice object. Choice only defines the default constructor, which creates an empty list. To add a selection to the list, call addItem( ) or add( ). They have these general forms: void addItem(String name) void add(String name) Handling Choice Lists Each time a choice is selected, an item event is generated. This is sent to any listeners that previously registered an interest in receiving item event notifications from that component. Each listener implements the ItemListener interface. That interface defines the itemStateChanged( ) method. An ItemEvent object is supplied as the argument to this method. Here is an example that creates two Choice menus. One selects the operating system. The other selects the browser.

// Demonstrate Choice lists. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="ChoiceDemo" width=300 height=180> </applet> */ public class ChoiceDemo extends Applet implements ItemListener { Choice os, browser; String msg = ""; public void init() { os = new Choice(); browser = new Choice(); // add items to os list os.add("Windows 98"); os.add("Windows NT"); os.add("Solaris"); os.add("MacOS"); // add items to browser list browser.add("Netscape 1.1"); browser.add("Netscape 2.x"); browser.add("Netscape 3.x"); browser.add("Netscape 4.x"); browser.add("Internet Explorer 2.0"); browser.add("Internet Explorer 3.0"); browser.add("Internet Explorer 4.0"); browser.add("Lynx 2.4"); browser.select("Netscape 4.x"); // add choice lists to window add(os); add(browser); // register to receive item events os.addItemListener(this); browser.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint();

} // Display current selections. public void paint(Graphics g) { msg = "Current OS: "; msg += os.getSelectedItem(); g.drawString(msg, 6, 120); msg = "Current Browser: "; msg += browser.getSelectedItem(); g.drawString(msg, 6, 140); } }

OUTPUT:-

c) List Controls
Theory and concepts
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the Choice object, which shows only the single selected item in the menu, a List object can be constructed to show any number of choices in the visible window. It can also be created to allow multiple selections. List provides these constructors: List( ) List(int numRows) List(int numRows, boolean multipleSelect) Handling Lists To process list events, you will need to implement the ActionListener interface. Each time a List item is double-clicked, an ActionEvent object is generated. Its getActionCommand( ) method can be used to retrieve the name of the newly selected item. Also, each time an item is selected or deselected with a single click, an ItemEvent object is generated. Its getStateChange( ) method can be used to determine whether a selection or deselection triggered this event. getItemSelectable( ) returns a reference to the object that triggered this event. Here is an example that converts the Choice controls in the preceding section into List components, one multiple choice and the other single choice:

// Demonstrate Lists. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="ListDemo" width=300 height=180> </applet> */ public class ListDemo extends Applet implements ActionListener { List os, browser; String msg = ""; public void init() { os = new List(4, true); browser = new List(4, false); // add items to os list os.add("Windows 98"); os.add("Windows NT"); os.add("Solaris"); os.add("MacOS"); // add items to browser list browser.add("Netscape 1.1"); browser.add("Netscape 2.x"); browser.add("Netscape 3.x"); browser.add("Netscape 4.x"); browser.add("Internet Explorer 2.0"); browser.add("Internet Explorer 3.0"); browser.add("Internet Explorer 4.0"); browser.add("Lynx 2.4"); browser.select(1); // add lists to window add(os); add(browser); // register to receive action events os.addActionListener(this); browser.addActionListener(this); } public void actionPerformed(ActionEvent ae) { repaint();

} // Display current selections. public void paint(Graphics g) { int idx[]; msg = "Current OS: "; idx = os.getSelectedIndexes(); for(int i=0; i<idx.length; i++) msg += os.getItem(idx[i]) + " "; g.drawString(msg, 6, 120); msg = "Current Browser: "; msg += browser.getSelectedItem(); g.drawString(msg, 6, 140); } }

OUTPUT:-

d) Check box Controls


Theory and concepts
A check box is a control that is used to turn an option on or off. It consists of a small box that can either contain a check mark or not. There is a label associated with each check box that describes what option the box represents. You change the state of a check box by clicking on it. Check boxes can be used individually or as part of a group. Check boxes are objects of the Checkbox class. Checkbox supports these constructors: Checkbox( ) Checkbox(String str) Checkbox(String str, boolean on) Checkbox(String str, boolean on, CheckboxGroup cbGroup) Checkbox(String str, CheckboxGroup cbGroup, boolean on)

Handling Check Boxes


Each time a check box is selected or deselected, an item event is generated. This is sent to any listeners that previously registered an interest in receiving item event notifications from that component. Each listener implements the ItemListener interface. That interface defines the itemStateChanged( ) method. An ItemEvent object is supplied as the argument to this method. It contains information about the event (for example, whether it was a selection or deselection). The following program creates four check boxes. The initial state of the first box is checked. The status of each check box is displayed. Each time you change the state of a check box, the status display is updated.

// Demonstrate check boxes. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="CheckboxDemo" width=250 height=200> </applet> */ public class CheckboxDemo extends Applet implements ItemListener { String msg = ""; Checkbox Win98, winNT, solaris, mac; public void init() { Win98 = new Checkbox("Windows 98", null, true); winNT = new Checkbox("Windows NT"); solaris = new Checkbox("Solaris"); mac = new Checkbox("MacOS"); add(Win98); add(winNT); add(solaris); add(mac); Win98.addItemListener(this); winNT.addItemListener(this); solaris.addItemListener(this); mac.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } // Display current state of the check boxes. public void paint(Graphics g) { msg = "Current state: "; g.drawString(msg, 6, 80); msg = " Windows 98: " + Win98.getState(); g.drawString(msg, 6, 100); msg = " Windows NT: " + winNT.getState(); g.drawString(msg, 6, 120); msg = " Solaris: " + solaris.getState(); g.drawString(msg, 6, 140); msg = " MacOS: " + mac.getState(); g.drawString(msg, 6, 160); } }

Output:-

SWINGS
Theory and concepts
Java Swing is a GUI toolkit for Java. Swing is one part of the Java Foundation Classes (JFC). Swing includes graphical user interface (GUI) widgets such as text boxes, buttons, split-panes, and tables. Swing widgets provide more sophisticated GUI components than the earlier Abstract Window Toolkit. Since they are written in pure Java, they run the same on all platforms, unlike the AWT which is tied to the underlying platform's windowing system. Swing supports pluggable look and feel not by using the native platform's facilities, but by roughly emulating (imitate) them. This means you can get any supported look and feel on any platform. The disadvantage of lightweight components is possibly slower execution. The advantage is uniform behavior on all platforms.

The following section explains the various JComponents available in swing package,

JPanel is Swing's version of the AWT class Panel and uses the same default layout, FlowLayout. JPanel is descended directly from JComponent. JFrame is Swing's version of Frame and is descended directly from that class. The components added to the frame are referred to as its contents; these are managed by the contentPane. To add a component to a JFrame, we must use its contentPane instead. JInternalFrame is confined to a visible area of a container it is placed in. It can be iconified , maximized and layered. JWindow is Swing's version of Window and is descended directly from that class. Like Window, it uses BorderLayout by default. JDialog is Swing's version of Dialog and is descended directly from that class. Like Dialog, it uses BorderLayout by default. Like JFrame and JWindow, JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass panes. All dialogs are modal, which means the current thread is blocked until user interaction with it has been completed. JDialog class is intended as the basis for creating custom dialogs; however, some of the most common dialogs are provided through static methods in the class JOptionPane. JLabel, descended from JComponent, is used to create text labels.

The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes, including JButton.

JTextField allows editing of a single line of text. New features include the ability to justify the text left, right, or center, and to set the text's font. JPasswordField (a direct subclass of JTextField) you can suppress the display of input. Each character entered can be replaced by an echo character. This allows confidential input for passwords, for example. By default, the echo character is the asterisk, *. JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to always or never have either the vertical or horizontal scrollbar; JButton is a component the user clicks to trigger a specific action. JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of radio buttons can be associated as a group in which only one button at a time can be selected. JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected, and it also displays its current state. JComboBox is like a drop down box. You can click a drop-down arrow and select an option from a list. For example, when the component has focus, pressing a key that corresponds to the first character in some entry's name selects that entry. A vertical scrollbar is used for longer lists. JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly, instead, the list must be associated with a scrollpane. The view port used by the scroll pane can also have a user-defined border. JList actions are handled using ListSelectionListener. JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image. JToolbar contains a number of components whose type is usually some kind of button which can also include separators to group related components within the toolbar. FlowLayout when used arranges swing components from left to right until there's no more space available. Then it begins a new row below it and moves from left to right again. Each component in a FlowLayout gets as much space as it needs and no more. BorderLayout places swing components in the North, South, East, West and center of a container. You can add horizontal and vertical gaps between the areas. GridLayout is a layout manager that lays out a container's components in a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in each rectangle.

GridBagLayout is a layout manager that lays out a container's components in a grid of cells with each component occupying one or more cells, called its display area. The display area aligns components vertically and horizontally, without requiring that the components be of the same size.

JMenubar can contain several JMenu's. Each of the JMenu's can contain a series of JMenuItem 's that you can select. Swing provides support for pull-down and popup menus. Scrollable JPopupMenu is a scrollable popup menu that can be used whenever we have so many items in a popup menu that exceeds the screen visible height.

EXAMPLE 2:
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class MasterFrame extends JFrame implements ActionListener{ JLabel l1,l2,l3,l4; JTextField t1,t2,t3,t4; JButton save; MasterFrame() { super("MasterFrame"); // build a panel with labels just to fill the GUI JPanel panel = new JPanel(new GridLayout(5, 2)); l1= new JLabel("Name"); panel.add(l1); t1= new JTextField(); panel.add(t1); l2= new JLabel("Address"); panel.add(l2); t2= new JTextField(); panel.add(t2); l3= new JLabel("City"); panel.add(l3); t3= new JTextField(); panel.add(t3); l4= new JLabel("Mobile No"); panel.add(l4); t4= new JTextField(); panel.add(t4); save = new JButton("Save"); panel.add(save); save.addActionListener(this); add(panel); setSize(500, 400); // create and show the Login form new Login(this); }

public void actionPerformed(ActionEvent e) { if(e.getSource()==save) { JOptionPane.showMessageDialog(this, "Data Updated"); } } // to test the whole thing public static void main(String[] args) { new MasterFrame(); } }

OUTPUT:-

DATAGRAM SOCKETS AND POCKETS


Theory and concepts TCP:TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data between two computers. When two applications want to communicate to each other reliably, they establish a connection and send data back and forth over that connection. This is analogous to making a telephone. CP provides a pointto-point channel for applications that require reliable communications. The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel. The order in which the data is sent and received over the network is critical to the success of these applications. When HTTP is used to read from a URL, the data must be received in the order in which it was sent. Otherwise, you end up with a jumbled HTML file, a corrupt zip file, or some other invalid information.

UDP:UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP. The UDP protocol provides for communication that is not guaranteed between two applications on the network. UDP is not connection-based like TCP. Rather, it sends independent packets of data, called datagrams, from one application to another. Sending datagrams is much like sending a letter through the postal service: The order of delivery is not important and is not guaranteed, and each message is independent of any other.

Port:In the context of TCP/IP, UDP or ICMP network communications it refers to a socket number to allow multiple channels to be operating independently between two computers

Socket:Provides a connection-oriented protocol that behaves like telnet or ftp. The connection remains active, even with no communications occurring, until explicitly broken.

Code for Server:

/* UDP Networking */
import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[100]; byte[] sendData = new byte[100] String Sentence=""; do{Sentence=""; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData()); System.out.println("From Client: " + sentence); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); System.out.println("Enter your message here: "); BufferedReader FromUser = new BufferedReader(new InputStreamReader(System.in)); Sentence = FromUser.readLine(); sendData = Sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); }while(!Sentence.equals("bye")); serverSocket.close(); } }

Code for Client


import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] sendData = new byte[100]; byte[] receiveData = new byte[100]; String sentence =""; System.out.println("Chat Client Started"); do{ sentence=""; System.out.println("Enter your message here: "); BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); sentence = inFromUser.readLine(); sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); } while(!sentence.equals("bye")); clientSocket.close(); } }

Output:Chat Server Started Client Sent : hi Enter your message here: hi Client Sent : hi dude Enter your message here: How r u? Client Sent: yup fine. Enter your message here: Ok.

Chat Server Started Enter your message here: Hi Server Sent: hi Enter your message here: Hi dude Server Sent: How r u? Enter your message: Ya fine

JDBC
Theory and concepts JDBC
Call-level interfaces such as JDBC are programming interfaces allowing external access to SQL database manipulation and update commands. They allow the integration of SQL calls into a general programming environment by providing library routines which interface with the database. In particular, Java based JDBC has a rich collection of routines which make such an interface extremely simple and intuitive. what happens in a call level interface: You are writing a normal Java program. Somewhere in the program, you need to interact with a database. Using standard library routines, you open a connection to the database. You then use JDBC to send your SQL code to the database, and process the results that are returned. When you are done, you close the connection.

Example:To run this example, you need a database with the following properties: => no username => no password => a table called "Cust" => a system DSN called "Database"

import java.sql.* ; class JDBCQuery { public static void main( String args[] ) { try { // Load the database driver Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ) ; // Get a connection to the database Connection conn = DriverManager.getConnection( "jdbc:odbc:Database" ) ; // Print all warnings for( SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning() ) { System.out.println( "SQL Warning:" ) ; System.out.println( "State : " + warn.getSQLState() ) ; System.out.println( "Message: " + warn.getMessage() ) ; System.out.println( "Error : " + warn.getErrorCode() ) ; } // Get a statement from the connection Statement stmt = conn.createStatement() ; // Execute the query ResultSet rs = stmt.executeQuery( "SELECT * FROM Cust" ) ; // Loop through the result set while( rs.next() ) System.out.println( rs.getString(1) ) ; // Close the result set, statement and the connection rs.close() ; stmt.close() ; conn.close() ; } catch( SQLException se ) { System.out.println( "SQL Exception:" ) ; // Loop through the SQL Exceptions

while( se != null ) { System.out.println( "State : " + se.getSQLState() ) ; System.out.println( "Message: " + se.getMessage() ) ; System.out.println( "Error : " + se.getErrorCode() ) ; se = se.getNextException() ; } } catch( Exception e ) { System.out.println( e ) ; } } }

REMOTE METHOD INVOCATION


Theory and concepts
Remote Method Invocation (RMI) Remote Method Invocation (RMI) is the object equivalent of Remote Procedure Calls (RPC). While RPC allows you to call procedures over a network, RMI invokes an object's methods over a network. In the RMI model, the server defines objects that the client can use remotely. The clients can now invoke methods of this remote object as if it were a local object running in the same virtual machine as the client. RMI hides the underlying mechanism of transporting method arguments and return values across the network. In Java-RMI, an argument or return value can be of any primitive Java type or any other Serializable Java object.

CODE:AllServerIntf.java import java.rmi.*; public interface AllServerIntf extends Remote { double si(double d1,double d2,double d3) throws RemoteException; }

AllServerImpl.java import java.rmi.*; import java.rmi.server.*; public class AllServerImpl extends UnicastRemoteObject implements AllServerIntf { public AllServerImpl() throws RemoteException { } public double si(double d1,double d2,double d3) throws RemoteException { return (d1*d2*d3)/100; } }

AllServer.java import java.rmi.*; import java.net.*; public class AllServer { public static void main(String args[]) { try {

AllServerImpl allserverimpl = new AllServerImpl(); Naming.rebind("AllServer", allserverimpl); } catch(Exception e) { System.out.println("Exception : " +e); } } }

AllClient.java import java.rmi.*; import java.io.*; public class AllClient { public static void main(String args[]) { DataInputStream j=new DataInputStream(System.in); try { String allserverURL = "rmi://" + args[0] + "/AllServer"; AllServerIntf allserverintf =(AllServerIntf)Naming.lookup(allserverURL); System.out.print(" Enter the principle amount is :"); double d1 = Double.valueOf(j.readLine()); System.out.print(" Enter the number of years is :"); double d2 = Double.valueOf(j.readLine()); System.out.print(" Enter the rate of interest per annum is :"); double d3 = Double.valueOf(j.readLine()); System.out.println("The simple interest amount is : " +allserverintf.si(d1,d2,d3)); }

catch(Exception e) { System.out.println("Exception : "+e); } } }

OUTPUT: RMI REGISTRY:

SERVER SIDE:

CLIENT SIDE:

You might also like