JAVA UNIT-V NOTES
JAVA UNIT-V NOTES
AWT Introduction
• Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
• Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.
• The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
• The predefined classes of awt package are classified into following types:
Limitations of AWT
• 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
Swing Introduction
• Java Swing is used to create window-based applications. It is built on the top of AWT
(Abstract Windowing Toolkit) API and entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and lightweight components.
• The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
3 AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
4 AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
MVC Architecture
• The MVC design pattern consists of three modules model, view and controller.
• Model :The model represents the state (data) and business logic of the application. For
example-in case of a check box, the model contains a field which indicates whether the box
is checked or unchecked.
• View :The view module is responsible to display data i.e. it represents the presentation.The
view determines how a component has displayed on the screen, including any aspects of
view that are affected by the current state of the model.
• Controller:The controller determines how the component will react to the
user.Controller The controller module 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.
Component Class
• A component is an object having a graphical representation that can be displayed on the
screen and that can interact with the user.
• Examples of components are the buttons, checkboxes, and scrollbars of a typical graphical
user interface.
The methods of Component class are widely used in java swing that are given below.
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default
false.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window.
JPanel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
JDialog
• The JDialog control represents a top level window with a border and a title used to take
some form of input from the user. It inherits the Dialog class.
• Unlike JFrame, it doesn't have maximize and minimize buttons.
JFrame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();
JButton b=new JButton("click");
f.add(b);
f.setSize(400,500);
f.setVisible(true);
}
}
Output:
import javax.swing.*;
public class Simple2 extends JFrame
{ //inheriting JFrame
JFrame f;
Simple2()
{
JButton b=new JButton("click"); //create button
add(b); //adding button on frame
setSize(400,500);
setVisible(true);
}
public static void main(String[] args)
{
new Simple2();
}
}
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.
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.
Example
import java.awt.*;
import javax.swing.*;
public class Border
{
Border()
{
JFrame f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new Border();
}
}
Output:
FlowLayout
• This layout is used to arrange the GUI components in a sequential flow (that means one
after another in horizontal way)
• You can also set flow layout of components like flow from left, flow from right.
FlowLayout Left
Frame f=new Frame();
f.setLayout(new FlowLayout(FlowLayout.LEFT));
FlowLayout Right
Frame f=new Frame();
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
Example
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout
{
MyFlowLayout()
{
JFrame f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyFlowLayout();
}
}
Output:
GridLayout
This layout is used to arrange the GUI components in the table format.
Example
import java.awt.*;
import javax.swing.*;
public class MyGridLayout
{
MyGridLayout()
{
JFrame f=new JFrame();
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);
f.setLayout(new GridLayout(3,3));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyGridLayout();
}
}
Output
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.
Output:
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
protected static int MINSIZE It is smallest grid that can be laid out by the
grid bag layout.
protected static int PREFERREDSIZE It is preferred grid size that can be laid out by
the grid bag layout.
Example
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame
{
public static void main(String[] args)
{
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample()
{
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Output:
Event Handling
• In general we can not perform any operation on dummy GUI screen even any button click or
select any item.
• To perform some operation on these dummy GUI screen you need some predefined classes
and interfaces.
• All these type of classes and interfaces are available in java.awt.event package.
• Changing the state of an object is known as an event.
• The process of handling the request in GUI screen is known as event handling (event
represent an action). It will be changes component to component.
Note: In event handling mechanism event represent an action class and Listener represent an
interface. Listener interface always contains abstract methods so here you need to write your
own logic.
Events
The Events are the objects that define state change in a source. An event can be generated as a
reaction of a user while interacting with GUI elements.
Some of the event generation activities are moving the mouse pointer, clicking on a button,
pressing the keyboard key, selecting an item from the list, and so on. We can also consider
many other user operations as events.
Event Sources
A source is an object that causes and generates an event. It generates an event when the
internal state of the object is changed. The sources are allowed to generate several different
types of events.
A source must register a listener to receive notifications for a specific event. Each event
contains its registration method. Below is an example:
Example
public void addTypeListener (TypeListener e1)
• From the above syntax, the Type is the name of the event, and e1 is a reference to the
event listener.
• For example, for a keyboard event listener, the method will be called as addKeyListener().
• For the mouse event listener, the method will be called as addMouseMotionListener().
• When an event is triggered using the respected source, all the events will be notified to
registered listeners and receive the event object.
• This process is known as event multicasting.
Event Listeners
It is also known as event handler.Listener is responsible for generating response to an event.
From java implementation point of view the listener is also an object. Listener waits until it
receives an event. Once the event is received , the listener process the event and then returns.
Event classes and Listener interfaces
Event Classes Description Listener Interface
Registration Methods
For registering the component with the Listener, many classes provide the registration
methods.
For example:
Button
public void addActionListener(ActionListener a)
{
}
MenuItem
public void addActionListener(ActionListener a)
{
}
TextField
public void addActionListener(ActionListener a)
{
}
public void addTextListener(TextListener a)
{
}
TextArea
public void addTextListener(TextListener a)
{
}
Checkbox
public void addItemListener(ItemListener a)
{
}
Choice
public void addItemListener(ItemListener a)
{
}
List
public void addActionListener(ActionListener a)
{
}
public void addItemListener(ItemListener a)
{
}
Steps to perform Event Handling
Following steps are required to perform event handling:
• Implement the Listener interface and overrides its methods
• Register the component with the Listener
• The User clicks the button and the event is generated.
• Now the object of concerned event class is created automatically and information about
the source and the event get populated with in same object.
• Event object is forwarded to the method of registered listener class.
• The method is now get executed and returns.
The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five
methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
Example
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label l;
MouseListenerExample()
{
addMouseListener(this);
l=new Label();
add(l);
setSize(300,300);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
l.setText("Mouse Released");
}
public static void main(String[] args)
{
new MouseListenerExample();
}
}
Output:
Example
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener
{
Label l;
TextArea area;
KeyListenerExample()
{
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e)
{
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
l.setText("Key Released");
}
public void keyTyped(KeyEvent e)
{
l.setText("Key Typed");
}
public static void main(String[] args)
{
new KeyListenerExample();
}
}
Output:
Adapter Classes
• In a program, when a listener has many abstract methods to override, it becomes complex
for the programmer to override all of them.
• For example, for closing a frame, we must override seven abstract methods of
WindowListener, but we need only one method of them.
• For reducing complexity, Java provides a class known as "adapters" or adapter class.
• Adapters are abstract classes, that are already being overriden.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
Inner classes
• Inner class means one class which is a member of another class.
• We use inner classes to logically group classes and interfaces in one place so that it can be
more readable and maintainable.
Example
class TestMemberOuter
{
private int data=30;
class Inner
{
void msg()
{
System.out.println("data is "+data);
}
}
public static void main(String args[])
{
TestMemberOuter obj=new TestMemberOuter();
TestMemberOuter.Inner in=obj.new Inner();
in.msg();
}
}
2.Anonymous inner class
• In Java, a class can contain another class known as nested class. It's possible to create a
nested class without giving any name.
• A nested class that doesn't have any name is known as an anonymous class.
• An anonymous class must be defined inside another class. Hence, it is also known as an
anonymous inner class.
Example
abstract class Person
{
abstract void eat();
}
class TestAnonymousInner
{
public static void main(String args[])
{
Person p=new Person()
{
void eat()
{
System.out.println("nice fruits");
}
};
p.eat();
}
}
3.Local inner class
• A class i.e. created inside a method is called local inner class in java.
• If you want to invoke the methods of local inner class, you must instantiate this class inside
the method.
Example
public class localInner
{
private int data=30;
void display()
{
class Local
{
void msg()
{
System.out.println(data);
}
}
Local l=new Local();
l.msg();
}
public static void main(String args[])
{
localInner obj=new localInner();
obj.display();
}
}
Example
class TestOuter
{
static int data=30;
static class Inner
{
void msg()
{
System.out.println("data is "+data);
}
}
public static void main(String args[])
{
TestOuter.Inner obj=new TestOuter.Inner();
obj.msg();
}
}
In this example, you need to create the instance of static nested class because it has instance
method msg(). But you don't need to create the object of Outer class because nested class is
static and static properties, methods or classes can be accessed without object.
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.
Advantages of Applet
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many platforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
• 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.
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet",20,20);
}
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to applet",150,150);
}
}
/*
<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
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g)
{
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Applications are just like a Java Applets are small Java programs that are designed
programs that can be execute to be included with the HTML web document.
independently without using the web They require a Java-enabled web browser for
browser. execution.
Java Application Java Applet
Application program requires a main Applet does not require a main function for its
function for its execution. execution.
Applications can executes the programs Applets cannot execute programs from the local
from the local system. machine.
• So far, we have created the applets based on AWT(Abstract Window Toolkit) by extending
the Applet class of the awt package.
• We can even create applets based on the Swing package.
• In order to create such applets, we must extend JApplet class of the swing package. JApplet
extends Applet class, hence all the features of Applet class are available in JApplet as well,
including JApplet's own Swing based features.
• Swing applets provides an easier to use user interface than AWT applets.
Example
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener
{
JButton b;
JTextField tf;
public void init()
{
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is invoked only
once.
myapplet.html
<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>
Painting in Swing
java.awt.Graphics class provides many methods for graphics programming.
Example
import java.awt.*;
import javax.swing.JFrame;
public class DisplayGraphics extends Canvas
{
public void paint(Graphics g)
{
g.drawString("Hello",40,40);
setBackground(Color.WHITE);
g.fillRect(130, 30,100, 80);
g.drawOval(30,130,50, 60);
setForeground(Color.RED);
g.fillOval(130,130,50, 60);
g.drawArc(30, 200, 40,50,90,60);
g.fillArc(30, 130, 40,50,180,40);
}
public static void main(String[] args)
{
DisplayGraphics m=new DisplayGraphics();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
//f.setLayout(null);
f.setVisible(true);
}
}
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.
Methods Description
void setText(String text) It defines the single line of text this component will
display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the
X axis.
Example
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);
}
}
Output:
JTextField
• The object of a JTextField class is a text component that allows the editing of a single line
text.
• It inherits JTextComponent class.
Methods Description
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
Example
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
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.
Methods Description
Output:
Java JToggleButton
Methods
Example
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
Output
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.
Example
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample()
{
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Output:
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.
Example
import javax.swing.*;
public class RadioButtonExample
{
RadioButtonExample()
{
JFrame f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
f.add(r1);
f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args)
{
new RadioButtonExample();
}
}
Output:
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.
Example
import javax.swing.*;
public class TabbedPaneExample
{
TabbedPaneExample()
{
JFrame f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
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);
}
public static void main(String[] args)
{
new TabbedPaneExample();
}
}
Output:
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.
Useful Methods
Modifier Method Description
void setColumnHeaderView(Component) It sets the column header for the scroll pane.
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
Component getCorner(String) one of the following constants defined in
ScrollPaneConstants: UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
Example
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
public class JScrollPaneExample
{
private static final long serialVersionUID = 1L;
private static void createAndShowGUI() {
// Create and set up the window.
final JFrame frame = new JFrame("Scroll Pane Example");
Output:
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.
Example
import javax.swing.*;
public class ListExample
{
ListExample()
{
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}
Output:
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.
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.
JDialog
• The JDialog control represents a top level window with a border and a title used to take
some form of input from the user. It inherits the Dialog class.
• Unlike JFrame, it doesn't have maximize and minimize buttons.
Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample
{
private static JDialog d;
DialogExample()
{
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Output: