Java awt tutorial



Yüklə 349,37 Kb.
tarix07.11.2018
ölçüsü349,37 Kb.
#78517

Java AWT Tutorial

Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application in java.

Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavyweight i.e. its components uses the resources of system.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

hierarchy of awt

Container

The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.

Window


The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window.

Panel


The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc.

Frame


The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield etc.

Useful Methods of Component class



Method

Description

public void add(Component c)

inserts a component on this component.

public void setSize(int width,int height)

sets the size (width and height) of the component.

public void setLayout(LayoutManager m)

defines the layout manager for the component.

public void setVisible(boolean status)

changes the visibility of the component, by default false.

Java AWT Example

To create simple awt example, you need a frame. There are two ways to create a frame in AWT.



  • By extending Frame class (inheritance)

  • By creating the object of Frame class (association)

Simple example of AWT by inheritance

  1. import java.awt.*;  

  2. class First extends Frame{  

  3. First(){  

  4. Button b=new Button("click me");  

  5. b.setBounds(30,100,80,30);// setting button position  

  6.   

  7. add(b);//adding button into frame  

  8. setSize(300,300);//frame size 300 width and 300 height  

  9. setLayout(null);//no layout manager  

  10. setVisible(true);//now frame will be visible, by default not visible  

  11. }  

  12. public static void main(String args[]){  

  13. First f=new First();  

  14. }}  

download this example

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that sets the position of the awt button.



awt example

Simple example of AWT by association



  1. import java.awt.*;  

  2. class First2{  

  3. First2(){  

  4. Frame f=new Frame();  

  5.   

  6. Button b=new Button("click me");  

  7. b.setBounds(30,50,80,30);  

  8.   

  9. f.add(b);  

  10. f.setSize(300,300);  

  11. f.setLayout(null);  

  12. f.setVisible(true);  

  13. }  

  14. public static void main(String args[]){  

  15. First2 f=new First2();  

  16. }}  

Event and Listener (Java Event Handling)

Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.

Event classes and Listener interfaces:

Event Classes

Listener Interfaces

ActionEvent

ActionListener

MouseEvent

MouseListener and MouseMotionListener

MouseWheelEvent

MouseWheelListener

KeyEvent

KeyListener

ItemEvent

ItemListener

TextEvent

TextListener

AdjustmentEvent

AdjustmentListener

WindowEvent

WindowListener

ComponentEvent

ComponentListener

ContainerEvent

ContainerListener

FocusEvent

FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:



  1. Implement the Listener interface and overrides its methods

  2. Register the component with the Listener

For registering the component with the Listener, many classes provide the registration methods. For example:

  • Button

    • public void addActionListener(ActionListener a){}

  • MenuItem

    • public void addActionListener(ActionListener a){}

  • TextField

    • public void addActionListener(ActionListener a){}

    • public void addTextListener(TextListener a){}

  • TextArea

    • public void addTextListener(TextListener a){}

  • Checkbox

    • public void addItemListener(ItemListener a){}

  • Choice

    • public void addItemListener(ItemListener a){}

  • List

    • public void addActionListener(ActionListener a){}

    • public void addItemListener(ItemListener a){}

EventHandling Codes:

We can put the event handling code into one of the following places:

  1. Same class

  2. Other class

  3. Annonymous class

Example of event handling within class:

  1. import java.awt.*;  

  2. import java.awt.event.*;  

  3.   

  4. class AEvent extends Frame implements ActionListener{  

  5. TextField tf;  

  6. AEvent(){  

  7.   

  8. tf=new TextField();  

  9. tf.setBounds(60,50,170,20);  

  10.   

  11. Button b=new Button("click me");  

  12. b.setBounds(100,120,80,30);  

  13.   

  14. b.addActionListener(this);  

  15.   

  16. add(b);add(tf);  

  17.   

  18. setSize(300,300);  

  19. setLayout(null);  

  20. setVisible(true);  

  21.   

  22. }  

  23.   

  24. public void actionPerformed(ActionEvent e){  

  25. tf.setText("Welcome");  

  26. }  

  27.   

  28. public static void main(String args[]){  

  29. new AEvent();  

  30. }  

  31. }  

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets the position of the component it may be button, textfield etc.

event handling in java

2) Example of event handling by Outer class:



  1. import java.awt.*;  

  2. import java.awt.event.*;  

  3. class AEvent2 extends Frame{  

  4. TextField tf;  

  5. AEvent2(){  

  6.   

  7. tf=new TextField();  

  8. tf.setBounds(60,50,170,20);  

  9.   

  10. Button b=new Button("click me");  

  11. b.setBounds(100,120,80,30);  

  12.   

  13. Outer o=new Outer(this);  

  14. b.addActionListener(o);//passing outer class instance  

  15.   

  16. add(b);add(tf);  

  17.   

  18. setSize(300,300);  

  19. setLayout(null);  

  20. setVisible(true);  

  21. }  

  22. public static void main(String args[]){  

  23. new AEvent2();  

  24. }  

  25. }  

  1. import java.awt.event.*;  

  2. class Outer implements ActionListener{  

  3. AEvent2 obj;  

  4. Outer(AEvent2 obj){  

  5. this.obj=obj;  

  6. }  

  7. public void actionPerformed(ActionEvent e){  

  8. obj.tf.setText("welcome");  

  9. }  

  10. }  

3) Example of event handling by Annonymous class:

  1. import java.awt.*;  

  2. import java.awt.event.*;  

  3. class AEvent3 extends Frame{  

  4. TextField tf;  

  5. AEvent3(){  

  6. tf=new TextField();  

  7. tf.setBounds(60,50,170,20);  

  8. Button b=new Button("click me");  

  9. b.setBounds(50,120,80,30);  

  10.   

  11. b.addActionListener(new ActionListener(){  

  12. public void actionPerformed(){  

  13. tf.setText("hello");  

  14. }  

  15. });  

  16. add(b);add(tf);  

  17. setSize(300,300);  

  18. setLayout(null);  

  19. setVisible(true);  

  20. }  

  21. public static void main(String args[]){  

  22. new AEvent3();  

  23. }  

  24. }  

Java Swing Tutorial

Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.


No.

Java AWT

Java Swing

1)

AWT components are platform-dependent.

Java swing components are platform-independent.

2)

AWT components are heavyweight.

Swing components are lightweight.

3)

AWT doesn't support pluggable look and feel.

Swing supports pluggable look and feel.

4)

AWT provides less components than Swing.

Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser, tabbedpane etc.

5)

AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view.

Swing follows MVC.

What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.



hierarchy of javax swing

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.


Method

Description

public void add(Component c)

add a component on another component.

public void setSize(int width,int height)

sets size of the component.

public void setLayout(LayoutManager m)

sets the layout manager for the component.

public void setVisible(boolean b)

sets the visibility of the component. It is by default false.

Java Swing Examples

There are two ways to create a frame:



  • By creating the object of Frame class (association)

  • By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example

Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside the main() method.

File: FirstSwingExample.java


  1. import javax.swing.*;  

  2. public class FirstSwingExample {  

  3. public static void main(String[] args) {  

  4. JFrame f=new JFrame();//creating instance of JFrame  

  5.           

  6. JButton b=new JButton("click");//creating instance of JButton  

  7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height  

  8.           

  9. f.add(b);//adding button in JFrame  

  10.           

  11. f.setSize(400,500);//400 width and 500 height  

  12. f.setLayout(null);//using no layout managers  

  13. f.setVisible(true);//making the frame visible  

  14. }  

  15. }  

simple example of java swing

Example of Swing by Association inside constructor

We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.

File: Simple.java


  1. import javax.swing.*;  

  2. public class Simple {  

  3. JFrame f;  

  4. Simple(){  

  5. f=new JFrame();//creating instance of JFrame  

  6.           

  7. JButton b=new JButton("click");//creating instance of JButton  

  8. b.setBounds(130,100,100, 40);  

  9.           

  10. f.add(b);//adding button in JFrame  

  11.           

  12. f.setSize(400,500);//400 width and 500 height  

  13. f.setLayout(null);//using no layout managers  

  14. f.setVisible(true);//making the frame visible  

  15. }  

  16.   

  17. public static void main(String[] args) {  

  18. new Simple();  

  19. }  

  20. }  

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the position of the button.

Simple example of Swing by inheritance

We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.

File: Simple2.java


  1. import javax.swing.*;  

  2. public class Simple2 extends JFrame{//inheriting JFrame  

  3. JFrame f;  

  4. Simple2(){  

  5. JButton b=new JButton("click");//create button  

  6. b.setBounds(130,100,100, 40);  

  7.           

  8. add(b);//adding button on frame  

  9. setSize(400,500);  

  10. setLayout(null);  

  11. setVisible(true);  

  12. }  

  13. public static void main(String[] args) {  

  14. new Simple2();  

  15. }}  

BorderLayout (LayoutManagers):

LayoutManagers:

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. There are following classes that represents the layout managers:


  1. java.awt.BorderLayout

  2. java.awt.FlowLayout

  3. java.awt.GridLayout

  4. java.awt.CardLayout

  5. java.awt.GridBagLayout

  6. javax.swing.BoxLayout

  7. javax.swing.GroupLayout

  8. javax.swing.ScrollPaneLayout

  9. javax.swing.SpringLayout etc.

BorderLayout:

The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout provides five constants for each region:



  1. public static final int NORTH

  2. public static final int SOUTH

  3. public static final int EAST

  4. public static final int WEST

  5. public static final int CENTER

Constructors of BorderLayout class:

  • BorderLayout(): creates a border layout but with no gaps between the components.

  • JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components.

Example of BorderLayout class:

borderlayout class

  1. import java.awt.*;  

  2. import javax.swing.*;  

  3.   

  4. public class Border {  

  5. JFrame f;  

  6. Border(){  

  7.     f=new JFrame();  

  8.       

  9.     JButton b1=new JButton("NORTH");;  

  10.     JButton b2=new JButton("SOUTH");;  

  11.     JButton b3=new JButton("EAST");;  

  12.     JButton b4=new JButton("WEST");;  

  13.     JButton b5=new JButton("CENTER");;  

  14.       

  15.     f.add(b1,BorderLayout.NORTH);  

  16.     f.add(b2,BorderLayout.SOUTH);  

  17.     f.add(b3,BorderLayout.EAST);  

  18.     f.add(b4,BorderLayout.WEST);  

  19.     f.add(b5,BorderLayout.CENTER);  

  20.       

  21.     f.setSize(300,300);  

  22.     f.setVisible(true);  

  23. }  

  24. public static void main(String[] args) {  

  25.     new Border();  

  26. }  

  27. }  

GridLayout

The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.

Constructors of GridLayout class:

  1. GridLayout(): creates a grid layout with one column per component in a row.

  2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components.

  3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps.

Example of GridLayout class:

gridlayout class

  1. import java.awt.*;  

  2. import javax.swing.*;  

  3.   

  4. public class MyGridLayout{  

  5. JFrame f;  

  6. MyGridLayout(){  

  7.     f=new JFrame();  

  8.       

  9.     JButton b1=new JButton("1");  

  10.     JButton b2=new JButton("2");  

  11.     JButton b3=new JButton("3");  

  12.     JButton b4=new JButton("4");  

  13.     JButton b5=new JButton("5");  

  14.         JButton b6=new JButton("6");  

  15.         JButton b7=new JButton("7");  

  16.     JButton b8=new JButton("8");  

  17.         JButton b9=new JButton("9");  

  18.           

  19.     f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  

  20.     f.add(b6);f.add(b7);f.add(b8);f.add(b9);  

  21.   

  22.     f.setLayout(new GridLayout(3,3));  

  23.     //setting grid layout of 3 rows and 3 columns  

  24.   

  25.     f.setSize(300,300);  

  26.     f.setVisible(true);  

  27. }  

  28. public static void main(String[] args) {  

  29.     new MyGridLayout();  

  30. }  

  31. }  

FlowLayout

The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel.

Fields of FlowLayout class:

  1. public static final int LEFT

  2. public static final int RIGHT

  3. public static final int CENTER

  4. public static final int LEADING

  5. public static final int TRAILING

Constructors of FlowLayout class:

  1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.

  2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap.

  3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal and vertical gap.

Example of FlowLayout class:



flowlayout class

  1. import java.awt.*;  

  2. import javax.swing.*;  

  3.   

  4. public class MyFlowLayout{  

  5. JFrame f;  

  6. MyFlowLayout(){  

  7.     f=new JFrame();  

  8.       

  9.     JButton b1=new JButton("1");  

  10.     JButton b2=new JButton("2");  

  11.     JButton b3=new JButton("3");  

  12.     JButton b4=new JButton("4");  

  13.     JButton b5=new JButton("5");  

  14.               

  15.     f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  

  16.       

  17.     f.setLayout(new FlowLayout(FlowLayout.RIGHT));  

  18.     //setting flow layout of right alignment  

  19.   

  20.     f.setSize(300,300);  

  21.     f.setVisible(true);  

  22. }  

  23. public static void main(String[] args) {  

  24.     new MyFlowLayout();  

  25. }  

  26. }  

BoxLayout class:

The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose, BoxLayout provides four constants. They are as follows:

Note: BoxLayout class is found in javax.swing package.

Fields of BoxLayout class:



  1. public static final int X_AXIS

  2. public static final int Y_AXIS

  3. public static final int LINE_AXIS

  4. public static final int PAGE_AXIS

Constructor of BoxLayout class:

  1. BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given axis.

Example of BoxLayout class with Y-AXIS:

boxlayout class

  1. import java.awt.*;  

  2. import javax.swing.*;  

  3.   

  4. public class BoxLayoutExample1 extends Frame {  

  5.  Button buttons[];  

  6.   

  7.  public BoxLayoutExample1 () {  

  8.    buttons = new Button [5];  

  9.     

  10.    for (int i = 0;i<5;i++) {  

  11.       buttons[i] = new Button ("Button " + (i + 1));  

  12.       add (buttons[i]);  

  13.     }  

  14.   

  15. setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));  

  16. setSize(400,400);  

  17. setVisible(true);  

  18. }  

  19.   

  20. public static void main(String args[]){  

  21. BoxLayoutExample1 b=new BoxLayoutExample1();  

  22. }  

  23. }  

Example of BoxLayout class with X-AXIS:

boxlayout class example

  1. import java.awt.*;  

  2. import javax.swing.*;  

  3.   

  4. public class BoxLayoutExample2 extends Frame {  

  5.  Button buttons[];  

  6.   

  7.  public BoxLayoutExample2() {  

  8.    buttons = new Button [5];  

  9.     

  10.    for (int i = 0;i<5;i++) {  

  11.       buttons[i] = new Button ("Button " + (i + 1));  

  12.       add (buttons[i]);  

  13.     }  

  14.   

  15. setLayout (new BoxLayout(this, BoxLayout.X_AXIS));  

  16. setSize(400,400);  

  17. setVisible(true);  

  18. }  

  19.   

  20. public static void main(String args[]){  

  21. BoxLayoutExample2 b=new BoxLayoutExample2();  

  22. }  }

CardLayout class

The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout class:

  1. CardLayout(): creates a card layout with zero horizontal and vertical gap.

  2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.

Commonly used methods of CardLayout class:

  • public void next(Container parent): is used to flip to the next card of the given container.

  • public void previous(Container parent): is used to flip to the previous card of the given container.

  • public void first(Container parent): is used to flip to the first card of the given container.

  • public void last(Container parent): is used to flip to the last card of the given container.

  • public void show(Container parent, String name): is used to flip to the specified card with the given name.

Example of CardLayout class:

cardlayout class


  1. import java.awt.*;  

  2. import java.awt.event.*;  

  3.   

  4. import javax.swing.*;  

  5.   

  6. public class CardLayoutExample extends JFrame implements ActionListener{  

  7. CardLayout card;  

  8. JButton b1,b2,b3;  

  9. Container c;  

  10.     CardLayoutExample(){  

  11.           

  12.         c=getContentPane();  

  13.         card=new CardLayout(40,30);  

  14. //create CardLayout object with 40 hor space and 30 ver space  

  15.         c.setLayout(card);  

  16.           

  17.         b1=new JButton("Apple");  

  18.         b2=new JButton("Boy");  

  19.         b3=new JButton("Cat");  

  20.         b1.addActionListener(this);  

  21.         b2.addActionListener(this);  

  22.         b3.addActionListener(this);  

  23.               

  24.         c.add("a",b1);c.add("b",b2);c.add("c",b3);  

  25.                           

  26.     }  

  27.     public void actionPerformed(ActionEvent e) {  

  28.     card.next(c);  

  29.     }  

  30.   

  31.     public static void main(String[] args) {  

  32.         CardLayoutExample cl=new CardLayoutExample();  

  33.         cl.setSize(400,400);  

  34.         cl.setVisible(true);  

  35.         cl.setDefaultCloseOperation(EXIT_ON_CLOSE);  

  36.     }  

  37. }  

Java Applet

Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:



  • It works at client side so less response time.

  • Secured

  • It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.

Drawback of Applet

  • Plugin is required at client browser to execute applet.

Hierarchy of Applet

hierarchy of applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass of Component.

Lifecycle of Java Applet

  1. Applet is initialized.

  2. Applet is started.

  3. Applet is painted.

  4. Applet is stopped.

  5. Applet is destroyed.

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.


  1. public void init(): is used to initialized the Applet. It is invoked only once.

  2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.

  3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.

  4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.



  1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet


  1. By html file.

  2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet code in html file. Now click the html file.



  1. //First.java  

  2. import java.applet.Applet;  

  3. import java.awt.Graphics;  

  4. public class First extends Applet{  

  5.   

  6. public void paint(Graphics g){  

  7. g.drawString("welcome",150,150);  

  8. }  

  9.   

  10. }  

Note: class must be public because its object is created by Java Plugin software that resides on the browser.

myapplet.html



  1.   

  2.   

  3.   

  4.   

  5.   

  6.   

  7.   

  8.   

  9.   

  10.   

  11.   

  12.   

  13.   

  14.   

  15.   

  16.   

  17.   

  18.   

  19.   

  20.   

  21.   

  22.   

  23.   

  24.   

  25.   

  26.   

  27.   
  28.   


  29.   

  30.   

  31.   

  32.   

  33.   

  34.   

  35.   

  36. Yüklə 349,37 Kb.

    Dostları ilə paylaş:




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə