Online-Academy

Look, Read, Understand, Apply

Menu

Swing Introduction

Java Swing – Developing User-Interface

In Java user interface is created by creating containers which provides space for components like textbox, list box, button etc.; JFrame, JPanel, JWindow are some of the containers which provide space for other components. JFrame is the mostly used container for developing user interface. JFrame can be created in following ways:

  • Extending JFrame class: e.g.,
    class myContainer extends JFrame{ }
  • Creating object of JFrame class:
    JFrame jf = new JFrame();

Containers have layout manager; layout manager specifies how the components on the container is placed, that is layout manager specifies physical arrangement of compoennts; FlowLayout, BorderLayout, GridLayout, BoxLayout, CardLayout are some of the inbuilt layouts for containers.

  • Package java.awt.* is imported to specify layout for the container.
  • In container components are added or placed using add() method of the container.
  • Layout for the container can be specified using setLayout() method of the container.
  • Size of container can be specified using setSize() method of the container, width and height are provided to this method.
  • Container can be made visible or invisible using setVisible() method, this method takes true or false value.
  • Container can be close using method setDefaultCloseOperation()
  • To locate container in the middle of the screen, setLocationRelativeTo() method; null value is passed to this function.

  • BorderLayout:- BorderLayout divides container into five different parts: NORTH, SOUTH, CENTER, EAST, WEST; components are placed in each part; container like JPanel can also be placed in these parts. BorderLayout is default layout for JFrame.
  • GridLayout:- GridLayout is used to create tabular layout for container; rows and columns are specified; components are added to the cells of the grid.
  • FlowLayout:- FlowLayout arranges components in left to right and top to bottom direction; components are added from left top corner of the container; it places components like we write text in paper, from left to right, top to bottom. It is default layout for JPanel.