Chapter 1
Chapter 1
Chapter 1
Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User
Interface (GUI) or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
Why AWT is platform independent?
In simple words, an AWT application will look like a windows application in
Windows OS whereas it will look like a Mac application in the MAC OS.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
Components
All the elements like the button, text fields, scroll bars, etc. are called
components. In Java AWT, there are classes for each component as shown in
above diagram. In order to place every component in a particular position on a
screen, we need to add them to a container.
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.
Note: A container itself is a component (see the above diagram), therefore
we can add a container inside container.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
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. We need to create
an instance of Window class to create this container.
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.
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.
Useful Methods of Component Class
Method Description
public void add(Component c) Inserts a component on this component.
public void setSize(int width,int Sets the size (width and height) of the
height) component.
public void Defines the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean Changes the visibility of the component,
status) by default false.
Java AWT Example
To create simple AWT example, you need a frame. There are two ways to create
a GUI using Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame class. Here,
we are showing Button component on the Frame.
AWTExample1.java
1. // importing Java AWT class
2. import java.awt.*;
3. // extending Frame class to our class AWTExample1
4. public class AWTExample1 extends Frame {
5. // initializing using constructor
6. AWTExample1() {
7. // creating a button
8. Button b = new Button("Click Me!!");
9. // setting button position on screen
10. b.setBounds(30,100,80,30);
11. // adding button into frame
12. add(b);
13. // frame size 300 width and 300 height
14. setSize(300,300);
15. // setting the title of Frame
16. setTitle("This is our basic AWT example");
17. // no layout manager
18. setLayout(null);
19. // now frame will be visible, by default it is not visible
20. setVisible(true);
21. }
22. // main method
23. public static void main(String args[]) {
24. // creating instance of Frame class
25. AWTExample1 f = new AWTExample1();
26. }
27. }
The setBounds(int x-axis, int y-axis, int width, int height) method is used in
the above example that sets the position of the awt button.
Output:
Java Swing
Java Swing tutorial 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.
BorderLayout (LayoutManagers)
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner.
The Java LayoutManagers facilitates us 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. 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
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 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.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border
5. {
6. JFrame f;
7. Border()
8. {
9. f = new JFrame();
10.
11. // creating buttons
12. JButton b1 = new JButton("NORTH");; // the button will be lab
eled as NORTH
13. JButton b2 = new JButton("SOUTH");; // the button will be lab
eled as SOUTH
14. JButton b3 = new JButton("EAST");; // the button will be labele
d as EAST
15. JButton b4 = new JButton("WEST");; // the button will be label
ed as WEST
16. JButton b5 = new JButton("CENTER");; // the button will be la
beled as CENTER
17.
18. f.add(b1, BorderLayout.NORTH); // b1 will be placed in the Nor
th Direction
19. f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the So
uth Direction
20. f.add(b3, BorderLayout.EAST); // b2 will be placed in the East
Direction
21. f.add(b4, BorderLayout.WEST); // b2 will be placed in the West
Direction
22. f.add(b5, BorderLayout.CENTER); // b2 will be placed in the C
enter
23.
24. f.setSize(300, 300);
25. f.setVisible(true);
26. }
27. public static void main(String[] args) {
28. new Border();
29. }
30. }
Output:
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.
Example of GridLayout class: Using GridLayout() Constructor
The GridLayout() constructor creates only one row. The following example
shows the usage of the parameterless constructor.
FileName: GridLayoutExample.java
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class GridLayoutExample
6. {
7. JFrame frameObj;
8.
9. // constructor
10. GridLayoutExample()
11. {
12. frameObj = new JFrame();
13.
14. // creating 9 buttons
15. JButton btn1 = new JButton("1");
16. JButton btn2 = new JButton("2");
17. JButton btn3 = new JButton("3");
18. JButton btn4 = new JButton("4");
19. JButton btn5 = new JButton("5");
20. JButton btn6 = new JButton("6");
21. JButton btn7 = new JButton("7");
22. JButton btn8 = new JButton("8");
23. JButton btn9 = new JButton("9");
24.
25. // adding buttons to the frame
26. // since, we are using the parameterless constructor, therfore;
27. // the number of columns is equal to the number of buttons we
28. // are adding to the frame. The row count remains one.
29. frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
30. frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
31. frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
32.
33. // setting the grid layout using the parameterless constructor
34. frameObj.setLayout(new GridLayout());
35.
36.
37. frameObj.setSize(300, 300);
38. frameObj.setVisible(true);
39. }
40.
41. // main method
42. public static void main(String argvs[])
43. {
44. new GridLayoutExample();
45. }
46. }
Output:
Example of GridLayout class: Using GridLayout(int rows, int columns)
Constructor
FileName: MyGridLayout.java
1. import java.awt.*;
2. import javax.swing.*;
3. public class MyGridLayout{
4. JFrame f;
5. MyGridLayout(){
6. f=new JFrame();
7. JButton b1=new JButton("1");
8. JButton b2=new JButton("2");
9. JButton b3=new JButton("3");
10. JButton b4=new JButton("4");
11. JButton b5=new JButton("5");
12. JButton b6=new JButton("6");
13. JButton b7=new JButton("7");
14. JButton b8=new JButton("8");
15. JButton b9=new JButton("9");
16. // adding buttons to the frame
17. f.add(b1); f.add(b2); f.add(b3);
18. f.add(b4); f.add(b5); f.add(b6);
19. f.add(b7); f.add(b8); f.add(b9);
20.
21. // setting grid layout of 3 rows and 3 columns
22. f.setLayout(new GridLayout(3,3));
23. f.setSize(300,300);
24. f.setVisible(true);
25. }
26. public static void main(String[] args) {
27. new MyGridLayout();
28. }
29. }
Output:
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.
Example of FlowLayout class: Using FlowLayout() constructor
FileName: FlowLayoutExample.java
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class FlowLayoutExample
6. {
7.
8. JFrame frameObj;
9.
10. // constructor
11. FlowLayoutExample()
12. {
13. // creating a frame object
14. frameObj = new JFrame();
15.
16. // creating the buttons
17. JButton b1 = new JButton("1");
18. JButton b2 = new JButton("2");
19. JButton b3 = new JButton("3");
20. JButton b4 = new JButton("4");
21. JButton b5 = new JButton("5");
22. JButton b6 = new JButton("6");
23. JButton b7 = new JButton("7");
24. JButton b8 = new JButton("8");
25. JButton b9 = new JButton("9");
26. JButton b10 = new JButton("10");
27.
28.
29. // adding the buttons to frame
30. frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameO
bj.add(b4);
31. frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frame
Obj.add(b8);
32. frameObj.add(b9); frameObj.add(b10);
33.
34. // parameter less constructor is used
35. // therefore, alignment is center
36. // horizontal as well as the vertical gap is 5 units.
37. frameObj.setLayout(new FlowLayout());
38.
39. frameObj.setSize(300, 300);
40. frameObj.setVisible(true);
41. }
42.
43. // main method
44. public static void main(String argvs[])
45. {
46. new FlowLayoutExample();
47. }
48. }
Output:
Example of FlowLayout class: Using FlowLayout(int align) constructor
FileName: MyFlowLayout.java
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. // adding buttons to the frame
16. f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5);
17.
18. // setting flow layout of right alignment
19. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23. }
24. public static void main(String[] args) {
25. new MyFlowLayout();
26. }
27. }
Output:
Java JButton
The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action when the
button is pushed. It inherits AbstractButton class.
JButton class declaration
Let's see the declaration for javax.swing.JButton class.
1. public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:
Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.
what are the commonly used methods, and constructors and write sample code
of the following Swing components?
JLabel JTable
JTextField JList
JTextArea JOptionPane
JPasswordField JColorChooser
JCheckBox JDialog
JRadioButton JMenuItem & JMenu
JComboBox
JButton
Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.
Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener It is used to add the action listener to this object.
a)
JLabel
Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty
string for the title.
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(Icon i) Creates a JLabel instance with the specified image.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.
Methods Description
String getText() t returns the text string that a label displays.
void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X axis.
alignment)
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis.
JTextField
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text and columns.
columns)
JTextField(int columns) Creates a new empty TextField with the specified number of columns.
Methods Description
void addActionListener(ActionListener l) It is used to add the specified action listener to receive
action events from this textfield.
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
void setFont(Font f) It is used to set the current font.
void removeActionListener(ActionListener It is used to remove the specified action listener so that
l) it no longer receives action events from this textfield.
JCheckBox
Constructor Description
JCheckBox() Creates an initially unselected check box button with no
text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it
selected) is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.
Methods Description
AccessibleContext It is used to get the AccessibleContext associated with
getAccessibleContext() this JCheckBox.
protected String paramString() It returns a string representation of this JCheckBox.
JRadioButton
Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified text.
JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.
Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener It is used to add the action listener to this object.
a)
JComboBox
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified
array.
JComboBox(Vector<?> Creates a JComboBox that contains the elements in the specified
items) Vector.
Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is
editable.
void addActionListener(ActionListener It is used to add the ActionListener.
a)
void addItemListener(ItemListener i) It is used to add the ItemListener.
JTable
Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] Creates a table with the specified data.
columns)
JList
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified
array.
JList(ListModel<ary> Creates a JList that displays elements from the specified, non-
dataModel) null, model.
Methods Description
Void addListSelectionListener It is used to add a listener to the list, to be notified
(ListSelectionListener listener) each time a change to the selection occurs.
int getSelectedIndex() It is used to return the smallest selected cell index.
ListModel getModel() It is used to return the data model that holds a list
of items displayed by the JList component.
void setListData(Object[] listData) It is used to create a read-only ListModel from an
array of objects.
JPanel
Constructor Description
JPanel() It is used to create a new JPanel with a double buffer and a flow
layout.
JPanel(boolean It is used to create a new JPanel with FlowLayout and the
isDoubleBuffered) specified buffering strategy.
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout
manager.
JFrame
Constructor Description
JFrame() It constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc) It creates a Frame in the specified
GraphicsConfiguration of a screen device and a blank
title.
JFrame(String title) It creates a new, initially invisible Frame with the
specified title.
JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen device.
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager sets the layout manager for the component.
m)
public void setVisible(boolean b) sets the visibility of the component. It is by default
false.
JPasswordField
Constructor Description
JPasswordField() Constructs a new JPasswordField, with a default document,
null starting text string, and 0 column width.
JPasswordField(int columns) Constructs a new empty JPasswordField with the specified
number of columns.
JPasswordField(String text) Constructs a new JPasswordField initialized with the specified
text.
JPasswordField(String text, int Construct a new JPasswordField initialized with the specified
columns) text and columns.