Skip to main content

GridLayout: fill the form with gridlayout

Swing controls are of two types they are Containers and components. components are arranged on a containers. example components are JLabel, JButton etc and example containers are JPanel, JFrame and JDialog etc.
these components are arranged on a container with the help of layout managers. Few layout managers available in swing toolkit are

1. FlowLayout [Jframe's Default layout manager]
2. GridLayout
3. BorderLayout [JPanel's Default layout manager]
4. GridBagLayout.
5. Custom Layout manager

The custom layout amanger is useful to design programmer's own layout manager. Usually this is useful when any of the available layout managers does not give the needy result.
apart of these above all layout managers, few third party libraries are also available they are

1. DesignGridLayout
2. Mig Layout etc

Design grid Layout


Gridlayout is one of the most simple and flexible layout managers. layout manager is used to arrange the components on a container with proper margins, gap etc.

Gridlayout is suitable when the number of components are even numbered in each row of the container.


Swing program without any layout manager:


import java.awt.GridLayout;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class GridLayoutExample extends JFrame {

private JLabel label1 = null;
    private JLabel label2 = null;
    private JLabel label3 = null;
    private JTextField tf1 = null;
    private JTextField tf2 = null;
    private JTextField tf3 = null;
    private JButton button1 = null;
    private JButton button2 = null;

    public GridLayoutExample() {
        initComponents();
    }

    private void initComponents() {

        label1 = new JLabel("Name: ");
        add(label1);
        tf1 = new JTextField();
        add(tf1);

        label2 = new JLabel("Qualification: ");
        add(label2);

        tf2 = new JTextField();
        add(tf2);
        label3 = new JLabel("Profile: ");
        add(label3);

        tf3 = new JTextField();
        add(tf3);

        button1 = new JButton("Submit");
        add(button1);
        button2 = new JButton("Cancel");
        add(button2);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
    }


    public static void main(String[] args) throws InvocationTargetException, InterruptedException {

        GridLayoutExample ex = new GridLayoutExample();

        ex.setSize(300, 200);
        ex.setLocationRelativeTo(null);
        
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                ex.setVisible(true);
            }
        });

    }
}

  Output:





Shown below is a Swing program after adding a GridLayout. 

Replace the initComponents() of the above program with the below method


   private void initComponents() {
    GridLayout gl = new GridLayout();
    gl.setColumns(2);
    gl.setRows(4);
    gl.setHgap(15);
    gl.setVgap(15);

    this.setLayout(gl);

    label1 = new JLabel("Name: ");
    add(label1);
    tf1 = new JTextField();
    add(tf1);

    label2 = new JLabel("Qualification: ");
    add(label2);

    tf2 = new JTextField();
    add(tf2);
    label3 = new JLabel("Profile: ");
    add(label3);

    tf3 = new JTextField();
    add(tf3);

    button1 = new JButton("Submit");
    add(button1);
    button2 = new JButton("Cancel");
    add(button2);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
}



the output after applying layout manager.....







Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Post a Comment

Popular posts from this blog

DesignGridLayout: Simple, yet powerful Layoutmanager for arranging swing components

Swing toolkit comes with few standard Layout Managers where none of them serves the need of arranging components in a way that usually developers require. some of them does, but it takes lot of coding time to achieve it. GridBagLayout is the most flexible layout manager available in swing toolkit but their are so many variables that developer has to look after. DesignGridLayout can be a useful LayoutManager to arrange components in less time with very small snippet of code and can still get proper alignment. Layouting with DesignGridLayout is as easy as coding with various GUI Builder tools available in varoius IDEs. Simple program which demonstrates DesignGridLayout: import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import net.java.dev.designgr...

JForm: Fill the form with style

After understanding and using swing toolkit, I understood that there is a allot of scope to develop Custom components easily. I have developed a component called JForm which basically a button and its selection pops up a window if it is not visible. Technically the JForm component is a combination of 2 components they are: 1. JButton 2. Window JButton is a API of swing toolkit where as Window is a API of AWT. Behaviour of JForm: JForm is a usual button like JButton. but it is glued to a Window component. this Window takes a JPanel class as an arguments. In the given example has 2 components they are 1. JTextArea  2. JButton [Submit] which are appended to a JPanel.. The below image shows the effect before selecting the JForm: This image shown is the effect after selecting the JForm:                                       the below code is an example which i...

JColorComboBox: JComboBox as Color Chooser

  Swing toolkit provides a component called JColorChooser to choose colors. It allows users to select color from multiple color combinations. Some times our application may need simple component with an option to select only basic colors/ less number of color options unlike sepearate dialog with too may color options[JColorChooser]. This JColorComboBox may serve the need. I wanted my color chooser to behave like JComboBox. The popup shows all 12 colors and their names, among all of them one color can be choosen. see the below image. I created two classes          1. JColorComboBox          2. ColorRenderer JColorComboBox extends the JComboBox and ColorRenderer extends JLabel and implements ListCellRenderer. import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.util.Enumeration; import java.util.Hashtable; import javax.swing.*; /** * * @author sharath */ public class JCol...

File Manager/File Explorer with Swing JTree Component

This post is intended to beginners of java swing toolkit programmers. It is a simple java program which demonstrates the swing based File explorer GUI. import java.awt.GridLayout; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.List; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; /**  * @author NagasharathK  *  */ public class FileExplorer extends JFrame { private JTree fileManagerTree = null; public FileExplorer() { initComponents(); } /** * Initializes components */ private void initComponents() { this.getContentPane().add(new JScrollPane(createFileManagerTree(...

Evolution of Java Programming Language

Evolution of Java: First of all, The Java programming language and it's tools that we currenly using is not what actually expected. This language started as a project to give solutions for embedded devices, mobile phones and other portable peripherals.  Initially, the Java was called Oak.  Why it is Oak first..? and Why it transformed to Java..? The team of five technocrats including Dr. James Gosling and also known as Dr. Java, together working on a project, which expected to give solutions on embedded devices, portable smart devices and TV Set top Boxes etc. at Sun Micro Systems.  In the process of achieving this solution, at their breaktime, team used to relax with a coffee by having a glimpse on a scenery of Oak tree next to their facility.  Once the project has come to conclusion and in the process of giving a title to it, they noticed the Oak trees [Always observing them in their break time], they named this programming language as Oak. Oak Logo Why it transfor...

Romain guy's blog

If you are interested in designing GUIs and building custom components with Swing toolkit, definitely Romain guy's blog  can be good reference for you, he writes about his work on swing components, custom components, tips and tricks on designing and using components. and you can download the demos of his work. You find more swing articles in 2005, 2006 archives. His URL: http://www.curious-creature.org/

JavaFX: arranging components on GridPane

JavaFX provides different layout panes for arranging components on them. for example GridPane, BorderPane etc. This article describes about arranging components on GridPane. GridPane layout manager allows arranging components/controls using overloaded method. ie add.                         1. add(controlinstance, colindex, rowindex)                       EX:  GridPane pane = new GridPane();                                pane.add(new Separator(), 0, 0); the above example code puts the separator on 0th row and 0th column of a gridPane.                       2. add(Node controlinstance,int colIndex,int rowIndex,int colSpan,int rowSpan)                          ...

Demonstration of Java NullPointerException

NullPointerException causes and reasons Since Java is object oriented programming language, every thing is considered to be an object. and there is always a scope of an object to be null or "No value".  Since Java supports primitive data types, Java is not considered to be pure Java object oriented programming language.   Few Notable points about NullPointerException NullPointerExceptions is unchecked exception Please read post  Exception handling and java keywords before reading this article Usually if program tries to fetch the value from reference and finds nothing as value, then program throws NullPointerException 'Zero' is not null And empty String is not considered to be null It is not the subclass of RuntimeException class Demo code that throws NullPointerException  package com.allabtjava.blog; public class DemoNullPointerException { class BeanDemo { String name; Integer ID; public String getName() { return name; } public void s...

Java programming language and IDEs

IDE: Integrated Development Environment Integrated development environment, in short IDE is a convenient environment to write, execute and  debug the code or programs on a single platform. IDEs support not only writing code smoothly but also provides a provision to write scripts, XML files, simple text files and build scripts like Ant, Maven are few among others. In short IDEs are development environments to execute complete development activities using one application. IDEs and Editors IDEs and Editors fulfills the same purpose. That is writing code. But IDEs are glued or closely works with respective programming language's compilers, runtime environments, profilers and other language specific tools to put developer in a comfortable zone.  Some of the features of IDE: Auto completion Syntax Highlighting Code debugger Profilers Multipage editors Auto completion: Auto completion feature suggests APIs [methods, classes and interfaces] and keywords etc as we start typing in the e...

Agile Methodology with SCRUM Framework Basics

Software development activities can be managed and taken care with different life cycle models. These life cycle models has became legacy since few years. Few of the available Software Development Life Cycle Models in short SDLC are Win-Win Model and Waterfall Model etc. These traditional models has different phases of development.           1. Requirements            2. Analysis            3. Design            4. Implementation            5. Test           6. Documentation  and 7. Maintenance  In SDLC, the above stages are freezed one after the other. If developer is in Design phase and realized that there could be a possibility of change in requirements, then it is not possible to go back one phase and fix in Requirement phase.  These scenarios and use cases has brough...