You are on page 1of 25

UNIT-2(DESIGN USER INTERFACE)

 AWT is used for creating GUI in Java.


 AWT components are heavy weight. It means AWT components take more system
resources like memory and processor time.
 All the classes of AWT are extended to form new classes and a new class library is
created. This library is called JFC (Java Foundation Classes).

Swing in java is part of JFC which is lightweight and platform independent. It is used for
creating window based applications. It includes components like button, scroll bar, text field etc.
Putting together all these components makes a graphical user interface.
 Java Foundation Classes (JFC):
 JFC is an extension of original AWT.
 It contains classes that are completely portable, since the entire JFC is developed in pure
Java.
 Some of the features of JFC are:
1. JFC components are light-weight: Means they utilize minimum resources. 2. JFC
components have same look and feel on all platforms. Once a component is created, it
looks same on any OS.
3. JFC offers “pluggable look and feel” feature, which allows the programmer to change
look and feel as suited for platform
4. JFC does not replace AWT, but JFC is an extension to AWT.
So, JFC represents class library developed in pure Java which is an extension to AWT and swing
is one package in JFC, which helps to develop GUIs and the name of the package is import
javax.swing.*; Here x represents that it is an ‘extended package’ whose classes are derived from
AWT package. The classes in the javax.swing package begins with the letter ‘J’. So in a
javax.swing package, we will have classes like JButton, JFrame, JTextField, JTextArea, etc.

The main features of Swing are:

1. Swing is written in pure Java (except a few classes) and therefore is 100% portable.
2. Swing components are lightweight. The AWT components are heavyweight (in terms of
system resource utilization).
3. Swing components support pluggable look-and-feel.

4. Swing supports mouse-less operation, i.e., it can operate entirely using keyboard.

5. Swing components support "tool-tips".

6. Swing components are JavaBeans – a Component-based Model used in Visual


Programming (like Visual Basic). You can drag-and-drop a Swing component into a
"design form" using a "GUI builder" and double-click to attach an event handler.
7. Swing application uses AWT event-handling classes (in package java.awt.event). Swing
added some new classes in package javax.swing. Event, but they are not frequently used.
8. Swing application uses AWT's layout manager (such as FlowLayout and BorderLayout in
package java.awt). It added new layout managers, such as springs, Struts,
and BoxLayout (in package javax.swing).
9. Swing implements double-buffering and automatic repaint batching for smoother screen
repaint.
10. Swing introduces JLayeredPane and JInternalFrame for creating Multiple Document
Interface (MDI) applications.
11. Swing supports floating toolbars (in JToolBar), splitter control, "undo".
MVC Architecture:
In MVC terminology,
 Model corresponds to the state information associated with the component (data). For
example, in the case of a check box, the model contains a field that indicates if the box is
checked or unchecked.
 The view visual appearance of the component based upon model data.
 The controller acts as an interface between view and model. It intercepts all the requests
i.e. receives input and commands to Model / View to change accordingly.
Difference between AWT and Swings:
.
Web-browser support Applet portability: A plug-in is required Do not support features like icon
and tool tip. It supports. The default layout manager for applet: flow and frame is border layout.
The default layout manager
AWT Swing
Heavy weight Light weight
Look and feel is OS based Look and feel is OS independent
Not pure Java based Pure Java based
Applet portability: Web-browser support Applet portability: A plug-in is required
Do not support features like icon and tool tip. It supports.
The default layout manager for applet: flow The default layout manager for content pane
and frame is border layout. is border layout.
All the components in swing like JButton, JComboBox, JList, and JLabel are inherited from the
JComponent class which can be added to the container classes. Containers are the windows like
frame and dialog boxes. Basic swing components are the building blocks of any GUI application.
Methods like setLayout override the default layout in each container. Containers like JFrame and
JDialog can only add a component to itself.
Some of the important classes of Swing API are as follows:
 JWindow: The JWindow class of Swing inherits the Window class directly. The
JWindow class uses ‘BorderLayout’ as the default layout.
 JPanel: JPanel is a descendent of JComponent class and is on similar lines to AWT class
Panel and has ‘FlowLayout’ as the default layout.
 JFrame: JFrame descends from the Frame class. The components added to the Frame are
called contents of the Frame.
 JLabel: JLabel class is a subclass of the JComponent. It is used to create text labels in
the application.
 JButton: The push-button functionality in Swing is provided by JButton. We can
associate a string, an icon, or both with the JButton object.
 JTextField: JTextField class provides a text field in which we can edit a single line of
text.
Java Swing Components
A component can be defined as a control that can be represented visually and is usually
independent. It has got a specific functionality and is represented as an individual class in Swing
API.For example, class JButton in swing API is a button component and provides the
functionality of a button.

Container Class
Containers are an integral part of SWING GUI components. A container provides a space where
a component can be located. A Container in AWT is a component itself and it provides the
capability to add a component to itself. Following are certain noticeable points to be considered.

 Sub classes of Container are called as Container. For example, JPanel, JFrame and
JWindow.
 Container can add only a Component to itself.
 A default layout is present in each container which can be overridden
using setLayout method.

Any class which has other components in it is called as a container class. For building GUI
applications at least one container class is necessary.
Following are the three types of container classes:
1. Panel – It is used to organize components on to a window

2. Frame – A fully functioning window with icons and titles

3. Dialog – It is like a pop up window but not fully functional like the frame

There are two groups of GUI elements:

1. Component (Widget, Control): Components are elementary GUI entities, such


as Button, Label, and TextField. They are also called widgets, controls in other graphics
systems.
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.
3. 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).

Frame classes:-The java.awt.Frame component is a Windows graphics system which has a


title bar and borders, behaving like a normal GUI window. How a subclass of
java.awt.Container is can contain other components being that its primary purpose. The
default alignment components added to a Java.awt.BorderLayout.
When working with Frame objects, the following steps are basically followed to get a
window to appear on the screen.

1. Create an object of type Frame.

2. Give the Frame object a size using setSize () method.

3. Make the Frame object appear on the screen by calling setVisible () method.

4. In order to close the window by clicking the close(X) button, you will have to insert the
code for window closing event.

Frame ()

Constructs a new instance, invisible and without title.

Frame (String)

Constructs a new instance, invisible and entitled given

dispose ()

Releases the resources used by this component

getTitle ()

Gets the title of the window.

isResizable ()

Determines whether or not the window is sizable.

setMenuBa (MenuBar)

Adds the specified menu bar of the window.

setResizable (Boolean)
Specifies whether or not the window is sizable.

setTitle (String)

Specifies the window title.

import java.awt.FlowLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

public class JFrameExample {

public static void main(String s[]) {

JFrame frame = new JFrame("JFrame Example");

JPanel panel = new JPanel();

panel.setLayout(new FlowLayout());

JLabel label = new JLabel("JFrame By Example");

JButton button = new JButton();

button.setText("Button");

panel.add(label);

panel.add(button);
frame.add(panel);

frame.setSize(200, 300);

frame.setLocationRelativeTo(null);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

The following FrameDemo code shows how to create and set up a frame.

//1. Create the frame.

JFrame frame = new JFrame("FrameDemo");

//2. Optional: What happens when the frame closes?

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//3. Create components and put them in the frame.

//...create emptyLabel...

frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);

//4. Size the frame.

frame.pack();
//5. Show it.

frame.setVisible(true);

1. JButton Class
The JButton class represents a button: a user interface component that the user can click to
initiate an action. It is used to create a labelled button. Using the ActionListener it will result in
some action when the button is pushed. It inherits the AbstractButton class and is platform
independent.

JButton class declaration

Let's see the declaration for javax.swing.JButton class.

public class JButton extends AbstractButton implements Accessible

import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
Java JButton Example with ActionListener-Action listeners are probably the easiest — and
most common — event handlers to implement. You implement an action listener to define what
should be done when a user performs certain operation. An action event occurs, whenever an
action is performed by the user.
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Example of displaying image on the button:

import javax.swing.*;
public class ButtonExample{
ButtonExample(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\icon.png"));
b.setBounds(100,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonExample();
}
}
What is a JButton?
The JButton class is a push-button implementation. When pressed, this component generates an
event and has a label. It can also have an image attached to it.
What are the AbstractButton class's subclasses?
JButton, JToggleButton, JCheckBox, and JRadioButton are the four types of buttons defined
by Swing. All of these classes are subclasses of AbstractButton, which extends JComponent.
As a result, all buttons have a set of characteristics in common.
What is the difference between JLabel and JButton?
A JButton is a push button that performs a specific action. JLabel is a component that
displays a short text string, an image, or both at the same time.

2. 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.

JLabel class declaration

Let's see the declaration for javax.swing.JLabel class.

public class JLabel extends JComponent implements SwingConstants, Accessible

import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

3. 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.

JTextField textbox = new JTextField (20);

import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JTextField b = new JTextField("edureka");
b.setBounds(50,100,200,30);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
4. 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.

import java.awt.FlowLayout;

import javax.swing.*;

public class JTextArea_Example


{
JFrame frame;
JTextArea JArea;
JButton btnPrint;

public static void main(String[] args)


{
JTextArea_Example j = new JTextArea_Example();
j.Draw();
}
public void Draw()
{
//JTextArea with 5 Rows and 5 Column
JArea = new JTextArea("This is simple JTextArea Example. \n New Line Begin. \
nThird Line Begin",10,15);

//Adding Component to Frame


frame = new JFrame("Simple JTextArea Example");
frame.setSize(300, 200);
frame.setLayout(new FlowLayout());

frame.add(JArea);
frame.setVisible(true);
}
}

5. 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.

import javax.swing.*;

public class JCheckBox_Example


{
JFrame frame;
JLabel lbltext;
JCheckBox boxjava, boxc,boxcplus;

public static void main(String[] args)


{
JCheckBox_Example j=new JCheckBox_Example();
j.Draw();
}

public void Draw()


{
boxjava = new JCheckBox("Java");
boxc = new JCheckBox("C");
boxcplus = new JCheckBox("C++");
lbltext = new JLabel("Which Language do you know?");

//Adding Component to Frame


frame = new JFrame("Simple JTextField Example");
frame.setSize(400, 200);

BoxLayout boxlayout = new BoxLayout(frame.getContentPane(),


BoxLayout.Y_AXIS);
frame.setLayout(boxlayout);

frame.add(lbltext);
frame.add(boxjava);
frame.add(boxc);
frame.add(boxcplus);
frame.setVisible(true);
}
}
6. 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.

7. 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);
8. 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());
9. JTables
JTable is used to edit or display 2-D data which consists of rows and columns. It is almost
similar to a spreadsheet that contains data in a tabular form. JTable can be created by
instantiating the class javax.swing.JTable.

JTable jt=new JTable();

import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}

10. 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.

 JScrollPane( )
import java.awt.*;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Jscrollpane {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane);
frame.setContentPane(panel);
frame.setSize(500, 500);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}

 JscrollPane (Component c)
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Jscrollpane {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JTextArea tArea = new JTextArea(10,10);
JScrollPane scrollPane = new JScrollPane(tArea);
panel.add(scrollPane);
frame.setContentPane(panel);
frame.setSize(500, 500);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
11. JTree
JTree is a Swing component with which we can display hierarchical data. JTree is quite a
complex component. A JTree has a 'root node' which is the top-most parent for all nodes in the
tree. A node is an item in a tree. A node can have many children nodes. These children nodes
themselves can have further children nodes. If a node doesn't have any children node, it is called
a leaf node. The leaf node is displayed with a different visual indicator. The nodes with children
are displayed with a different visual indicator along with a visual 'handle' which can be used to
expand or collapse that node. Expanding a node displays the children and collapsing hides them.

The node is represented in Swing API as TreeNode which is an interface. The interface
MutableTreeNode extends this interface which represents a mutable node. Swing API provides
an implementation of this interface in the form of DefaultMutableTreeNode class.We will be
using the DefaultMutableTreeNode class to represent our node. This class is provided in the
Swing API and we can use it to represent our nodes. This class has a handy add() method which
takes in an instance of MutableTreeNode.

public class JTree extends JComponent implements Scrollable, Accessible

Constructor Description

JTree() Creates a JTree with a sample model.

JTree(Object[] value) Creates a JTree with every element of the specified array as the child of a new root
node.

JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which displays the root node.
root)

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}

12. JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.It doesn't have title bar. JPanel is a Swing’s
lightweight container which is used to group a set of components together. JPanel is a pretty
simple component which, normally, does not have a GUI (except when it is being set an opaque
background or has a visual border).

Creating new JPanel


JPanel Panel = new JPanel();

We frequently make a class that extends from JPanel in the following way:
public class Panel extends JPanel {

// code to add components to the panel


}
Setting Layout in Jpanel
After the panel is built, we can specify a layout manager by calling the method
setLayout(LayoutManager). To prevent producing the default FlowLayout object, it is advised to
specify the layout manager when creating the panel:

// RECOMMENDED:
JPanel Panel = new JPanel(new GridBagLayout());
We cannot specify a BoxLayout while establishing the panel since its constructor requires an
existing container. For instance:

// Exception
JPanel Panel = new JPanel(); // a FlowLayout manager is created by default
Panel.setLayout(new BoxLayout(Panel, BoxLayout.X_AXIS));

Adding components to JPanel


The add() method adds GUI elements, such as JLabel, JTextField, JButton, etc., to the panel. The
add() method comes in various iterations; therefore, the panel's layout manager determines which
version should be utilized.

For the FlowLayout, BoxLayout, GridLayout, or SpringLayout layout managers, use the
add(Component) method.
Use the add(Component comp, Object constraints) method for the following layout managers:
CardLayout, GridBagLayout, or BorderLayout.

import java.awt.*;
import javax.swing.*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}

You might also like