INTEGRATIVE
PROGRAMMING
TECHNOLOGIES
FOR POLYTECHNIC STUDENTS
HARTATI MASKUR | AZRIND OTHMAN | ROSHILA ABD MUTALIB
Contents
1.0 GRAPHICAL USER INTERFACE (GUI) .................................................................................................. 3
1.1 Abstract Window Toolkit (AWT) fundamentals ............................................................................ 3
1.1.1 Define the use of AWT ........................................................................................................... 3
1.1.2 Explain the AWT hierarchy..................................................................................................... 4
1.1.3 Use AWT in Java programs..................................................................................................... 6
1.2 Create Frame Windows and Menu Bars in Java programs ........................................................... 6
1.2.1 Define the use of Frame in Java programs ............................................................................ 6
1.2.2 Create and set the Frame Windows ...................................................................................... 6
1.2.3 Create Menu Bars in Java Programs ...................................................................................... 9
1.2.4 Write a program with dialog and panels .............................................................................11
1.2.5 Write java programs using the AWT component ................................................................16
1.2.5 Write java programs to set colour and fonts .......................................................................16
2.0 SWING COMPONENTS ....................................................................................................................27
2.1 Use Swing components...............................................................................................................27
2.1.1 Define swing components and identify its use ....................................................................27
2.1.2 Write Java programs using the swing component...............................................................27
2.2 Use Layout manager ...................................................................................................................44
2.2.1 Define the use of layout manager in Java program .............................................................47
2.1.4 Use layout manager in AWT ................................................................................................47
2.1.5 Write Java program using a layout manager .......................................................................47
3.0 EVENT HANDLING ...........................................................................................................................52
3.1 Write program using the Event Handling with GUI components ...............................................52
3.1.1 Define Event Handling and identify its uses ........................................................................52
3.1.2 Explain Event Listener in Java program ...............................................................................54
3.1.3 Summarize events and their respective components and interfaces .................................54
3.1.4 Write program using the Event Handling with GUI components ........................................57
4.0 JAVA DATABASE CONNECTIVITY (JDBC)..........................................................................................66
Integrative Programming Technologies | 1
4.1 Apply JDBC Connectivity .............................................................................................................66
4.1.1 Explain JDBC and ODBC database access.............................................................................66
4.1.2 Identify JDBC driver type......................................................................................................67
4.1.3 Explain JDBC Statement Objects ..........................................................................................72
4.1.4 Use JDBC for database connectivity by applying the appropriate steps .............................82
4.2 Use SQL in JDBC ..........................................................................................................................85
4.2.1 Handling SQL statements in JDBC ........................................................................................85
Integrative Programming Technologies | 2
1.0 GRAPHICAL USER INTERFACE (GUI)
1.1 Abstract Window Toolkit (AWT) fundamentals
1.1.1 Define the use of AWT
AWT stands for Abstract Window Toolkit. It is a platform dependent API used by Java
programmers to create Graphical User Interface (GUI) objects, such as buttons, scroll bars
and windows.
Why AWT is platform dependent? Java AWT calls native platform (Operating systems)
subroutine for creating components such as textbox, checkbox, button etc. For example an
AWT GUI having a button would have a different look and feel across platforms like
windows, Mac OS & Unix, this is because these platforms have different look and feel for
their native buttons and AWT directly calls their native subroutine that creates the button.
In simple, an application build on AWT would look like a windows application when it runs
on Windows, but the same application would look like a Mac application when runs on Mac
OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with 18
packages of 737 classes as of JDK 8). Fortunately, only 2 packages
- java.awt and java.awt.event - are commonly-used.
1. The java.awt package contains the core AWT graphics classes:
o GUI Component classes, such as Button, TextField, and Label.
o GUI Container classes, such as Frame and Panel.
o Layout managers, such as FlowLayout, BorderLayout and GridLayout.
o Custom graphics classes, such as Graphics, Color and Font.
2. The java.awt.event package supports event handling:
o Event classes, such as ActionEvent, MouseEvent, KeyEvent and WindowEvent.
o Event Listener interfaces, such as ActionListener, MouseListener,
MouseMotionListener, KeyListener and WindowListener.
o Event Listener Adapter classes, such as MouseAdapter, KeyAdapter,
and WindowAdapter.
AWT provides a platform-independent and device-independent interface to develop
graphic programs that runs on all platforms, including Windows, Mac OS X, and Unixes.
Integrative Programming Technologies | 3
1.1.2 Explain the AWT hierarchy
Components and containers
All the elements like buttons, Labels, scrollbars etc are known as components. In AWT we
have classes for each component as shown in the above diagram. To have everything placed
on a screen to a particular position, we have to add them to a container. A container is like a
screen wherein we are placing components like buttons, text fields, checkbox etc. In short a
container contains and controls the layout of components. A container itself is a component
(shown in the above hierarchy diagram) thus we can add a container inside container.
AWT Components
Integrative Programming Technologies | 4
Types of containers
As explained above, a container is a place wherein we add components like text field,
button, checkbox etc. There are four types of containers available in AWT: Window, Frame,
Dialog and Panel. As shown in the hierarchy diagram above, Frame and Dialog are
subclasses of Window class.
Window: An instance of the Window class has no border and no title
Dialog: Dialog class has border and title. An instance of the Dialog class cannot exist without
an associated instance of the Frame class.
Panel: Panel does not contain title bar, menu bar or border. It is a generic container for
holding components. An instance of the Panel class provides a container to which to add
components.
Frame: A frame has title, border and menu bars. It can contain several components like
buttons, text fields, scrollbars etc. This is most widely used container while developing an
application in AWT.
Example
Based in the above figure, there are two types of GUI elements:
1. Component: Components are elementary GUI entities, such as Button, Label,
and TextField.
2. Container: Containers, such as Frame and Panel, are used to hold components in a
specific layout (such as FlowLayout or GridLayout). A container can also hold sub-
containers.
Integrative Programming Technologies | 5
In the above figure, there are three containers: a Frame and two Panels. A Frame is the top-
level container of an AWT program. A Frame has a title bar (containing an icon, a title, and the
minimize/maximize/close buttons), an optional menu bar and the content display area.
A Panel is a rectangular area used to group related GUI components in a certain layout. In the
above figure, the top-level Frame contains two Panels. There are five components:
a Label (providing description), a TextField (for users to enter text), and three Buttons (for
user to trigger certain programmed actions).
1.1.3 Use AWT in Java programs
Useful Methods of Component class
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height)
public void setLayout(LayoutManager m) sets the size (width and height) of the
public void setVisible(boolean status) component.
defines the layout manager for the
component.
changes the visibility of the component,
by default false.
1.2 Create Frame Windows and Menu Bars in Java programs
1.2.1 Define the use of Frame in Java programs
The frame in java works like the main window where your components (controls) are added
to develop a application. It has a title bar (containing an icon, a title, the minimize,
maximize/restore-down and close buttons), an optional menu bar, and the content display
area. In the Java AWT, top-level windows are represented by the Frame class.
1.2.2 Create and set the Frame Windows
We can create a GUI using Frame in two ways:
1) By extending Frame class
2) By creating the instance of Frame class
Lets have a look at the example of each one.
Integrative Programming Technologies | 6
Example 1: creating Frame by extending Frame class
import java.awt.*;
/* We have extended the Frame class here,
* thus our class "SimpleExample" would behave
* like a Frame
*/
public class SimpleExample extends Frame{
SimpleExample(){
Button b=new Button("Button!!");
// setting button position on screen
b.setBounds(50,50,50,50);
//adding button into frame
add(b);
//Setting Frame width and height
setSize(500,300);
//Setting the title of Frame
setTitle("This is my First AWT example");
//Setting the layout for the Frame
setLayout(new FlowLayout());
/* By default frame is not visible so
* we are setting the visibility to true
* to make it visible.
*/
setVisible(true);
}
public static void main(String args[]){
// Creating the instance of Frame
SimpleExample fr=new SimpleExample();
}
}
Output:
Integrative Programming Technologies | 7
Example 2: creating Frame by creating instance of Frame class
import java.awt.*;
public class Example2 {
Example2()
{
//Creating Frame
Frame fr=new Frame();
//Creating a label
Label lb = new Label("UserId: ");
//adding label to the frame
fr.add(lb);
//Creating Text Field
TextField t = new TextField();
//adding text field to the frame
fr.add(t);
//setting frame size
fr.setSize(500, 300);
//Setting the layout for the Frame
fr.setLayout(new FlowLayout());
fr.setVisible(true);
}
public static void main(String args[])
{
Example2 ex = new Example2();
}
}
Output:
Integrative Programming Technologies | 8
1. While creating a frame, Following two attributes are must for visibility of
the frame:
o setSize(int width, int height);
o setVisible(true);
2. When you create other components like Buttons, TextFields, etc. Then
you need to add it to the frame by using the method - add(Component's
Object);
3. You can add the following method also for resizing the frame
- setResizable(true);
1.2.3 Create Menu Bars in Java Programs
A menu has a pull-down list of menu items from which the user can select one at a time.
When many options in multiple categories exist for selection by the user, menus are the
best choice since they take less space on the frame. A click on the MenuItem generates an
ActionEvent and is handled by an ActionListener. A Menu and a MenuItem are not
components since they are not subclasses of the java.awt.Component class. They are
derived from the MenuComponent class.
How to add a menu bar, menu and its menu items to the window application.
A menu bar can be created using MenuBar class.
A menu bar may contain one or multiple menus, and these menus are created
using Menu class.
A menu may contain one of multiple menu items and these menu items are created
using MenuItem class.
Integrative Programming Technologies | 9
Example 1: creating MenuBar, Menu and MenuItem
1. import java.awt.*;
2. class AWTMenu extends Frame
3. {
4. MenuBar mbar;
5. Menu menu,submenu;
6. MenuItem m1,m2,m3,m4,m5;
7. public AWTMenu()
8. {
9. // Set frame properties
10. setTitle("AWT Menu"); // Set the title
11. setSize(300,300); // Set size to the frame
12. setLayout(new FlowLayout()); // Set the layout
13. setVisible(true); // Make the frame visible
14. setLocationRelativeTo(null); // Center the frame
15. // Create the menu bar
16. mbar=new MenuBar();
17. // Create the menu
18. menu=new Menu("Menu");
19. // Create the submenu
20. submenu=new Menu("Sub Menu");
21. // Create MenuItems
22. m1=new MenuItem("Menu Item 1");
23. m2=new MenuItem("Menu Item 2");
24. m3=new MenuItem("Menu Item 3");
25. m4=new MenuItem("Menu Item 4");
26. m5=new MenuItem("Menu Item 5");
27. // Attach menu items to menu
28. menu.add(m1);
29. menu.add(m2);
30. menu.add(m3);
31. // Attach menu items to submenu
32. submenu.add(m4);
33. submenu.add(m5);
34. // Attach submenu to menu
35. menu.add(submenu);
36. // Attach menu to menu bar
37. mbar.add(menu);
38. // Set menu bar to the frame
39. setMenuBar(mbar);
40. }
41. public static void main(String args[])
42. {
43. new AWTMenu();
44. }
45. }
Integrative Programming Technologies | 10
Example 2: creating MenuBar, Menu and MenuItem
import java.awt.*;
import java.awt.event.*;
public class menusample
{
public static void main (String arg[])
{
Frame a = new Frame();
MenuBar mb = new MenuBar();
Menu m1 = new Menu ("File");
Menu m2 = new Menu ("Edit");
Menu m3 = new Menu ("Help");
MenuItem m11 = new MenuItem ("Save");
MenuItem m12 = new MenuItem ("Save as..");
Menu m13 = new Menu ("Undo/Redo");
MenuItem m14 = new MenuItem ("Undo");
MenuItem m15 = new MenuItem ("Redo");
mb.add(m1);
mb.add(m2);
mb.add(m3);
m1.add(m11);
m1.add(m12);
m2.add(m13);
m13.add(m14);
m13.add(m15);
a.setMenuBar(mb);
a.setSize(400,400);
a.setVisible(true);
}}
Output
Integrative Programming Technologies | 11
1.2.4 Write a program with dialog and panels
Dialog
A Dialog is a top-level window with a title and a border that is typically 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.
2 types of Dialog windows in AWT:
- Modal Dialog window
• When a modal dialog window is active, all the user inputs are directed to it and all the
other parts of application are inaccessible until this modal dialog is closed.
- Modeless Dialog window
• When a modeless dialog window is active, the other parts of application are still
accessible as normal and inputs can be directed to them, without needing to close this
modeless dialog window.
Example 1: Creating AWT Dialog
1. import java.awt.*;
2. import java.awt.event.*;
3. public class DialogExample {
4. private static Dialog d;
5. DialogExample() {
6. Frame f= new Frame();
7. d = new Dialog(f , "Dialog Example", true);
8. d.setLayout( new FlowLayout() );
9. Button b = new Button ("OK");
10. b.addActionListener ( new ActionListener()
11. {
12. public void actionPerformed( ActionEvent e )
13. {
14. DialogExample.d.setVisible(false);
15. }
16. });
17. d.add( new Label ("Click button to continue."));
18. d.add(b);
19. d.setSize(300,300);
20. d.setVisible(true);
21. }
22. public static void main(String args[])
23. {
24. new DialogExample();
25. }
26. }
Integrative Programming Technologies | 12
Output:
Example 2: Creating AWT Dialog (Modal Dialog)
1. import java.awt.*;
2. import java.awt.event.*;
3. class Dialog2 {
4. public static void main(String[] args) {
5. final Frame frame1 = new Frame("DialogExample");
6. frame1.setLayout(new FlowLayout());
7. Button button = new Button("This is Dialog Example");
8. button.addActionListener(new ActionListener() {
9. public void actionPerformed(ActionEvent e) {
10. Dialog dialog = new Dialog(frame1, "Application-Dialog",
11. Dialog.ModalityType.APPLICATION_MODAL);
12. dialog.setBounds(200, 150, 200, 150);
13. dialog.setVisible(true);
14. }
15. });
16. frame1.add(button);
17. frame1.setBounds(100, 100, 200, 150);
18. frame1.setVisible(true);
19. }
20. }
Integrative Programming Technologies | 13
Output:
Panels
When writing a GUI application, the GUI portion can become quite complex. To manage the
complexity, GUIs are broken down into groups of components. Each group generally
provides a unit of functionality.
A Panel is a rectangular Container whose sole purpose is to hold and manage components
within a GUI. The Panel is a simplest container class. It provides space in which an
application can attach any other component, including other panels.
It uses FlowLayout as default layout manager. How ever, your application can utilize
multiple layout strategies with Panels. Panels play a very important role in layout
management.
The layout managers are used to automatically decide the position and size of the added
components. In the absence of a layout manager, the position and size of the
components have to be set manually. The setBounds() method is used in such a situation
to set the position and size. To specify the position and size of the components manually,
the layout manager of the frame can be null.
setBounds()
The setBounds() method needs four arguments. The first two arguments are x and y
coordinates of the top-left corner of the component, the third argument is the width of
the component and the fourth argument is the height of the component.
Syntax
setBounds(int x-coordinate, int y-coordinate, int width, int height)
.
Integrative Programming Technologies | 14
Example 1: Creating Panel
1. import java.awt.*;
2. public class PanelExample {
3. PanelExample()
4. {
5. Frame f= new Frame("Panel Example");
6. Panel panel=new Panel();
7. panel.setBounds(40,80,200,200);
8. panel.setBackground(Color.gray);
9. Button b1=new Button("Button 1");
10. b1.setBounds(50,100,80,30);
11. b1.setBackground(Color.yellow);
12. Button b2=new Button("Button 2");
13. b2.setBounds(100,100,80,30);
14. b2.setBackground(Color.green);
15. panel.add(b1); panel.add(b2);
16. f.add(panel);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String args[])
22. {
23. new PanelExample();
24. }
25. }
26. frame1.add(button);
27. frame1.setBounds(100, 100, 200, 150);
28. frame1.setVisible(true);
29. }
30. }
Integrative Programming Technologies | 15
Output:
1.2.5 Write java programs using the AWT component
Some types of components
Labels
This class is a Component which displays a single line of text.
Labels are read-only. That is, the user cannot click on a label to edit the text it
displays.
Text can be aligned within the label.
Integrative Programming Technologies | 16
import java.awt.*;
class LabelExample{
public static void main(String args[]){
Frame f= new Frame("Label Example");
Label l1,l2;
l1=new Label("First Label.");
l1.setBounds(50,100, 100,30);
l2=new Label("Second Label.");
l2.setBounds(50,150, 100,30);
f.add(l1); f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}}
Buttons
This class represents a push-button which displays some specified text.
When a button is pressed, it notifies its Listeners. (More about Listeners in the next
chapter).
To be a Listener for a button, an object must implement the ActionListener Interface.
import java.awt.*;
public class ButtonExample {
public static void main(String[] args) {
Frame f=new Frame("Button Example");
Button b=new Button("Click Here");
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Integrative Programming Technologies | 17
Checkbox
This class represents a GUI checkbox with a textual label.
The Checkbox maintains a boolean state indicating whether it is checked or not.
When the checkbox is checked then its state is “on” (true) else it is “off”(false).
If a Checkbox is added to a CheckBoxGroup, it will behave like a radio button.
import java.awt.*;
public class CheckboxExample
{ public static void main(String args[])
{
Frame f= new Frame("Checkbox Example");
Checkbox cb1 = new Checkbox("C++");
cb1.setBounds(100,100, 50,50);
Checkbox cb2 = new Checkbox("Java", true);
cb2.setBounds(100,150, 50,50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Integrative Programming Technologies | 18
RadioButton
Is a group of checkboxes, where only one of the items in the group can be selected
at any one time.
import java.awt.*;
public class CheckboxGroupExample
{ public static void main(String args[])
{
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg,false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
ScrollPane
A container class which implements automatic horizontal and/or vertical scrolling for
a single child components.
The display policy for the scrollbars can be set to : as
Needed : scrollbars created and shown only when needed by scrollpane
Always : Scrollbars created and always shown by the scrollpane
Never : scrollbars never created or shown by the scrollpane
Integrative Programming Technologies | 19
import java.awt.*;
import java.awt.event.WindowAdapter;
public class AWTScrollPane{
public static void main(String[] args) {
Frame frame = new Frame("AWTScrollPane");
frame.setLayout(new BorderLayout());
ScrollPane SC = new
ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
SC.add(new ScrollPane());
frame.add(SC, BorderLayout.CENTER);
frame.setSize(300, 250);
frame.setVisible(true);
}
}
List
This class is a Component which displays a list of Strings.
The list is scrollable, if necessary.
Sometimes called Listbox in other languages.
Lists can be set up to allow single or multiple selections.
The list will return an array indicating which Strings are selected
Integrative Programming Technologies | 20
import java.awt.*;
public class ListExample
{
public static void main(String args[])
{
Frame f= new Frame(“List Example”);
List l1=new List(5);
l1.setBounds(100,100, 75,75);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
f.add(l1);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Choice
This class represents a dropdown list of Strings.
Similar to a list in terms of functionality, but displayed differently.
Only one item from the list can be selected at one time and the currently selected
element is displayed.
Integrative Programming Technologies | 21
import java.awt.*;
public class ChoiceExample
{
public static void main(String args[])
{
Frame f= new Frame(“Choice Example”);
Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
TextField
This class displays a single line of optionally editable text.
This class inherits several methods from TextComponent.
This is one of the most commonly used Components in the AWT
Integrative Programming Technologies | 22
import java.awt.*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome to Java.");
t1.setBounds(50,100, 200,30);
t2=new TextField();
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}}
TextArea
This class displays multiple lines of optionally editable text.
This class inherits several methods from TextComponent.
TextArea also provides the methods: appendText(), insertText() and replaceText()
import java.awt.*;
public class TextAreaExample
{
public static void main(String args[])
{
Frame f= new Frame("TextArea Example");
TextArea area=new TextArea("Welcome to java");
area.setBounds(10,30, 300,300);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Integrative Programming Technologies | 23
1.2.6 Write java programs to set colour and fonts
• AWT Colors give extra effects to application and make them more appealing. In AWT
Colors, you can learn about:
– Fonts and its attributes.
– AWT Colors and models in Colors.
• use two classes java.awt.Color and java.awt.Font.
• Font object can be created using the syntax:
Font f = new Font(String fontName, int fontStyle, int fontSize);
• Example:
Font f = new Font("Monospaced", Font.ITALIC, 12);
• There are several font settings in the Font class including PLAIN, BOLD, ITALIC and 13
different colors in the Color class (listed below).
– BLACK – MAGENTA
– BLUE – ORANGE
– CYAN – PINK
– DARK_GRAY – RED
– GRAY – WHITE
– GREEN – YELLOW
– LIGHT_GRAY
• There are four styles for displaying fonts in Java : plain, bold, italic and bold italic.
Three class constants are used to represent font styles:
public static finat int BOLD The BOLD constant represents a boldface font
public static finat int ITALIC The ITALIC constant represents a italic font
public static finat int PLAIN The PLAIN constant represents a plain or normal
font
Integrative Programming Technologies | 24
Example 1 : Set background color in Panel
import java.awt.*;
public class PanelsDemo extends Frame {
public static void main(String args[]){
Frame f= new Frame("Learning panel");
// creating panels Integrative Programming Technologies | 25
Panel p1 = new Panel();
Panel p2 = new Panel();
// setting some properties
p1.setBackground(Color.yellow);
p2.setBackground(Color.magenta);
// create some components
Button b1 = new Button("OK 1");
Button b2 = new Button("OK 2");
Button b3 = new Button("OK 3");
Button b4 = new Button("OK 4");
Button b5 = new Button("OK 5");
Button b6 = new Button("OK 6");
// add 3 buttons to Panel p1
p1.add(b1);
p1.add(b2);
p1.add(b3);
// add 3 buttons to Panel p2
p2.add(b4);
p2.add(b5);
p2.add(b6);
// add panels to frame
f.add(p1, "North");
f.add(p2, "South");
//setTitle("Learning Panels");
f.setSize(300, 300);
f.setVisible(true);
}//end of constructor PanelsDemo()
}//end of class PanelsDemo
Example 2 : Set types, size and styles of fonts and setforeground
import java.awt.*;
public class AttractiveStrings extends Frame{
Label s1, s2, s3;
Font f1, f2, f3;
public AttractiveStrings() {
setTitle("Attractive Strings");
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout());
f1 = new Font("DialogInput", Font.BOLD, 20);
s1 = new Label ("Malaysia");
s1.setFont(f1);
s1.setForeground(Color.BLUE);
add(s1);
f2 = new Font("SansSerif", Font.ITALIC, 22);
s2 = new Label ("Singapore");
s2.setFont(f2);
s2.setForeground(Color.RED);
add(s2);
f3 = new Font("Monospaced", Font.BOLD + Font.ITALIC, 25);
s3 = new Label ("Thailand");
s3.setFont(f3);
s3.setForeground(Color.GREEN);
add(s3);
}
public static void main(String args[]){
new AttractiveStrings();
}
}
Integrative Programming Technologies | 26
2.0 SWING COMPONENTS
2.1 Use Swing components
2.1.1 Define swing components and identify its use
Java, provides a rich set of libraries to create Graphical User Interface (GUI), to make it
work independently on different platforms. Swing is definitely the one which is most
popular used because of its properties of light-weight, rich-control, easy-customizable.
Before Java Swing, Abstract Windowing Toolkit (AWT) is the one to create different
GUIs. However, because of its disadvantages on platform-dependent, heavy-weight,
few-components, it has been replaced by Java Swing, which is built on top of the AWT
package. Note that some AWT components remain in Java and in some situations it
must be used.
Swing was developed to provide a more sophisticated set of GUI components than the
earlier Abstract Window Toolkit (AWT). Provides a look and feel for the program.
“Look” refers to the appearance of GUI widgets and “feel” refers to the way the
widgets behave.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.The swing components
use ‘J’ as their signature merged with origin name of the AWT component.
Difference between AWT and Swing
Integrative Programming Technologies | 27
Swing Hierarchy
Integrative Programming Technologies | 28
Components and containers
A component is an independent visual control. Swing Framework contains a large set of
components which provide rich functionalities and allow high level of customization. All the
components in swing like JButton, JComboBox, JList, JLabel are inherited from the
JComponent class which can be added to the container classes. All these components are
lightweight components. This class provides some common functionality like pluggable look
and feel, support for accessibility, drag and drop, layout, etc.
A container holds a group of components. It provides a space where a component can be
managed and displayed. Containers are of two types:
1. Top level Containers
o It inherits Component and Container of AWT.
o It cannot be contained within other containers.
o Heavyweight.
o Example: JFrame, JDialog, JApplet
2. Lightweight Containers
o It inherits JComponent class.
o It is a general purpose container.
o It can be used to organize related components together.
o Example: JPanel
JFrame: used for the application's main window (with an icon, a title,
minimize/maximize/close buttons, an optional menu-bar, and a content-pane), as
illustrated.
JDialog: used for secondary pop-up window (with a title, a close button, and a content-
pane).
JApplet: used for the applet's display-area (content-pane) inside a browser’s window.
Integrative Programming Technologies | 29
JMenu
JLabel JTextField
JRadioButton JTextArea
JCheckBox JComboBox
JButton
Application demonstrates many of Java’s Swing GUI components
2.1.2 Write Java programs using the swing component
JFrame
There are two ways to create a frame:
o By creating the object of Frame class (association)
o By extending Frame class (inheritance)
Integrative Programming Technologies | 30
Example 1: creating JFrame by extending Frame class
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13. }
14. public static void main(String[] args) {
15. new Simple2();
16. }}
Example 2: creating JFrame by creating instance of Frame class
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15. }
16. }
Integrative Programming Technologies | 31
JPanel
JPanel is a popular container to hold different components. We can use JPanel to
add multiple components to a window. It could be set and added by using the code
similar to the following:
1 JPanel panel = new JPanel();
2 frame.add(panel);
1. import javax.swing.*;
2. import java.awt.Color;
3. public class PanelExample_Extended extends JFrame{
4. PanelExample_Extended(){
5. // We create a bottom JPanel to place everything on.
6. JPanel totalGUI = new JPanel();
7. // We set the Layout Manager to null so we can
8. //manually place the Panels.
9. totalGUI.setLayout(null);
10. // Now we create a new panel, size it, shape it,color
11. // it red.then add it to the bottom JPanel.
12. JPanel redPanel = new JPanel();
13. redPanel.setBackground(Color.red);
14. redPanel.setLocation(10, 10);
15. redPanel.setSize(50,50);
16. totalGUI.add(redPanel);
17.
18. JPanel bluePanel = new JPanel();
19. bluePanel.setBackground(Color.blue);
20. bluePanel.setLocation(220, 10);
21. bluePanel.setSize(50, 50);
22. totalGUI.add(bluePanel);
23.
24. setTitle("Example of 3 panels");
25. add(totalGUI);
26. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
27. setSize(290, 100);
28. setVisible(true);
29. }
30.
31. public static void main(String[] args) {
32. new PanelExample_Extended();
33. } Integrative Programming Technologies | 32
34. }
JLabel
The object of JLabel class is a component for placing text in a container.
It is used to display a single line of read only text. The text can be changed by an
application but a user cannot edit it directly. It inherits JComponent class.
1. import javax.swing.*; Example 1
2. public class ExampleLabel{
3. public static void main(String args[])
4. {
5. JFrame a = new JFrame("Label Example");
6. JLabel b1;
7. b1 = new JLabel("welcome to java");
8. b1.setBounds(80,80,110,80);
9. a.add(b1);
10. a.setSize(400,400);
11. a.setLayout(null);
12. a.setVisible(true);
13. a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14. }
15. }
1. import javax.swing.*; Example 2
2. import java.awt.*;
3. public class LabelEx extends JFrame {
4. public LabelEx() {
5. Jpanel p1 = new Jpanel();
6. JLabel one = new JLabel("Hello, welcome Java Programming");
7. one.setFont(new Font("Serif", Font.PLAIN, 30));
8. one.setForeground(Color.BLUE);
9. JLabel two = new JLabel (new ImageIcon("C:/users/java.png"));
10. p1.add(one);
11. p1.add(two);
12. add(p1);
13. setTitle("JLabel");
14. setSize(500,400);
15. setVisible(true);
16. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. }
18. public static void main(String[] args) {
19. new LabelEx(); Integrative Programming Technologies | 33
20. } }
JButton
JButton is an implementation of a “push” button.
It can be pressed and configured to have different actions, using the event listener.
For this part, we’ll discuss it in the chapter 3.
1. import javax.swing.*; Example 1
2. public class ButtonExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton("Click Here");
6. b.setBounds(50,100,95,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. } }
1. import javax.swing.*; Example 2
2. import java.awt.*;
3. public class ImageIconButtonEx extends JFrame {
4. public ImageIconButtonEx() {
5. Jpanel p1 = new Jpanel();
6. ImageIcon saveIcon = new ImageIcon("C:/user/save.png");
7. ImageIcon homeIcon = new ImageIcon("C:/user/home.png");
8. JButton quitBtn = new JButton("Quit");
9. JButton saveBtn = new JButton(saveIcon);
10. JButton homeBtn = new JButton("Home",homeIcon);
11. cp.add(quitBtn);
12. cp.add(saveBtn);
13. cp.add(homeBtn);
14. setTitle("JButtons");
15. setSize(500,200);
16. setVisible(true);
17. }//end of constructor
18. public static void main(String[] args) {
19. new ImageIconButtonEx();
20. }
21. }//end of class ImageIconButtonEx
Integrative Programming Technologies | 34
JCheckBox
The JCheckBox class is used to create a checkbox.
It is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
1. import javax.swing.*;
2. public class CheckBoxExample
3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new JCheckBox("C++");
7. checkBox1.setBounds(100,100, 50,50);
8. JCheckBox checkBox2 = new JCheckBox("Java", true);
9. checkBox2.setBounds(100,150, 50,50);
10. f.add(checkBox1);
11. f.add(checkBox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}
Integrative Programming Technologies | 35
JRadioButton
The JRadioButton class is used to create a radio button.
It is used to choose one option from multiple options.
It should be added in ButtonGroup to select one radio button only.
1. import javax.swing.*;
2. public class RadioButtonExample {
3. JFrame f;
4. RadioButtonExample(){
5. f=new JFrame();
6. JRadioButton r1=new JRadioButton("A) Male");
7. JRadioButton r2=new JRadioButton("B) Female");
8. r1.setBounds(75,50,100,30);
9. r2.setBounds(75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. bg.add(r1);bg.add(r2);
12. f.add(r1);f.add(r2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new RadioButtonExample();
19. }
20. }
Integrative Programming Technologies | 36
JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or
off.
1. import java.awt.FlowLayout;
2. import java.awt.event.ItemEvent;
3. import java.awt.event.ItemListener;
4. import javax.swing.JFrame;
5. import javax.swing.JToggleButton;
6.
7. public class JToggleButtonExample extends JFrame implements I
temListener {
8. public static void main(String[] args) {
9. new JToggleButtonExample();
10. }
11. private JToggleButton button;
12. JToggleButtonExample() {
13. setTitle("JToggleButton with ItemListener Example");
14. setLayout(new FlowLayout());
15. setJToggleButton();
16. setAction();
17. setSize(200, 200);
18. setVisible(true);
19. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. private void setJToggleButton() {
22. button = new JToggleButton("ON");
23. add(button);
24. }
25. private void setAction() {
26. button.addItemListener(this);
27. }
28. public void itemStateChanged(ItemEvent eve) {
29. if (button.isSelected())
30. button.setText("OFF");
31. else
32. button.setText("ON");
33. }
34. }
Integrative Programming Technologies | 37
JScrollPane
A JscrollPane is used to make scrollable view of a component.
When screen size is limited, we use a scroll pane to display a large component or a
component whose size can change dynamically.
1. import javax.swing.*;
2. public class JScrollContainer{
3. public static void main(String[] args) {
4. String st = "Math_calculs_coordinate\n"
5. + "Computer_Operator_Programer\n"
6. + "Physics_Laboratry\n"
7. + "Chemestru\n"
8. + "Biology"
9. + "Civics\n" +"History"
10. + "Hindi\n" + "English\n"
11. + "Tally" + "Coordinate\n"
12. + "Trigonometry" + "ram is a good boy\n"
13. + "He has four cars and two computers.";
14. JFrame frame = new JFrame("Creating a JScrollPane Container");
15. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16. JPanel panel = new JPanel();
17. JTextArea area = new JTextArea(st,5,6);
18. JScrollPane spane = new JScrollPane(area);
19. panel.add(spane);
20. frame.add(panel);
21. frame.setSize(400,400);
22. frame.setVisible(true);
23. }
24. }
Integrative Programming Technologies | 38
JTextField
The object of a JTextField class is a text component that allows the editing of a single
line text. It inherits JTextComponent class.
It is an input area where the user can type in characters.
1. import javax.swing.*;
2. class TextFieldExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("TextField Example");
7. JTextField t1,t2;
8. t1=new JTextField("Welcome to our class.");
9. t1.setBounds(50,100, 200,30);
10. t2=new JTextField("Swing Tutorial");
11. t2.setBounds(50,150, 200,30);
12. f.add(t1); f.add(t2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
JPasswordField
The object of a JPasswordField class is a text component specialized for password
entry.
It allows the editing of a single line of text. It inherits JTextField class.
1. import javax.swing.*;
2. public class PasswordFieldExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Password Field Example");
5. JPasswordField value = new JPasswordField();
6. JLabel l1=new JLabel("Password:");
7. l1.setBounds(20,100, 80,30);
8. value.setBounds(100,100,100,30);
9. f.add(value); f.add(l1);
10. f.setSize(300,300);
11. f.setLayout(null);
12. f.setVisible(true);
13. }
14. }
Integrative Programming Technologies | 39
JTextArea
The object of a JTextArea class is a multi line region that displays text.
It allows the editing of multiple line text. It inherits JTextComponent class
1. import javax.swing.*;
2. public class jTextAreaExample
3. {
4. jTextAreaExample(){
5. JFrame f= new JFrame();
6. JTextArea area=new JTextArea("Welcome to our class");
7. area.setBounds(10,30, 200,200);
8. f.add(area);
9. f.setSize(300,300);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public static void main(String args[])
14. {
15. new jTextAreaExample();
16. }}
Integrative Programming Technologies | 40
JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message
dialog box, confirm dialog box and input dialog box.
These dialog boxes are used to display information or get input from the user. The
JOptionPane class inherits JComponent class.
Methods Description
static void showMessageDialog(Component It is used to create an information-
parentComponent, Object message) message dialog titled "Message".
static void showMessageDialog(Component It is used to create a message dialog
parentComponent, Object message, String with given title and messageType.
title, int messageType)
static int showConfirmDialog(Component It is used to create a dialog with the
parentComponent, Object message) options Yes, No and Cancel; with the
title, Select an Option.
static String showInputDialog(Component
parentComponent, Object message) It is used to show a question-message
dialog requesting input from the user
parented to parentComponent.
Integrative Programming Technologies | 41
Example 1 : showMessageDialog()
1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. JOptionPane.showMessageDialog(f,"Hello, Welcome to Javat
point.");
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }
Example 2 : showMessageDialog()
1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. JOptionPane.showMessageDialog(f,"Successfully Updated.",
"Alert",JOptionPane.WARNING_MESSAGE);
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }
Integrative Programming Technologies | 42
Example 3 : showInputDialog()
1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. String name=JOptionPane.showInputDialog(f,"Enter Name");
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }
Example 4 : showConfirmDialog()
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class OptionPaneExample extends WindowAdapter{
4. JFrame f;
5. OptionPaneExample(){
6. f=new JFrame();
7. f.addWindowListener(this);
8. f.setSize(300, 300);
9. f.setLayout(null);
10. f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
11. f.setVisible(true);
12. }
13. public void windowClosing(WindowEvent e) {
14. int a=JOptionPane.showConfirmDialog(f,"Are you sure?");
15. if(a==JOptionPane.YES_OPTION){
16. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. }
18. }
19. public static void main(String[] args) {
20. new OptionPaneExample();
21. }
22. }
Integrative Programming Technologies | 43
JComboBox
Combo box is a combination of text fields and drop-down list. You can choose one
and only one element from the list.
.JComboBox component is used to create a combo box in Swing.
1. import javax.swing.*;
2. public class ComboBoxExample {
3. JFrame f;
4. ComboBoxExample(){
5. f=new JFrame("ComboBox Example");
6. String country[]={"India","Aus","U.S.A","England","Newze
aland"};
7. JComboBox cb=new JComboBox(country);
8. cb.setBounds(50, 50,90,20);
9. f.add(cb);
10. f.setLayout(null);
11. f.setSize(400,500);
12. f.setVisible(true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. }
17. }
Integrative Programming Technologies | 44
JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking
on a tab with a given title or icon.
1. import javax.swing.*;
2. public class TabbedPaneExample {
3. JFrame f;
4. TabbedPaneExample(){
5. f=new JFrame();
6. JTextArea ta=new JTextArea(200,200);
7. JPanel p1=new JPanel();
8. p1.add(ta);
9. JPanel p2=new JPanel();
10. JPanel p3=new JPanel();
11. JTabbedPane tp=new JTabbedPane();
12. tp.setBounds(50,50,200,200);
13. tp.add("main",p1);
14. tp.add("visit",p2);
15. tp.add("help",p3);
16. f.add(tp);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String[] args) {
22. new TabbedPaneExample();
23. }}
Integrative Programming Technologies | 45
JMenu
In Java, Swing toolkit contains a JMenuBar, JMenu and JMenuItem Class.
The JMenuBar class is used for displaying menubar on the frame.
The JMenu Object is used for pulling down the components of the menu bar.
The JMenuItem Object is used for adding the labelled menu item.
1. import javax.swing.*;
2. class SMenuDemo1
3. {
4. JMenu m_menu, m_submenu;
5. JMenuItem menu_i1, menu_i2, menu_i3, menu_i4, menu_i5;
6. SMenuDemo1()
7. {
8. JFrame menu_f= new JFrame("Menu and MenuItem Example");
9. JMenuBar menu_mb=new JMenuBar();
10. m_menu=new JMenu("Menu");
11. m_submenu=new JMenu("Sub Menu");
12. menu_i1=new JMenuItem("Red");
13. menu_i2=new JMenuItem("Pink");
14. menu_i3=new JMenuItem("Black");
15. menu_i4=new JMenuItem("Green");
16. menu_i5=new JMenuItem("White");
17. m_menu.add(menu_i1);
18. m_menu.add(menu_i2);
19. m_menu.add(menu_i3);
20. m_submenu.add(menu_i4);
21. m_submenu.add(menu_i5);
22. m_menu.add(m_submenu);
23. menu_mb.add(m_menu);
24. menu_f.setJMenuBar(menu_mb);
25. menu_f.setSize(500,500);
26. menu_f.setLayout(null);
27. menu_f.setVisible(true);
28. }
29. public static void main(String args[])
30. {
31. new SMenuDemo1();
32. }}
Integrative Programming Technologies | 46
2.2 Use Layout manager
2.2.1 Define the use of layout manager in Java program
Layout means the arrangement of components within the container. In other way we can
say that placing the components at a particular position within the container. The task of
layouting the controls is done automatically by the Layout Manager.
The layout manager automatically positions all the components within the container. If we
do not use layout manager then also the components are positioned by the default layout
manager.
2.1.4 Use layout manager in AWT
There are some classes that represent the layout managers.
The Abstract Windowing Toolkit (AWT) has the following five layout managers:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
Some of these are used in the swing:
javax.swing.BoxLayout
javax.swing.ScrollPanelLayout
javax.swing.GroupLayout
javax.swing.SpringLayout
and so on
But for our chapter, we will discuss only four layout managers. There are FlowLayout
manager, GridLayout manager, BorderLayout manager and BoxLayout manager.
2.1.5 Write Java program using a layout manager
FlowLayout
Used to arrange the components in a line, one after another (in a flow).
Default layout of applet or panel.
Components are added left-to-right. If no room, a new row is started
Components are made as small as possible
You can align the components left, right, or center (default).
Integrative Programming Technologies | 47
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.
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. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
16.
17. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
18. //setting flow layout of right alignment
19.
20. f.setSize(300,300);
21. f.setVisible(true);
22. }
23. public static void main(String[] args) {
24. new MyFlowLayout();
25. }
26. }
27.
Integrative Programming Technologies | 48
GridLayout
Used to arrange the components in rectangular grid. One component is displayed in
each rectangle.
GridLayout(rows, columns)
All sections of the grid are equally sized and as large as possible.
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
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
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. JButton b6=new JButton("6");
15. JButton b7=new JButton("7");
16. JButton b8=new JButton("8");
17. JButton b9=new JButton("9");
18.
19. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
20. f.add(b6);f.add(b7);f.add(b8);f.add(b9);
21.
22. f.setLayout(new GridLayout(3,3));
23. //setting grid layout of 3 rows and 3 columns
24.
25. f.setSize(300,300);
26. f.setVisible(true);
27. }
28. public static void main(String[] args) {
29. new MyGridLayout();
30. } } Integrative Programming Technologies | 49