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

posts

    JTable

    The JTable class is a part of Java Swing Package and is generally used to display or edit two-dimensional data that is having both rows and columns. It is similar to a spreadsheet. This arranges data in a tabular form.

    Constructors in JTable: 

    1. JTable(): A table is created with empty cells.
    2. JTable(int rows, int cols): Creates a table of size rows * cols.
    3. JTable(Object[][] data, Object []Column): A table is created with the specified name where []Column defines the column names.

    Functions in JTable: 

    1. addColumn(TableColumn []column) : adds a column at the end of the JTable.
    2. clearSelection() : Selects all the selected rows and columns.
    3. editCellAt(int row, int col) : edits the intersecting cell of the column number col and row number row programmatically, if the given indices are valid and the corresponding cell is editable.
    4. setValueAt(Object value, int row, int col) : Sets the cell value as ‘value’ for the position row, col in the JTable.

    Ex:

    // Packages to import

    import javax.swing.JFrame;

    import javax.swing.JScrollPane;

    import javax.swing.JTable;

     

    public class JTableExamples {

                // frame

                JFrame f;

                // Table

                JTable j;

                 // Constructor

                JTableExamples()

                {

                            // Frame initialization

                            f = new JFrame();

                             // Frame Title

                            f.setTitle("JTable Example");

                             // Data to be displayed in the JTable

                            String[][] data = {

                                        { "Ashraf", "4001", "CS" },

                                        { "Amjad", "6001", "IT" }

                            };

                             // Column Names

                            String[] columnNames = { "Name", "Roll Number", "Department" };

                             // Initializing the JTable

                            j = new JTable(data, columnNames);

                            j.setBounds(30, 40, 200, 300);

                            // adding it to JScrollPane

                            JScrollPane sp = new JScrollPane(j);

                            f.add(sp);

                            // Frame Size

                            f.setSize(500, 200);

                            // Frame Visible = true

                            f.setVisible(true);

                }

                 // Driver method

                public static void main(String[] args)

                {

                            new JTableExamples();

                }

    }

    Layout Manager

    Layout refers to the arrangement of components within the container. The task of laying out the controls is done automatically by the Layout Manager.

    The following are the layout managers:

    • FlowLayout
    • BorderLayout
    • CardLayout
    • BoxLayout
    • GridLayout
    • GridBagLayout
    • GroupLayout
    • SpringLayout

    Ø  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 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();   

    }   

    }   

    Ø  Java GridLayout

    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 java.awt.*;   

    import javax.swing.*;   

    public class GridLayoutExample 

    {   

    JFrame frameObj;   

    GridLayoutExample() 

    {   

    frameObj = new JFrame();   

    // creating 9 buttons 

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

    JButton btn6 = new JButton("6");   

    JButton btn7 = new JButton("7");   

    JButton btn8 = new JButton("8");    

    JButton btn9 = new JButton("9");   

       

    // 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); frameObj.add(btn6); 

    frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);   

     

    // 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();   

    }   

    }   

    Ø  Java FlowLayout

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

        JButton b6 = new JButton("6");   

        JButton b7 = new JButton("7");   

        JButton b8 = new JButton("8");   

        JButton b9 = new JButton("9");   

        JButton b10 = new JButton("10");   

                

        // adding the buttons to frame       

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

        frameObj.add(b5); frameObj.add(b6);  frameObj.add(b7);  frameObj.add(b8);   

        frameObj.add(b9);  frameObj.add(b10);     

          

        // 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();   

    }   

    }   

    Ø  Java BoxLayout

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

    1. public static final int X_AXIS: Alignment of the components are horizontal from left to right.
    2. public static final int Y_AXIS: Alignment of the components are vertical from top to bottom.
    3. public static final int LINE_AXIS: Alignment of the components is similar to the way words are aligned in a line, which is based on the ComponentOrientation property of the container. If the ComponentOrientation property of the container is horizontal, then the components are aligned horizontally; otherwise, the components are aligned vertically. For horizontal orientations, we have two cases: left to right, and right to left. If the value ComponentOrientation property of the container is from left to right, then the components are rendered from left to right, and for right to left, the rendering of components is also from right to left. In the case of vertical orientations, the components are always rendered from top to bottom.
    4. public static final int PAGE_AXIS: Alignment of the components is similar to the way text lines are put on a page, which is based on the ComponentOrientation property of the container. If the ComponentOrientation property of the container is horizontal, then components are aligned vertically; otherwise, the components are aligned horizontally. For horizontal orientations, we have two cases: left to right, and right to left. If the value ComponentOrientation property of the container is also from left to right, then the components are rendered from left to right, and for right to left, the rendering of components is from right to left. In the case of vertical orientations, the components are always rendered from top to bottom.

    Constructor of BoxLayout class

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

    Ø  Java CardLayout

    The Java 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.

     

    Ø  Java GridBagLayout

    The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline.

    The components may not be of the same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells. Each component occupies one or more cells known as its display area. Each component associates an instance of GridBagConstraints. With the help of the constraints object, we arrange the component's display area on the grid. 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.


    Ø  GroupLayout

    GroupLayout groups its components and places them in a Container hierarchically. The grouping is done by instances of the Group class.

    Group is an abstract class, and two concrete classes which implement this Group class are SequentialGroup and ParallelGroup.

    SequentialGroup positions its child sequentially one after another whereas ParallelGroup aligns its child on top of each other.

    The GroupLayout class provides methods such as createParallelGroup() and createSequentialGroup() to create groups.

    GroupLayout treats each axis independently. That is, there is a group representing the horizontal axis, and a group representing the vertical axis. Each component must exist in both a horizontal and vertical group, otherwise an IllegalStateException is thrown during layout or when the minimum, preferred, or maximum size is requested.


    Ø  Java SpringLayout

    SpringLayout arranges the children of its associated container according to a set of constraints. Constraints are nothing but horizontal and vertical distance between two-component edges. Every constraint is represented by a SpringLayout.Constraint object.

    Each child of a SpringLayout container, as well as the container itself, has exactly one set of constraints associated with them.

    Each edge position is dependent on the position of the other edge. If a constraint is added to create a new edge, than the previous binding is discarded. SpringLayout doesn't automatically set the location of the components it manages.

    Constructor:

    SpringLayout(): The default constructor of the class is used to instantiate the SpringLayout class


    Ø  ScrollPaneLayout

    The layout manager is used by JScrollPane. JScrollPaneLayout is responsible for nine components: a viewport, two scrollbars, a row header, a column header, and four "corner" components.

    Constructor:

    ScrollPaneLayout(): The parameterless constructor is used to create a new ScrollPanelLayout.

    Swing components

    Swing components are the basic building blocks of an application. Swing is a GUI widget toolkit for Java. Every application has some basic interactive interface for the user. For example, a button, check-box, radio-button, text-field, etc. These together form the components in Swing. Swing components are the interactive elements in a Java application.

    The hierarchy of java swing API is given below.


    Below are the different components of swing in java:

    1. ImageIcon

    The ImageIcon component creates an icon sized-image from an image residing at the source URL.

    Example:

    ImageIcon homeIcon = new ImageIcon(“src/images/home.jpg”);

    This returns an icon of a home button. The string parameter is the path at which the source image is present.

    2. JButton

    JButton class is used to create a push-button on the UI. The button can contain some display text or image. It generates an event when clicked and double-clicked. A JButton can be implemented in the application by calling one of its constructors.

    Example:

    JButton okBtn = new JButton(“Ok”);

    This constructor returns a button with text Ok on it.

    JButton homeBtn = new JButton(homeIcon);

    It returns a button with a homeIcon on it.

    JButton btn2 = new JButton(homeIcon, “Home”);

    It returns a button with the home icon and text Home.

    3. JLabel

    JLabel class is used to render a read-only text label or images on the UI. It does not generate any event.

    Example:

    JLabel textLbl = new JLabel(“This is a text label.”);

    This constructor returns a label with text.

    JLabel imgLabel = new JLabel(homeIcon);

    It returns a label with a home icon.

    4. JTextField

    JTextField renders an editable single-line text box. A user can input non-formatted text in the box. To initialize the text field, call its constructor and pass an optional integer parameter to it. This parameter sets the width of the box measured by the number of columns. It does not limit the number of characters that can be input in the box.

    Example:

    JTextField txtBox = new JTextField(20);

    It renders a text box of 20 column width.

    5. JTextArea

    JTextArea class renders a multi-line text box. Similar to the JTextField, a user can input non-formatted text in the field. The constructor for JTextArea also expects two integer parameters which define the height and width of the text-area in columns. It does not restrict the number of characters that the user can input in the text-area.

    Example:

    JTextArea txtArea = new JTextArea(“This text is default text for text area.”, 5, 20);

    The above code renders a multi-line text-area of height 5 rows and width 20 columns, with default text initialized in the text-area.

    6. JPasswordField

    JPasswordField is a subclass of JTextField class. It renders a text-box that masks the user input text with bullet points. This is used for inserting passwords into the application.

    Example:

    JPasswordField pwdField = new JPasswordField(15);
    var pwdValue = pwdField.getPassword();

    It returns a password field of 15 column width. The getPassword method gets the value entered by the user.

    7. JCheckBox

    JCheckBox renders a check-box with a label. The check-box has two states – on/off. When selected, the state is on and a small tick is displayed in the box.

    Example:

    CheckBox chkBox = new JCheckBox(“Show Help”, true);

    It returns a checkbox with the label Show Help. Notice the second parameter in the constructor. It is a boolean value that indicates the default state of the check-box. True means the check-box is defaulted to on state.

    8. JRadioButton

    JRadioButton is used to render a group of radio buttons in the UI. A user can select one choice from the group.

    Example:

    ButtonGroup radioGroup = new ButtonGroup();
    JRadioButton rb1 = new JRadioButton(“Easy”, true);
    JRadioButton rb2 = new JRadioButton(“Medium”);
    JRadioButton rb3 = new JRadioButton(“Hard”);
    radioGroup.add(rb1);
    radioGroup.add(rb2);
    radioGroup.add(rb3);

    The above code creates a button group and three radio button elements. All three elements are then added to the group. This ensures that only one option out of the available options in the group can be selected at a time. The default selected option is set to Easy.

    9. JList

    JList component renders a scrollable list of elements. A user can select a value or multiple values from the list. This select behavior is defined in the code by the developer.

    Example:

    DefaultListItem cityList = new DefaultListItem();
    cityList.addElement(“Mumbai”):
    cityList.addElement(“London”):
    cityList.addElement(“New York”):
    cityList.addElement(“Sydney”):
    cityList.addElement(“Tokyo”):
    JList cities = new JList(cityList);
    cities.setSelectionModel(ListSelectionModel.SINGLE_SELECTION);

    The above code renders a list of cities with 5 items in the list. The selection restriction is set to SINGLE_SELECTION. If multiple selections is to be allowed, set the behavior to MULTIPLE_INTERVAL_SELECTION.

    10. JComboBox

    JComboBox class is used to render a dropdown of the list of options.

    Example:

    String[] cityStrings = { "Mumbai", "London", "New York", "Sydney", "Tokyo" };
    JComboBox cities = new JComboBox(cityList);
    cities.setSelectedIndex(3);

    The default selected option can be specified through the setSelectedIndex method. The above code sets Sydney as the default selected option.

    11. JFileChooser

    JFileChooser class renders a file selection utility. This component lets a user select a file from the local system.

    Example:

    JFileChooser fileChooser = new JFileChooser();
    JButton fileDialogBtn = new JButton(“Select File”);
    fileDialogBtn.AddEventListner(new ActionListner(){
    fileChooser.showOpenDialog();
    })
    var selectedFile = fileChooser.getSelectedFile();

    The above code creates a file chooser dialog and attaches it to the button. The button click would open the file chooser dialog. The selected file is returned through the getSelectedFile method.

    12. JTabbedPane

    JTabbedPane is another very useful component that lets the user switch between tabs in an application. This is a highly useful utility as it lets the user browse more content without navigating to different pages.

    Example:

    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab(“Tab 1”, new JPanel());
    tabbedPane.addTab(“Tab 2”, new JPanel());

    The above code creates a two tabbed panel with headings Tab 1 and Tab 2.

    13. JSlider

    JSlider component displays a slider which the user can drag to change its value. The constructor takes three arguments – minimum value, maximum value, and initial value.

    Example:

    JSlider volumeSlider = new JSlider(0, 100, 50);
    var volumeLevel = volumeSlider.getValue();

    The above code creates a slider from 0 to 100 with an initial value set to 50. The value selected by the user is returned by the getValue method.