Java AWT unit5
Java AWT unit5
Event Handling- The Delegation event model- Events, Event sources, Event
Listeners, Event classes, Handling mouse and keyboard events, Adapter classes,
Inner classes, Anonymous Inner classes.
A Simple Swing Application, Applets – Applets and HTML, Security Issues, Applets
and Applications, passing parameters to applets. Creating a Swing Applet, Painting
in Swing, A Paint example, Exploring Swing Controls- JLabel and Image Icon, JText
Field, The Swing ButtonsJButton, JToggle Button, JCheck Box, JRadio Button,
JTabbed Pane, JScroll Pane, JList, JCombo Box, Swing Menus, DialogsJava AWT
AWT stands for Abstract Window Toolkit. It is a platform dependent API for
creating Graphical User Interface (GUI) for java programs.
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.
AWT is rarely used now a days because of its platform dependent and heavy-
weight nature. AWT components are considered heavy weight because they are
being generated by underlying operating system (OS). For example if you are
instantiating a text box in AWT that means you are actually asking OS to create a
text box for you.
Swing is a preferred API for window based applications because of its platform
independent and light-weight nature. Swing is built upon AWT API however it
provides a look and feel unrelated to the underlying platform. It has more
powerful and flexible components than AWT. In addition to familiar components
such as buttons, check boxes and labels, Swing provides several advanced
components such as tabbed panel, scroll panes, trees, tables, and lists.
AWT:
Characteristics
It is a set of native user interface components.
It is very robust in nature.
It includes various editing tools like graphics tool and imaging tools.
It uses native window-system controls.
It provides functionality to include shapes, colors and font classes.
Advantages
It takes very less memory for development of GUI and executing programs.
It is highly stable as it rarely crashes.
It is dependent on operating system so performance is high.
It is easy to use for beginners due to its easy interface.
Disadvantages
The buttons of AWT does not support pictures.
It is heavyweight in nature.
Two very important components trees and tables are not present.
Extensibility is not possible as it is platform dependent
AWT hierarchy
The hierarchy of Java AWT classes are given below.
Components and containers
All the elements like buttons, text fields, 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.
Types of containers:
As explained above, a container is a place where in 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: Window is a container that has no border and menubars. You must use
frame, dialog or another window for creating a window.
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. 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.
Useful Methods of Component class
Method Description
public void setSize(int width,int sets the size (width and height) of the
height) component.
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the
above example that sets the position of the awt button.
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout
managers. These are the following classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
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 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:
o BorderLayout(): creates a border layout but with no gaps between the
components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");
10. JButton b2=new JButton("SOUTH");
11. JButton b3=new JButton("EAST");
12. JButton b4=new JButton("WEST");
13. JButton b5=new JButton("CENTER");
14. f.setLayout(new BorderLayout(20,30));
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22.
23. f.setVisible(true);
24.f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
25.}
26.public static void main(String[] args) {
27. new Border();
28.}
29.}
Output:
Java GridLayout
The GridLayout is used to arrange the components in 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 alongwith 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. JButton b1=new JButton("1");
9. JButton b2=new JButton("2");
10. JButton b3=new JButton("3");
11. JButton b4=new JButton("4");
12. JButton b5=new JButton("5");
13. JButton b6=new JButton("6");
14. JButton b7=new JButton("7");
15. JButton b8=new JButton("8");
16. JButton b9=new JButton("9");
17.
18. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
19. f.add(b6);f.add(b7);f.add(b8);f.add(b9);
20.
21. f.setLayout(new GridLayout(3,3)); //setting grid layout of 3 rows and 3 columns
22. f.setSize(300,300);
23. f.setVisible(true);
24.f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
25.}
26.public static void main(String[] args) {
27. new MyGridLayout();
28.}
29.}
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in
a flow). It is the default layout of 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
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.f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
23.}
24.public static void main(String[] args) {
25. new MyFlowLayout();
26.}
27.}
Java CardLayout
The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is
known as CardLayout.
Constructors of CardLayout class
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.
Commonly used methods of CardLayout class
o public void next(Container parent): is used to flip to the next card of the
given container.
o public void previous(Container parent): is used to flip to the previous card
of the given container.
o public void first(Container parent): is used to flip to the first card of the
given container.
o public void last(Container parent): is used to flip to the last card of the
given container.
o public void show(Container parent, String name): is used to flip to the
specified card with the given name.
Example of CardLayout class
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. import javax.swing.*;
5.
6. public class CardLayoutExample extends JFrame implements ActionListener{
7. CardLayout card;
8. JButton b1,b2,b3;
9. Container c;
10. CardLayoutExample(){
11.
12. c=getContentPane();
13. card=new CardLayout(40,30);
14.//create CardLayout object with 40 hor space and 30 ver space
15. c.setLayout(card);
16.
17. b1=new JButton("Apple");
18. b2=new JButton("Boy");
19. b3=new JButton("Cat");
20. b1.addActionListener(this);
21. b2.addActionListener(this);
22. b3.addActionListener(this);
23.
24. c.add("a",b1);c.add("b",b2);c.add("c",b3);
25.
26. }
27. public void actionPerformed(ActionEvent e) {
28. card.next(c);
29. }
30.
31. public static void main(String[] args) {
32. CardLayoutExample cl=new CardLayoutExample();
33. cl.setSize(400,400);
34. cl.setVisible(true);
35. cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
36. }
37.}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
c.setLayout(card);
b1=new JButton(icon);
b2=new JButton(icon1);
b3=new JButton(icon2);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
card.next(c);
}
public static void main(String[] args) {
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.
The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known as
its display area. Each component associates an instance of GridBagConstraints. With the
help of constraints object we arrange component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to
determine component's size.
Fields
Modifier and Type Field Description
Useful Methods
Modifier and Type Method Description
Example
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public GridBagLayoutExample() {
GridBagLayout grid = new GridBagLayout();
setLayout(grid);
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Event Handling
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
Java event handling by implementing ActionListener for Button class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class AEvent extends JFrame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
import java.awt.event.*;
import javax.swing.*;
LabelExample(){
tf=new TextField();
tf.setBounds(50,50, 150,20);
l=new Label();
l.setBounds(50,100, 250,20);
b.setBounds(50,150,60,30);
b.addActionListener(this); //register
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample();
Output:
import java.awt.event.*;
import javax.swing.*;
TextField tf1,tf2,tf3;
Button b1,b2;
TextFieldExample(){
tf1=new TextField();
tf1.setBounds(50,50,150,20);
tf2=new TextField();
tf2.setBounds(50,100,150,20);
tf3=new TextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new Button("+");
b1.setBounds(50,200,50,50);
b2=new Button("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
add(tf1);add(tf2);add(tf3);add(b1);add(b2);
setSize(300,300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1)
// The getSource method is used in the actionPerformed method to determine which button
was //clicked.
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
String result=String.valueOf(c);
tf3.setText(result);
Output:
Java AWT Checkbox Example with ActionListener
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
CheckboxExample(){
label.setAlignment(Label.CENTER);
label.setSize(400,100);
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100,150, 50,50);
checkbox1.addItemListener(new ItemListener() {
+ (e.getStateChange()==1?"checked":"unchecked"));
});
checkbox2.addItemListener(new ItemListener() {
+ (e.getStateChange()==1?"checked":"unchecked"));
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
{
new CheckboxExample();
Output:
Java AWT Choice Example with ActionListener
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
ChoiceExample(){
label.setAlignment(Label.CENTER);
label.setSize(400,100);
b.setBounds(200,100,50,20);
c.setBounds(100,100, 75,75);
c.add("C");
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Python");
f.add(c);f.add(label); f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.addActionListener(new ActionListener() {
label.setText(data);
});
new ChoiceExample();
Output:
Java AWT List Example with ActionListener
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
{
ListExample(){
label.setAlignment(Label.CENTER);
label.setSize(500,100);
b.setBounds(200,150,80,30);
l1.setBounds(100,100, 70,70);
l1.add("C");
l1.add("C++");
l1.add("Java");
l1.add("PHP");
l2.setBounds(100,200, 70,70);
l2.add("Turbo C++");
l2.add("Spring");
l2.add("Hibernate");
l2.add("CodeIgniter");
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.addActionListener(new ActionListener() {
for(String frame:l2.getSelectedItems()){
label.setText(data);
});
new ListExample();
Output
Java AWT TextArea Example with ActionListener
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Label l1,l2;
TextArea area;
Button b;
TextAreaExample(){
l1=new Label();
l1.setBounds(50,50,100,30);
l2=new Label();
l2.setBounds(160,50,100,30);
area=new TextArea();
area.setBounds(20,100,300,300);
b.setBounds(100,400,100,30);
b.addActionListener(this);
add(l1);add(l2);add(area);add(b);
setSize(400,500);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
new TextAreaExample();
}
Output:
import javax.swing.*;
class MenuExample
MenuExample(){
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
{
new MenuExample();
Output:
setSize(300,300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mouseClicked(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
addMouseMotionListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mouseDragged(MouseEvent e) {
l.setText("X="+e.getX()+", Y="+e.getY());
Graphics g=getGraphics();
g.setColor(Color.RED);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {
l.setText("X="+e.getX()+", Y="+e.getY());
}
public static void main(String[] args) {
new Paint();
}
}
output:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Label l;
TextArea area;
KeyListenerExample(){
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
String text=area.getText();
String words[]=text.split("\\s");
Adapter classes
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
import java.awt.event.*;
AdapterExample(){
f.addWindowListener(new WindowAdapter(){
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
new AdapterExample();
Output:
Inner classes
3) AWT doesn't support pluggable look and Swing supports pluggable look
feel. and feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
import javax.swing.*;
public class Simple2 extends JFrame{ //inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
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.
Commonly used Constructors:
Constructor Description
Output:
Java 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.
2.
3.
4.
JTextField class declaration
Let's see the declaration for javax.swing.JTextField class.
1. public class JTextField extends JTextComponent implements SwingConstants
Commonly used Constructors:
Constructor Description
JTextField(String text, int Creates a new TextField initialized with the specified
columns) text and columns.
5.
6. import javax.swing.*;
7. class TextFieldExample
8. {
9. public static void main(String args[])
10. {
11. JFrame f= new JFrame("TextField Example");
12. JTextField t1,t2;
13. t1=new JTextField("Welcome to Java
14..");
15. t1.setBounds(50,100, 200,30);
16. t2=new JTextField("AWT Tutorial");
17. t2.setBounds(50,150, 200,30);
18. f.add(t1); f.add(t2);
19. f.setSize(400,400);
20. f.setLayout(null);
21. f.setVisible(true);
22. }
23. }
Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on
or off.
Nested Classes
Modifier Class Description
and Type
Constructors
Constructor Description
JToggleButton() It creates an initially unselected toggle button
without setting the text or image.
JToggleButton(String text, Icon It creates a toggle button that has the specified
icon) text and image, and that is initially unselected.
Methods
Modifier and Type Method Description
JToggleButton Example
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
Java 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.
JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.
import java.awt.event.*;
CheckBoxExample(){
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
checkbox1.setBounds(150,100, 50,50);
checkbox2.setBounds(150,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
+ (e.getStateChange()==1?"checked":"unchecked"));
});
checkbox2.addItemListener(new ItemListener() {
+ (e.getStateChange()==1?"checked":"unchecked"));
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new CheckBoxExample();
}
}
Output:
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from multiple
options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.
import java.awt.event.*;
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
if(rb1.isSelected()){
if(rb2.isSelected()){
new RadioButtonExample();
}}
Output:
Java JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab with a
given title or icon. It inherits JComponent class.
TabbedPaneExample(){
f=new JFrame();
p1.add(ta);
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new TabbedPaneExample();
}}
Output:
Java 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.
Constructors
Constructor Purpose
JScrollPane(int, int)
JScrollPane(Component
, int, int)
Useful Methods
Modifier Method Description
void setColumnHeaderView(Compo It sets the column header for the scroll pane.
nent)
void setRowHeaderView(Component It sets the row header for the scroll pane.
)
void setCorner(String, Component) It sets or gets the specified corner. The int
parameter specifies which corner and must
be one of the following constants defined in
Compone getCorner(String) ScrollPaneConstants: UPPER_LEFT_CORNER,
nt UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
JScrollPane Example
import javax.swing.*;
public ScrollPaneDemo() {
super("ScrollPane Demo");
getContentPane().add(png);
setSize(200,200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ScrollPaneDemo();
Output:
Java JList
The object of JList class represents a list of text items. The list of text items can be set up so that the
user can choose either one item or multiple items. It inherits JComponent class.
JList(ary[] listData) Creates a JList that displays the elements in the specified
array.
import javax.swing.*;
import java.awt.event.*;
ListExample(){
label.setSize(500,100);
b.setBounds(200,150,80,30);
l1.addElement("C");
l1.addElement("C++");
l1.addElement("Java");
l1.addElement("PHP");
list1.setBounds(100,100, 75,75);
l2.addElement("Turbo C++");
l2.addElement("Struts");
l2.addElement("Spring");
l2.addElement("YII");
list2.setBounds(100,200, 75,75);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
if (list1.getSelectedIndex() != -1) {
label.setText(data);
}
if(list2.getSelectedIndex() != -1){
label.setText(data);
});
new ListExample();
}}
Output:
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on
the top of a menu. It inherits JComponent class.
void removeAllItems() It is used to remove all the items from the list.
import java.awt.event.*;
JFrame f;
ComboBoxExample(){
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener() {
+ cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
});
new ComboBoxExample();
}
Output:
Java Swing Menus
JMenuBar, JMenu and JMenuItem
The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
The object of JMenu class is a pull down menu component which is displayed from the menu bar. It
inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must
belong to the JMenuItem or any of its subclass.
import java.awt.event.*;
DialogExample() {
DialogExample.d.setVisible(false);
});
d.setSize(300,300);
d.setVisible(true);
new DialogExample();
}
Output:
Applets
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content.
It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many platforms, including Linux, Windows, Mac
Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to
start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object
that can be used for drawing oval, rectangle, arc etc.
Note: class must be public because its object is created by Java Plugin software that resides on the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
Applets and HTML
Features of Applets over HTML
Displaying dynamic web pages of a web application.
Playing sound files.
Displaying documents
Playing animations
Security Issues
1. In general, applets loaded over the Internet (or any network) are prevented
from reading and writing files on the client file system, and from making
network connections except to the originating host.
2. Applets loaded over the net are prevented from starting other programs on
the client.
3. Applets are not allowed to open network connections to any computer,
except for the host that provided the .class files.
4. Applets loaded over the net are not allowed to start programs on the client.
Applications are just like a Java Applets are small Java programs that are
programs that can be execute designed to be included with the HTML
independently without using the web document. They require a Java-
web browser. enabled web browser for execution.
Application program requires a Applet does not require a main function for
main function for its execution. its execution.
Applications can executes the Applets cannot execute programs from the
programs from the local system. local machine.
import java.awt.*;
import java.applet.*;
/*
<applet code="Applet8" width="400"
height="200">
<param name="Name" value="Roger">
<param name="Age" value="26">
<param name="Sport" value="Tennis">
<param name="Food" value="Pasta">
<param name="Fruit" value="Apple">
<param name="Destination"
value="California">
</applet>
*/
}
Output
Creating a Swing Applet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The JApplet
class extends the Applet class.
1. import java.applet.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class EventJApplet extends JApplet implements ActionListener{
5. JButton b;
6. JTextField tf;
7. public void init(){
8.
9. tf=new JTextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new JButton("Click");
13. b.setBounds(80,150,70,40);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is invoked
only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Painting in Swing:
import javax.swing.JFrame;
g.drawString("Hello",40,40);
setBackground(Color.WHITE);
g.drawOval(30,130,50, 60);
setForeground(Color.RED);
g.fillOval(130,130,50, 60);
f.add(m);
f.setSize(400,400);
//f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
output
A Paint example
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.
myapplet.html
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>