***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***

posts

    Java Swing - difference between AWT and swing

    Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for building optimized window based applications. It is a part of the JFC( Java Foundation Classes). It is build on top of the AWT API and entirely written in java. It is platform independent unlike AWT and has lightweight components.

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

    Swing component follows a Model-View-Controller architecture to fulfill the following criterias.

    • A single API is to be sufficient to support multiple look and feel.
    • API is to be model driven so that the highest level API is not required to have data.
    • API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers for use.

    Swing API architecture follows loosely based MVC architecture in the following manner.

    • Model represents component's data.
    • View represents visual representation of the component's data.
    • Controller takes the input from the user on the view and reflects the changes in Component's data.
    • Swing component has Model as a separate element, while the View and Controller part are clubbed in the User Interface elements. Because of which, Swing has a pluggable look-and-feel architecture.

    Swing Features

    • Light Weight − Swing components are independent of native Operating System's API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls.
    • Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, and table controls.
    • Highly Customizable − Swing controls can be customized in a very easy way as visual apperance is independent of internal representation.
    • Pluggable look-and-feel − SWING based GUI Application look and feel can be changed at run-time, based on available values.

    Difference between AWT and Swing

    Java AWT

    Java Swing

    AWT components are platform-dependent.

    Java swing components are platform-independent.

    AWT components are heavyweight.

    Swing components are lightweight.

    AWT doesn't support pluggable look and feel.

    Swing supports pluggable look and feel.

    AWT provides less components than Swing.

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

    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.

    AWT Layouts

    Layout means the arrangement of components within the container. The task of layouting the controls is done automatically by the Layout Manager.

    The Java LayoutManagers helps to control the positioning and size of the components in GUI forms. LayoutManager is an interface that is implemented by all the classes of layout managers.

    The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the LayoutManager interface.

    There are the following classes that represent the layout managers:

    1. java.awt.BorderLayout
    2. java.awt.FlowLayout
    3. java.awt.GridLayout
    4. java.awt.CardLayout
    5. java.awt.GridBagLayout

    1. Border Layout:

    The borderlayout arranges the components to fit in the five regions: east, west, north, south and center.

    Each region (area) may contain one component only. It is the default layout of a 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.
    • BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components.

    Ex:

    import java.awt.*;   

    import javax.swing.*;     

    public class Border  

    {   

    JFrame f;   

    Border() 

    {   

        f = new JFrame();   

         // creating buttons 

        JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH  

        JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH 

        JButton b3 = new JButton("EAST");; // the button will be labeled as EAST 

        JButton b4 = new JButton("WEST");; // the button will be labeled as WEST 

        JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER 

        f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction   

        f.add(b2, BorderLayout.SOUTH);  // b2 will be placed in the South Direction   

        f.add(b3, BorderLayout.EAST);  // b2 will be placed in the East Direction   

        f.add(b4, BorderLayout.WEST);  // b2 will be placed in the West Direction   

        f.add(b5, BorderLayout.CENTER);  // b2 will be placed in the Center    

        f.setSize(300, 300);   

        f.setVisible(true);   

    }   

    public static void main(String[] args) {   

        new Border();   

    }   

    }   

    2. Flow Layout

    It layouts the components in a directional flow. The Java FlowLayout class is used to arrange the components in a line, one after another (in a flow). It is the default layout of the 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.

    Ex:

    // import statements 

    import java.awt.*;   

    import javax.swing.*;       

    public class FlowLayoutExample 

    {  

    JFrame frameObj; 

    // constructor   

    FlowLayoutExample() 

    {   

        // creating a frame object 

        frameObj = new JFrame();   

         // creating the buttons 

        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");     

        // adding the buttons to frame       

        frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);     

        frameObj.add(b5);

         // parameter less constructor is used therefore, alignment is center  

        // horizontal as well as the vertical gap is 5 units. 

        frameObj.setLayout(new FlowLayout());   

        frameObj.setSize(300, 300);   

        frameObj.setVisible(true);   

    }  

    // main method 

    public static void main(String argvs[])  

    {   

        new FlowLayoutExample();   

    }   

    }  

    3. Grid Layout

    The GridLayout manages the components in form of a rectangular grid. The Java GridLayout class is used to arrange the components in a 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 along with given horizontal and vertical gaps.

    Ex:

    / import statements 

    import java.awt.*;   

    import javax.swing.*;      

    public class GridLayoutExample 

    {   

    JFrame frameObj;   

    // constructor 

    GridLayoutExample() 

    {   

    frameObj = new JFrame();   

    JButton btn1 = new JButton("1");   

    JButton btn2 = new JButton("2");   

    JButton btn3 = new JButton("3");   

    JButton btn4 = new JButton("4");   

    JButton btn5 = new JButton("5");   

    // adding buttons to the frame 

    // since, we are using the parameterless constructor, therfore;  

    // the number of columns is equal to the number of buttons we  

    // are adding to the frame. The row count remains one. 

    frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3); 

    frameObj.add(btn4); frameObj.add(btn5);

     // setting the grid layout using the parameterless constructor   

    frameObj.setLayout(new GridLayout());   

    frameObj.setSize(300, 300);   

    frameObj.setVisible(true);   

    // main method 

    public static void main(String argvs[])  

    {   

    new GridLayoutExample();   

    }   

    }

    4. Card Layout

    The CardLayout object treats each component in the container as a card. Only one card is visible at a time.

    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.

    Ex:

    import java.awt.*;   

    import javax.swing.*;  

    import java.awt.event.*;   

    public class CardLayoutExample1 extends JFrame implements ActionListener 

    {   

    CardLayout crd;   

    // button variables to hold the references of buttons 

    JButton btn1, btn2, btn3;   

    Container cPane;  

    // constructor of the class 

    CardLayoutExample1() 

    {   

     cPane = getContentPane();   

     //default constructor used therefore, components will cover the whole area 

    crd = new CardLayout();   

    cPane.setLayout(crd);   

    // creating the buttons 

    btn1 = new JButton("Apple");   

    btn2 = new JButton("Boy");   

    btn3 = new JButton("Cat");   

    // adding listeners to it 

    btn1.addActionListener(this);   

    btn2.addActionListener(this);   

    btn3.addActionListener(this);   

    cPane.add("a", btn1); // first card is the button btn1 

    cPane.add("b", btn2); // first card is the button btn2 

    cPane.add("c", btn3);  // first card is the button btn3            

    }   

    public void actionPerformed(ActionEvent e)  

    {   

    // Upon clicking the button, the next card of the container is shown 

    // after the last card, again, the first card of the container is shown upon clicking 

    crd.next(cPane);   

    }   

    // main method 

    public static void main(String argvs[])  

    {    

    // creating an object of the class CardLayoutExample1 

    CardLayoutExample1 crdl = new CardLayoutExample1();  

    // size is 300 * 300         

    crdl.setSize(300, 300);   

    crdl.setVisible(true);   

    crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);   

    }   

    5. GridBag Layout

    This is the most flexible layout manager class.The object of GridBagLayout aligns the component vertically,horizontally or along their baseline without requiring the components of same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells. Each component occupies one or more cells known as its display area.

    The GridBagLayout manages each component's minimum and preferred sizes in order to determine the component's size. GridBagLayout components are also arranged in the rectangular grid but can have many different sizes and can occupy multiple rows or columns.

    Constructor:

    GridBagLayout(): The parameterless constructor is used to create a grid bag layout manager.

    Ex:

    import java.awt.Button; 

    import java.awt.GridBagConstraints; 

    import java.awt.GridBagLayout; 

    import javax.swing.*; 

    public class GridBagLayoutExample extends JFrame{ 

        public static void main(String[] args) { 

                GridBagLayoutExample a = new GridBagLayoutExample(); 

            } 

            public GridBagLayoutExample() { 

        GridBagLayoutgrid = new GridBagLayout(); 

                GridBagConstraints gbc = new GridBagConstraints(); 

                setLayout(grid); 

                setTitle("GridBag Layout Example"); 

                GridBagLayout layout = new GridBagLayout(); 

        this.setLayout(layout); 

        gbc.fill = GridBagConstraints.HORIZONTAL; 

        gbc.gridx = 0; 

        gbc.gridy = 0; 

        this.add(new Button("Button One"), gbc); 

        gbc.gridx = 1; 

        gbc.gridy = 0; 

        this.add(new Button("Button two"), gbc); 

        gbc.fill = GridBagConstraints.HORIZONTAL; 

        gbc.ipady = 20; 

        gbc.gridx = 0; 

        gbc.gridy = 1; 

        this.add(new Button("Button Three"), gbc); 

        gbc.gridx = 1; 

        gbc.gridy = 1; 

        this.add(new Button("Button Four"), gbc); 

        gbc.gridx = 0; 

        gbc.gridy = 2; 

        gbc.fill = GridBagConstraints.HORIZONTAL; 

        gbc.gridwidth = 2; 

        this.add(new Button("Button Five"), gbc); 

                setSize(300, 300); 

                setPreferredSize(getSize()); 

                setVisible(true); 

                setDefaultCloseOperation(EXIT_ON_CLOSE); 

            } 

    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. It is basically a screen where the where the components are placed at their specific locations. Thus it contains and controls the layout of components.

    There are four types of containers in Java AWT:

    1. Window
    2. Panel
    3. Frame
    4. Dialog

    Window

    The window is the container that does not have borders and menu bars. A frame, dialog or another window must be used for creating a window. An instance of Window class needs to be created to create this container.

    Following is the declaration for java.awt.Window class:

    public class Window extends Container implements Accessible

    A window can act as a container of information – outputs,drawings etc. Even applets make use of window to display the information.

    Panel

    The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for holding the components. It can have other components like button, text field etc. An instance of Panel class creates a container, in which we can add components.

    Following is the declaration for java.awt.Panel class:

    public class Panel extends Container implements Accessible  

    Any other components can be added to a panel using add() method. They can be even resized using setSize(),setBounds() and setPreferredSize(). Components can be positioned in a panel using setLocation().

    Frame

    The Frame is the container that contain title bar and border and can have menu bars. It can have other components like button, text field, scrollbar etc. Frame is most widely used container while developing an AWT application. They are the child windows which users create within the applets for stand alone applications.

    Following is the declaration for java.awt.Frame class:

    public class Frame extends Window implements MenuContainer

    Dialog

    The Dialog control represents a top level window with a border and a title used to take some form of input from the user. It inherits the Window class. Unlike Frame, it doesn't have maximize and minimize buttons.

    Following is the declaration for java.awt.Dialog class:

    public class Dialog extends Window

    Java AWT Radio Button

    In java.awt we are not having a special class for radio buttons but we can create radio button from Checkbox class. Radio buttons are created as instances of the CheckboxGroup class. 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.

    public class CheckboxGroup extends Object implements Serializable  

    Steps for converting checkboxes into radiobutton:

    1. Create objects of CheckboxGroup class.

    Ex: CheckboxGroup cbg1=new CheckboxGroup ();

    2. Create 'n' number of objects of Checkbox class.

    Ex:

    Checkbox b1, b2, b3;

    b1=new Checkbox ("C");

    b2=new Checkbox ("Cpp");

    b3=new Checkbox ("Java");

    3. Decide which checkboxes are adding to which CheckboxGroup object. In order to add the checkboxes to the CheckboxGroup object, in Check box class we have the following method:

    public void setCheckboxGroup (CheckboxGroup);

    Ex:

    cb1.setCheckboxGroup (cbg1);

    cb2.setCheckboxGroup (cbg2);

    cb3.setCheckboxGroup (cbg3);

    Instead of using a setCheckboxGroup method the following Constructor which is present in Check box class can be used to create checkbox group.

    Checkbox (String, CheckboxGroup, boolean);

    Checkbox (String, boolean, CheckboxGroup);

    Ex:

    Checkbox cb1=new Checkbox ("C", cbg1, false);

    Checkbox cb2=new Checkbox ("Cpp", cbg2, false);

    Checkbox cb3=new Checkbox ("Java", cbg3, false);

    Ex:

    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("Cpp", 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();   

    }   

    }