Java AWT Tutorial PDF

Summary

This document provides an introduction to Java AWT (Abstract Window Toolkit). It covers the basic concepts and components of AWT, including its hierarchy (Object, Component, Container, etc.). It also discusses event handling in AWT, demonstrating different approaches for handling events, using example code.

Full Transcript

Java AWT Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications 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 are usin...

Java AWT Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications 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 are using the resources of OS. The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, Listetc. Java AWT Hierarchy 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 Componentv class 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) AWT Example by Inheritance import java.awt.*; class First extends Frame{ First(){ Button b=new Button("click me"); b.setBounds(30,100,80,30);// setting button position add(b);//adding button into frame setSize(300,300);//frame size 300 width and 300 height setLayout(null);//no layout manager setVisible(true);//now frame will be visible, by default not visible } public static void main(String args[]){ First f=new First(); } } Output AWT Example by Association import java.awt.*; class First2{ First2(){ Frame f=new Frame(); Button b=new Button("click me"); b.setBounds(30,50,80,30); f.add(b); f.setSize(300,300); f.setLayout(null); f.setVisible(true); } public static void main(String args[]){ First2 f=new First2(); } } Output 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. Steps to perform Event Handling Following steps are required to perform event handling: 1. Register the component with the Listener 2. Registration Methods 3. 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){} Java Event Handling Code We can put the event handling code into one of the following places: 1. Within class 2. Other class 3. Anonymous class Java event handling by implementing ActionListener import java.awt.*; import java.awt.event.*; class AEvent extends Frame implements ActionListener{ TextField tf; AEvent(){ //create components tf=new TextField(); tf.setBounds(60,50,170,20); Button b=new Button("click me"); b.setBounds(100,120,80,30); //register listener b.addActionListener(this);//passing current instance //add components and set size, layout and visibility add(b);add(tf); setSize(300,300); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e){ tf.setText("Welcome"); } public static void main(String args[]){ new AEvent(); } } 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. 2) Java event handling by outer class import java.awt.*; import java.awt.event.*; class AEvent2 extends Frame{ TextField tf; AEvent2(){ //create components tf=new TextField(); tf.setBounds(60,50,170,20); Button b=new Button("click me"); b.setBounds(100,120,80,30); //register listener Outer o=new Outer(this); b.addActionListener(o);//passing outer class instance //add components and set size, layout and visibility add(b);add(tf); setSize(300,300); setLayout(null); setVisible(true); } public static void main(String args[]){ new AEvent2(); } } import java.awt.event.*; class Outer implements ActionListener{ AEvent2 obj; Outer(AEvent2 obj){ this.obj=obj; } public void actionPerformed(ActionEvent e){ obj.tf.setText("welcome"); } } 3) Java event handling by anonymous class import java.awt.*; import java.awt.event.*; class AEvent3 extends Frame{ TextField tf; AEvent3(){ tf=new TextField(); tf.setBounds(60,50,170,20); Button b=new Button("click me"); b.setBounds(50,120,80,30); b.addActionListener(new ActionListener(){ public void actionPerformed(){ tf.setText("hello"); } }); add(b);add(tf); setSize(300,300); setLayout(null); setVisible(true); } public static void main(String args[]){ new AEvent3(); } } Java AWT Button The button class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. public class Button extends Component implements Accessible Java AWT Button Example import java.awt.*; public class ButtonExample { public static void main(String[] args) { Frame f=new Frame("Button Example"); Button b=new Button("Click Here"); b.setBounds(50,100,80,30); f.add(b); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } } Output: Java AWT Button Example with ActionListener import java.awt.*; import java.awt.event.*; public class ButtonExample { public static void main(String[] args) { Frame f=new Frame("Button Example"); final TextField tf=new TextField(); tf.setBounds(50,50, 150,20); Button b=new Button("Click Here"); b.setBounds(50,100,60,30); b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ tf.setText("Welcome to Javatpoint."); } }); f.add(b);f.add(tf); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } } Java AWT Label The object of Label class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by an application but a user cannot edit it directly. AWT Label Class Declaration public class Label extends Component implements Accessible Java Label Example import java.awt.*; class LabelExample{ public static void main(String args[]){ Frame f= new Frame("Label Example"); Label l1,l2; l1=new Label("First Label."); l1.setBounds(50,100, 100,30); l2=new Label("Second Label."); l2.setBounds(50,150, 100,30); f.add(l1); f.add(l2); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } } Java AWT Label Example with ActionListener import java.awt.*; import java.awt.event.*; public class LabelExample extends Frame implements ActionListener{ TextField tf; Label l; Button b; LabelExample(){ tf=new TextField(); tf.setBounds(50,50, 150,20); l=new Label(); l.setBounds(50,100, 250,20); b=new Button("Find IP"); b.setBounds(50,150,60,30); b.addActionListener(this); add(b);add(tf);add(l); setSize(400,400); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e) { try{ String host=tf.getText(); String ip=java.net.InetAddress.getByName(host).getHostAddress(); l.setText("IP of "+host+" is: "+ip); }catch(Exception ex){System.out.println(ex);} } public static void main(String[] args) { new LabelExample(); } } Java AWT TextField Sr. Method name Description no. The object of a TextField class is a text component that allows the editing of a single line text. It inherits TextComponent class. 1. void addNotify() It creates the peer of text field. 2. boolean echoCharIsSet() It tells whether text field has character set for echoing or not. 3. void addActionListener(ActionListener l) It adds the specified action listener to receive action events from the text field. 4. ActionListener[] getActionListeners() It returns array of all action listeners registered on text field. 5. AccessibleContext getAccessibleContext() It fetches the accessible context related to the text field. 6. int getColumns() It fetches the number of columns in text field. 7. char getEchoChar() It fetches the character that is used for echoing. 8. Dimension getMinimumSize() It fetches the minimum dimensions for the text field. 9. Dimension getMinimumSize(int columns) It fetches the minimum dimensions for the text field with specified number of columns. 10. Dimension getPreferredSize() It fetches the preferred size of the text field. 11. Dimension getPreferredSize(int columns) It fetches the preferred size of the text field with specified number of columns. 12. protected String paramString() It returns a string representing state of the text field. 13. protected void It processes action events occurring in the text field by processActionEvent(ActionEvent e) dispatching them to a registered ActionListener object. 14. protected void processEvent(AWTEvent It processes the event on text field. e) 15. void removeActionListener(ActionListener It removes specified action listener so that it doesn't l) receive action events anymore. 16. void setColumns(int columns) It sets the number of columns in text field. 17. void setEchoChar(char c) It sets the echo character for text field. 18. void setText(String t) It sets the text presented by this text component to the specified text. AWT TextField Class Declaration public class TextField extends TextComponent Java AWT TextField Example import java.awt.*; class TextFieldExample{ public static void main(String args[]){ Frame f= new Frame("TextField Example"); TextField t1,t2; t1=new TextField("Welcome to Javatpoint."); t1.setBounds(50,100, 200,30); t2=new TextField("AWT Tutorial"); t2.setBounds(50,150, 200,30); f.add(t1); f.add(t2); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } } Java AWT TextField Example with ActionListener import java.awt.*; import java.awt.event.*; public class TextFieldExample extends Frame implements ActionListener{ TextField tf1,tf2,tf3; Button b1,b2; TextFieldExample(){ tf1=new TextField(); tf1.setBounds(50,50,150,20); tf2=new TextField(); tf2.setBounds(50,100,150,20); tf3=new TextField(); tf3.setBounds(50,150,150,20); tf3.setEditable(false); b1=new Button("+"); b1.setBounds(50,200,50,50); b2=new Button("-"); b2.setBounds(120,200,50,50); b1.addActionListener(this); b2.addActionListener(this); add(tf1);add(tf2);add(tf3);add(b1);add(b2); setSize(300,300); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e) { String s1=tf1.getText(); String s2=tf2.getText(); int a=Integer.parseInt(s1); int b=Integer.parseInt(s2); int c=0; if(e.getSource()==b1){ c=a+b; }else if(e.getSource()==b2){ c=a-b; } String result=String.valueOf(c); tf3.setText(result); } public static void main(String[] args) { new TextFieldExample(); } } Java AWT TextArea The object of a TextArea class is a multi line region that displays text. It allows the editing of multiple line text. It inherits TextComponent class. AWT TextArea Class Declaration public class TextArea extends TextComponent TextField Class Methods Java AWT TextArea Example import java.awt.*; public class TextAreaExample { TextAreaExample(){ Frame f= new Frame(); TextArea area=new TextArea("Welcome to javatpoint"); area.setBounds(10,30, 300,300); f.add(area); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new TextAreaExample(); } } Java AWT TextArea Example with ActionListener import java.awt.*; import java.awt.event.*; public class TextAreaExample extends Frame implements ActionListener{ Label l1,l2; TextArea area; Button b; TextAreaExample(){ l1=new Label(); l1.setBounds(50,50,100,30); l2=new Label(); l2.setBounds(160,50,100,30); area=new TextArea(); area.setBounds(20,100,300,300); b=new Button("Count Words"); b.setBounds(100,400,100,30); b.addActionListener(this); add(l1);add(l2);add(area);add(b); setSize(400,450); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e){ String text=area.getText(); String words[]=text.split("\\s"); l1.setText("Words: "+words.length); l2.setText("Characters: "+text.length()); } public static void main(String[] args) { new TextAreaExample(); } } Java AWT Checkbox The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on". AWT Checkbox Class Declaration public class Checkbox extends Component implements ItemSelectable, Accessible Java AWT Checkbox Example import java.awt.*; public class CheckboxExample { CheckboxExample(){ Frame f= new Frame("Checkbox Example"); Checkbox checkbox1 = new Checkbox("C++"); checkbox1.setBounds(100,100, 50,50); Checkbox checkbox2 = new Checkbox("Java", true); checkbox2.setBounds(100,150, 50,50); f.add(checkbox1); f.add(checkbox2); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new CheckboxExample(); } } Java AWT Checkbox Example with ItemListener import java.awt.*; import java.awt.event.*; public class CheckboxExample { CheckboxExample(){ Frame f= new Frame("CheckBox Example"); final Label label = new Label(); label.setAlignment(Label.CENTER); label.setSize(400,100); Checkbox checkbox1 = new Checkbox("C++"); checkbox1.setBounds(100,100, 50,50); Checkbox checkbox2 = new Checkbox("Java"); checkbox2.setBounds(100,150, 50,50); f.add(checkbox1); f.add(checkbox2); f.add(label); checkbox1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { label.setText("C++ Checkbox: " + (e.getStateChange()==1?"checked":"unchecked")); } }); checkbox2.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { label.setText("Java Checkbox: " + (e.getStateChange()==1?"checked":"unchecked")); } }); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new CheckboxExample(); } } Java AWT CheckboxGroup The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only one check box button is allowed to be in "on" state and remaining check box button in "off" state. It inherits the object class. Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special control for creating radio buttons in AWT. AWT CheckboxGroup Class Declaration public class CheckboxGroup extends Object implements Serializable Java AWT CheckboxGroup Example import java.awt.*; public class CheckboxGroupExample { CheckboxGroupExample(){ Frame f= new Frame("CheckboxGroup Example"); CheckboxGroup cbg = new CheckboxGroup(); Checkbox checkBox1 = new Checkbox("C++", cbg, false); checkBox1.setBounds(100,100, 50,50); Checkbox checkBox2 = new Checkbox("Java", cbg, true); checkBox2.setBounds(100,150, 50,50); f.add(checkBox1); f.add(checkBox2); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new CheckboxGroupExample(); } } Java AWT CheckboxGroup Example with ItemListener import java.awt.*; import java.awt.event.*; public class CheckboxGroupExample { CheckboxGroupExample(){ Frame f= new Frame("CheckboxGroup Example"); final Label label = new Label(); label.setAlignment(Label.CENTER); label.setSize(400,100); CheckboxGroup cbg = new CheckboxGroup(); Checkbox checkBox1 = new Checkbox("C++", cbg, false); checkBox1.setBounds(100,100, 50,50); Checkbox checkBox2 = new Checkbox("Java", cbg, false); checkBox2.setBounds(100,150, 50,50); f.add(checkBox1); f.add(checkBox2); f.add(label); f.setSize(400,400); f.setLayout(null); f.setVisible(true); checkBox1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { label.setText("C++ checkbox: Checked"); } }); checkBox2.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { label.setText("Java checkbox: Checked"); } }); } public static void main(String args[]) { new CheckboxGroupExample(); } } Java AWT Choice The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of a menu. It inherits Component class. AWT Choice Class Declaration public class Choice extends Component implements ItemSelectable, Accessible Java AWT Choice Example import java.awt.*; public class ChoiceExample { ChoiceExample(){ Frame f= new Frame(); Choice c=new Choice(); c.setBounds(100,100, 75,75); c.add("Item 1"); c.add("Item 2"); c.add("Item 3"); c.add("Item 4"); c.add("Item 5"); f.add(c); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new ChoiceExample(); } } Java AWT Choice Example with ActionListener import java.awt.*; import java.awt.event.*; public class ChoiceExample { ChoiceExample(){ Frame f= new Frame(); final Label label = new Label(); label.setAlignment(Label.CENTER); label.setSize(400,100); Button b=new Button("Show"); b.setBounds(200,100,50,20); final Choice c=new Choice(); c.setBounds(100,100, 75,75); c.add("C"); c.add("C++"); c.add("Java"); c.add("PHP"); c.add("Android"); f.add(c);f.add(label); f.add(b); f.setSize(400,400); f.setLayout(null); f.setVisible(true); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String data = "Programming language Selected: "+ c.getItem(c.getSelectedIndex()); label.setText(data); } }); } public static void main(String args[]) { new ChoiceExample(); } } Java AWT List The object of List class represents a list of text items. By the help of list, user can choose either one item or multiple items. It inherits Component class. AWT List class Declaration public class List extends Component implements ItemSelectable, Accessible Java AWT List Example import java.awt.*; public class ListExample { ListExample(){ Frame f= new Frame(); List l1=new List(5); l1.setBounds(100,100, 75,75); l1.add("Item 1"); l1.add("Item 2"); l1.add("Item 3"); l1.add("Item 4"); l1.add("Item 5"); f.add(l1); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new ListExample(); } } Java AWT List Example with ActionListener import java.awt.*; import java.awt.event.*; public class ListExample { ListExample(){ Frame f= new Frame(); final Label label = new Label(); label.setAlignment(Label.CENTER); label.setSize(500,100); Button b=new Button("Show"); b.setBounds(200,150,80,30); final List l1=new List(4, false); l1.setBounds(100,100, 70,70); l1.add("C"); l1.add("C++"); l1.add("Java"); l1.add("PHP"); final List l2=new List(4, true); l2.setBounds(100,200, 70,70); l2.add("Turbo C++"); l2.add("Spring"); l2.add("Hibernate"); l2.add("CodeIgniter"); f.add(l1); f.add(l2); f.add(label); f.add(b); f.setSize(450,450); f.setLayout(null); f.setVisible(true); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String data = "Programming language Selected: "+l1.getItem(l1.getSelectedIndex()); data += ", Framework Selected:"; for(String frame:l2.getSelectedItems()){ data += frame + " "; } label.setText(data); } }); } public static void main(String args[]) { new ListExample(); } } Java AWT Scrollbar The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public class Scrollbar extends Component implements Adjustable, Accessible Java AWT Scrollbar Example import java.awt.*; class ScrollbarExample{ ScrollbarExample(){ Frame f= new Frame("Scrollbar Example"); Scrollbar s=new Scrollbar(); s.setBounds(100,100, 50,100); f.add(s); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]){ new ScrollbarExample(); } } Java AWT Scrollbar Example with AdjustmentListener import java.awt.*; import java.awt.event.*; class ScrollbarExample{ ScrollbarExample(){ Frame f= new Frame("Scrollbar Example"); final Label label = new Label(); label.setAlignment(Label.CENTER); label.setSize(400,100); final Scrollbar s=new Scrollbar(); s.setBounds(100,100, 50,100); f.add(s);f.add(label); f.setSize(400,400); f.setLayout(null); f.setVisible(true); s.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { label.setText("Vertical Scrollbar value is:"+ s.getValue()); } }); } public static void main(String args[]){ new ScrollbarExample(); } } Java 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. Java 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: o BorderLayout(): creates a border layout but with no gaps between the components. o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components. Java 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: o BorderLayout(): creates a border layout but with no gaps between the components. o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components. Java 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: o BorderLayout(): creates a border layout but with no gaps between the components. o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components. Example of BorderLayout class: import java.awt.*; import javax.swing.*; public class Border { JFrame f; Border(){ f=new JFrame(); JButton b1=new JButton("NORTH");; JButton b2=new JButton("SOUTH");; JButton b3=new JButton("EAST");; JButton b4=new JButton("WEST");; JButton b5=new JButton("CENTER");; f.add(b1,BorderLayout.NORTH); f.add(b2,BorderLayout.SOUTH); f.add(b3,BorderLayout.EAST); f.add(b4,BorderLayout.WEST); f.add(b5,BorderLayout.CENTER); f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new Border(); } } Java 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 import java.awt.*; import javax.swing.*; public class MyGridLayout{ JFrame f; MyGridLayout(){ f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); JButton b6=new JButton("6"); JButton b7=new JButton("7"); JButton b8=new JButton("8"); JButton b9=new JButton("9"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.add(b6);f.add(b7);f.add(b8);f.add(b9); f.setLayout(new GridLayout(3,3)); //setting grid layout of 3 rows and 3 columns f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new MyGridLayout(); } } Java 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 import java.awt.*; import javax.swing.*; public class MyFlowLayout{ JFrame f; MyFlowLayout(){ f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.setLayout(new FlowLayout(FlowLayout.RIGHT)); //setting flow layout of right alignment f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new MyFlowLayout(); } } Java AWT MenuItem and Menu The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must belong to the MenuItem or any of its subclass. The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the MenuItem class. AWT MenuItem class declaration public class MenuItem extends MenuComponent implements Accessible AWT Menu class declaration public class Menu extends MenuItem implements MenuContainer, Accessible Java AWT MenuItem and Menu Example import java.awt.*; class MenuExample { MenuExample(){ Frame f= new Frame("Menu and MenuItem Example"); MenuBar mb=new MenuBar(); Menu menu=new Menu("Menu"); Menu submenu=new Menu("Sub Menu"); MenuItem i1=new MenuItem("Item 1"); MenuItem i2=new MenuItem("Item 2"); MenuItem i3=new MenuItem("Item 3"); MenuItem i4=new MenuItem("Item 4"); MenuItem i5=new MenuItem("Item 5"); menu.add(i1); menu.add(i2); menu.add(i3); submenu.add(i4); submenu.add(i5); menu.add(submenu); mb.add(menu); f.setMenuBar(mb); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new MenuExample(); } } Java Swing Java Swing 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. 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. Commonly used Methods of Component class The methods of Component class are widely used in java swing that are given below. Java Swing Examples There are two ways to create a frame: o By creating the object of Frame class (association) o 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 import javax.swing.*; public class FirstSwingExample { public static void main(String[] args) { JFrame f=new JFrame();//creating instance of JFrame JButton b=new JButton("click");//creating instance of JButton b.setBounds(130,100,100, 40);//x axis, y axis, width, height f.add(b);//adding button in JFrame f.setSize(400,500);//400 width and 500 height f.setLayout(null);//using no layout managers f.setVisible(true);//making the frame visible } } 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 import javax.swing.*; public class Simple { JFrame f; Simple(){ f=new JFrame();//creating instance of JFrame JButton b=new JButton("click");//creating instance of JButton b.setBounds(130,100,100, 40); f.add(b);//adding button in JFrame f.setSize(400,500);//400 width and 500 height f.setLayout(null);//using no layout managers f.setVisible(true);//making the frame visible } public static void main(String[] args) { new Simple(); } } 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 import javax.swing.*; public class Simple2 extends JFrame{//inheriting JFrame JFrame f; Simple2(){ JButton b=new JButton("click");//create button b.setBounds(130,100,100, 40); add(b);//adding button on frame setSize(400,500); setLayout(null); setVisible(true); } public static void main(String[] args) { new Simple2(); }} Introduction To Swing Swing Controls Every user interface considers the following three main aspects −  UI Elements − These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex, which we will cover in this tutorial.  Layouts − They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter.  Behavior − These are the events which occur when the user interacts with UI elements. This part will be covered in the Event Handling chapter. Every SWING controls inherits properties from the following Component class hiearchy. SWING UI Elements Following is the list of commonly used controls while designing GUI using SWING. S.No. Class & Description JLabel 1 A JLabel object is a component for placing text in a container. JButton 2 This class creates a labeled button. JColorChooser 3 A JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color. JCheck Box 4 A JCheckBox is a graphical component that can be in either an on (true) or off (false) state. JRadioButton 5 The JRadioButton class is a graphical component that can be in either an on (true) or off (false) state. in a group. JList 6 A JList component presents the user with a scrolling list of text items. JComboBox 7 A JComboBox component presents the user with a to show up menu of choices. JTextField 8 A JTextField object is a text component that allows for the editing of a single line of text. JPasswordField 9 A JPasswordField object is a text component specialized for password entry. 10 JTextArea A JTextArea object is a text component that allows editing of a multiple lines of text. ImageIcon 11 A ImageIcon control is an implementation of the Icon interface that paints Icons from Images JScrollbar 12 A Scrollbar control represents a scroll bar component in order to enable the user to select from range of values. JOptionPane 13 JOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of something. JFileChooser 14 A JFileChooser control represents a dialog window from which the user can select a file. JProgressBar 15 As the task progresses towards completion, the progress bar displays the task's percentage of completion. JSlider 16 A JSlider lets the user graphically select a value by sliding a knob within a bounded interval. JSpinner 17 A JSpinner is a single line input field that lets the user select a number or an object value from an ordered sequence. In this chapter, you will learn about Events, its types, and also learn how to handle an event. Example is provided at the end of the chapter for better understanding. What is an Event? Change in the state of an object is known as Event, i.e., event describes the change in the state of the source. Events are generated as a result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from the list, and scrolling the page are the activities that causes an event to occur. Types of Event The events can be broadly classified into two categories −  Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc.  Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events. What is Event Handling? Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an event handler, that is executed when an event occurs. Java uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events. The Delegation Event Model has the following key participants.  Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide us with classes for the source object.  Listener − It is also known as event handler. The listener is responsible for generating a response to an event. From the point of view of Java implementation, the listener is also an object. The listener waits till it receives an event. Once the event is received, the listener processes the event and then returns.  The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to a separate piece of code.  In this model, the listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listeners who want to receive them.  Steps Involved in Event Handling  Step 1 − The user clicks the button and the event is generated.  Step 2 − The object of concerned event class is created automatically and information about the source and the event get populated within the same object.  Step 3 − Event object is forwarded to the method of the registered listener class.  Step 4 − The method is gets executed and returns. Points to Remember About the Listener  In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods, which must be implemented by the listener class.  If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a source object. Callback Methods These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represent an event method. In response to an event, java jre will fire callback method. All such callback methods are provided in listener interfaces. If a component wants some listener to listen ot its events, the source must register itself to the listener. SWING - Event Classes Event classes represent the event. Java provides various Event classes, however, only those which are more frequently used will be discussed. EventObject Class It is the root class from which all event state objects shall be derived. All Events are constructed with a reference to the object, the source, that is logically deemed to be the object upon which the Event in question initially occurred upon. This class is defined in java.util package. Class Declaration Following is the declaration for java.util.EventObject class − public class EventObject extends Object implements Serializable Field Following are the fields for java.util.EventObject class − protected Object source − The object on which the Event initially occurred. Class Constructors Sr.No. Constructor & Description EventObject(Object source) 1 Constructs a prototypical Event. Class Methods Sr.No. Method & Description 1 Object getSource() The object on which the Event initially occurred. String toString() 2 Returns a String representation of this EventObject. Methods Inherited This class inherits methods from the following class −  java.lang.Object SWING Event Classes Following is the list of commonly used Event classes. Sr.No. Class & Description AWTEvent 1 It is the root event class for all SWING events. This class and its subclasses supercede the original java.awt.Event class. ActionEvent 2 The ActionEvent is generated when the button is clicked or the item of a list is double- clicked. InputEvent 3 The InputEvent class is the root event class for all component-level input events. KeyEvent 4 On entering the character the Key event is generated. MouseEvent 5 This event indicates a mouse action occurred in a component. WindowEvent 6 The object of this class represents the change in the state of a window. 7 AdjustmentEvent The object of this class represents the adjustment event emitted by Adjustable objects. ComponentEvent 8 The object of this class represents the change in the state of a window. ContainerEvent 9 The object of this class represents the change in the state of a window. MouseMotionEvent 10 The object of this class represents the change in the state of a window. PaintEvent 11 The object of this class represents the change in the state of a window. SWING - Event Listeners Event listeners represent the interfaces responsible to handle events. Java provides various Event listener classes, however, only those which are more frequently used will be discussed. Every method of an event listener method has a single argument as an object which is the subclass of EventObject class. For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent derives from EventObject. EventListner Interface It is a marker interface which every listener interface has to extend. This class is defined in java.util package. Class Declaration Following is the declaration for java.util.EventListener interface − public interface EventListener Following is the list of commonly used event listeners. Sr.No. Class & Description ActionListener 1 This interface is used for receiving the action events. ComponentListener 2 This interface is used for receiving the component events. 3 ItemListener This interface is used for receiving the item events. 4 KeyListener This interface is used for receiving the key events. 5 MouseListener This interface is used for receiving the mouse events. WindowListener 6 This interface is used for receiving the window events. 7 AdjustmentListener This interface is used for receiving the adjustment events. 8 ContainerListener This interface is used for receiving the container events. 9 MouseMotionListener This interface is used for receiving the mouse motion events. 10 FocusListener This interface is used for receiving the focus events. SWING - Event Adapters Adapters are abstract classes for receiving various events. The methods in these classes are empty. These classes exist as convenience for creating listener objects. SWING Adapters Following is the list of commonly used adapters while listening GUI events in SWING. Sr.No. Adapter & Description FocusAdapter 1 An abstract adapter class for receiving focus events. KeyAdapter 2 An abstract adapter class for receiving key events. MouseAdapter 3 An abstract adapter class for receiving mouse events. MouseMotionAdapter 4 An abstract adapter class for receiving mouse motion events. WindowAdapter 5 An abstract adapter class for receiving window events.

Use Quizgecko on...
Browser
Browser