Oops Co3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

CO3: Build GUI Applications Using Swing

Q1. Define Graphical User Interface (GUI)


interact with digital devices, software, or
GUI is a user interface that allows users to
of text
using graphical elements such as icons, buttons, and menus instead
operating systems
based command-line interfaces (CLI).
Q2. Define Swing
interface
provides a rich set of graphical user
Swing is a GUI toolkit for Java that
Foundation
and tables. It is a part of the Java
components, such as buttons, labels, text fields,
Abstract Window Toolkit (AWT) API.
Classes (JFC) and is built on top of the
03. List the features of Swing
Classes)
1. Swing is apart of JFC(Java Foundation
(Abstract Window Toolkit)
2. Swing is built on top of AWT
3. Swing components are lightweight
pluggable look and feel
4. Swingcomponents have
independent
5. Swing components are platform
package javax.swing
6. Swing components are included in thc
using Swing in Java
04: What are the advantages of
customized and styled to meet the
1. Arich set of GUI components that can be
requirements of any application.
components are implemented in pure Java and can
2. Cross-platform support, as Swing
the Java Virtual Machine (JVM).
be run on any platform that supports
High performance and responsiveness, as Swing is optimized for modern hardware
3.
interactions efficiently.
and can handle complex graphics and user
technologies, such as JDBC, JSP, and servlets.
4. Easy integration with other Java
the implementation of complex user
5. Robust event handling mechanism that simplifies
interactions.
containers in Swing
Q5. Distinguish between components and
interface. Examples are
Components are the individual elements that make up the user
of components that
JButton, JLabel,JTextField and JCheckBox. Containers are special types
JFrame, JPanel and JDialog.
are designed to hold other components. Examples are
method.
Components can be added to containers using container's add ()
Q6. List the types of containers in Swing
1. Top-level containcrs Eg: JFrame, JApplet, JWindow
JRootlane
2. Lightweight containers Ig: JPancl,
Q7. What is a lLayout Manager
componcnts within a Containcr. Lg:
Layout Managers control the position of
Flowlayout, Borderlayout
Q8. Explain different types of Layout managers in Java
I Flowlayout : This layout manager places components in a
row from left-t0-righi,
top-to-bottom manner. It is the default layout for thc applet or pancl.
Flowlayout Demo
Button 1 Button 2 Button 3

Button 4 Button 5

FlowLayout class defines the following constructors


FlowLayout ()
FlowLayout ( int alignment)
Alignment - LEFT, CENTERand RIGHT
FlowLayout( int alignment, int horizontal gap, int vertical gap)
The default alignment for tlc componcnts in a row is CENTER. Default horizontal and
vertical gaps are 5pixels.
2. BorderLayout: BorderLayout Manager divides the window into five regions - North.
East, West, South and Center. BorderLayout class defines the following constructors
BorderLayout()
BorderLayout(int hor_gap, int ver_gap)
Components can be added the container using the add) method defined in the Container
class.

Component add(Component comp);


void add(Component comp, Object constraints);
Here constraints can be NORTH, SOUTH, EAST, WEST and
CENTER. These constants
correspond to strings "North", "South", "East", "West", and "Center" respectively. They
describe the region where the component should be placed. The default region is
CENTER.
Bordertest
North

West Center East

South
3. GridLayout: AGridLayout Manager places the components in arectangular grid.
Each component's position is identified by acolumn and row. Allthe cells in the grid
have the same size and width. The GridLayout class provides the following
Constructors.

GridLayout);
GridLayout(int rows, int columns);
GridLayout(int rows, int columns, int hor_gap, int ver_gap);
This creates a row*column grid layout with the specified horizontal and
not both. The
vertical gaps. In the constructor, either rows or columns can be zero, but
Thedefault
first constructor is equivalent toone row with any number of components.
gap between components is zero pixels.

components to be added to a
4. CardLayout: This layout manager allows multiple
container, but only one component is visibleat a time.

that
5. GridBagLayout: This layout manager is a powerful and flexible layout manager
allows components to be placed in cells of different sizes and shapes.

Button 1 Button 2

Button 3 Button 4

Button 5

Q9. Explain the steps for creating a simple swing GUlapplication with an example
1. Import the necessary Swing packages: To use Swing in aJava program, you
need to import the necessary packages, such as javax.swing and java.awt.
Create a JFrame object: The JFrame class represents the main window of a
2.
the constructor or by
Swing application. Youcan create a JFrame object using
extending the JFrame class.
3. Add components to the JFrame: Once you
have a JFrame object. you can

add componcnts to it, such as buttons, labcls. text


ficlds, and other controls.
suits the design of the
4. Set layout manager: Choose a layout manager that best
interface.
the
3. Set the properties of the JFrame: You can set various properties of
JFrame, such as its size, title, and visibility.
6. Write event handlers: You can write event handlers to handle user input.
such as button clicks or menu selections.
Example:
import javax.swing *:
Import java.awt.*:
public class SimpleSwingApp {
public static void main(String[] args)
I/create a new JFrame object

JFrame frame new JFrame("Simple Swing App");


/create a new label and button
JLabel label = new JLabel("Hello, World!"):
JButton button = new JButton("Click me!"):
l/create a new panel and add the label and button to it
JPanel panel = new JPanel();
panel.add(label);
panel.add(button);
ll set the layout manager for the pancl
panel.setLayout(new FlowLayout():
ll add the panel to the frame

frame.add(panel):
ll set the properties of the frame
frame.setSize(300, 200):
frame. setDefaultCloseOperation(JFrame.EXIT ON CLOSE);
frame.setVisible(true):
ll add an event listener to the button
button.addActionListener(e -> {
JOptionPane.show Message Dialog( frame, "You clicked the button!");
);

Simple Swing App


Hello, World! Click me!

Message
Youclicked the button!

OK

Q10. List the commonly used methods for Swing Components


1. add(Component c) - inserts a component ona container.
2. setSize(int width,int height) - sets the size (width and height) of the componcnt.
3. setLayout(LayoutManager m) -defines the layout manager for the component.
4. setVisible(boolean status) -changes the visibility of the component, by default false.
5. setTitle(String text) -sets the title for acomponent
Q11. Write notes on Swing Hierarchy

JLabel
Component

JL0st

JTable
Container JComponent

JComboBox

Panel
JSlider
Window

JMenu
Frame Applet

JButton

Q12. Explain creating a frame in Swing with an example


A frame can be created in two ways:
1. By creating the object of JFrame class
Example:
import javax.swing. *;
public class SwingExample

public static void main( String|] args)

JFrame f=new JFrame("Simple Swing Example");


f.setSize(300,300);
f.setLayout(null);
f.set Visible(true):

2. By extending JFrame class (inheritance)


Example:
import javax.swing.*;
class Swing Example extends JFrame

SwingExample()

setSize(300,300); /frame size 300 width and 300 height


setLayout(null); //no layout manager
setVisible(true); /now frame willbe visible,
I/by default not visible
setTitle("S wingExample "), /Set Title

public static void main(String args[))

SwingExample f-new SwingExample(0:

Q13.Explain different Swing Components


1. JButton: The JButton class is used to create a labelled button that bas platform
independent implementation. The application results in some action when the button
is pushed.
Constructors
JButton()- Crcates a button with no text and
con
JButton(Strings )- (reates a button with the specificd text
JButtonlcon ) -Creates abutton with the spcificd con
Example: object
JButton b ncw
bsetBounds( 50,
JButton("Text"),.
100,80,30).
(Iist twO parameters -x andy
coord1nates of top-left corncr Third width, fourth
henght)
2 JLabel: The JLabel class /s a component for
plac1ng text in a container It is used to
d1splay a single lIne of read only text. The text can he
changed by an application but a
user cannot cd1t it drectly
Constructors
JLabcl)

JLabel( String s)
JLabel(lcon i )
JLabel(String s, lcon i. int horzontalAlignment )
Methods
String get Text() - Returns the text in the label
vOId setText) - Sets the text of label
void setiiorizontalAlignment(int alignment) - Al1gns the label's text in Xaxus
lcon getlcon() - Retums the mage the label displays
int getHonzontalAl1gnmentt)- Returns thc alignment of label's text in Xaxis
Example:
JLabel |l new JLatbel("Text" .
3. JTextField: The JTextField class is a text componcnt that
allows the c1ting of a
single line text
Constructors
JTextField() -Creates a new TextFicld
JTextFicld( String text) -TextField initial1sed with some text
JTextFicld( String text, int columns) - Initial1zed with some text and columns
JTextFicld(int columns) - Empty TextField with spec1fied number of columns
Example:
JTextFieldt! new JTextField"Text"):
4. JTextArea : The JTextAreaclass is a multi line region that displays text. Itallows the
cditing of multiple line text.
Constructors
JTextArea()
JTextArca(String s)
JTextArea(int row, int column)
JTextArea(String s, int row. int column)
Example:
JTextArea tl=new JTextArea("Text"):
(or)
JTextArea tl,t2; tl=new JTextArea(Text");
5. 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".

Example:
JCheckBox cl=new JCheckBox(*Text");
6. JList: The object of the JList class represents a list of text items.
The list of text items
can be set up so that the user can choose one or more items from list of
items.
Example:
DefaultListModel || = new DefaultListModel<0:
Il.addElement("ltem1");
|1.addElement("Item2" );
11.addElement("Item3"):
11.addElement("Item4"):
JList list = new JList<>(1):
7. JPasswordField: The JPasswordFicld class is a text component specialised for
password entry. It allows the editing of a single line of text.
Example:
JPasswordField pwd = new JPasswordField():
pwd.setBounds( 100,50,80,30):
8. 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
quizzes. It should be added in ButtonGroup to select one radio button only.
Example:
ButtonGroup bg-new ButtonGroup():
JRadioButton rl=new JRadioButton("Male"):
JRadioButton r2-ncw JRadioButton("Fcmale");
bg.add(rl):
bg.add(r2):
9. JComboBox: The JComboBox class is used to show a popup menu of itcms. Item
selected bythe user is shownon the top of a menu.
Example:
String country[]={"India","Aus" "U.S.A","England","Ncwzcaland";:
JComboBox cb=new JComboBox(country);
cb.setBounds(50,50,90,20);
10. JTable: The JTable class is used to display data in tabular form. It is composed of
rows and columns.

Example:
String data|]|= "52 1" "Madhu""43400"}. "512", "Hari","54500").
509","Ganesh""70000"::
String column[]={"ID","NAME'" "SALARY"};
JTable j=new JTable(data,column);
jt.setBounds(30,40,200,300):
1. JPanel: The JPanel is a simplest container class. It provides space in which an
application can attach any other component.
Example:
JPanel panel=new JPanel();
pancl.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton bl=new JButton("Button 1");
bl.setBounds(50,100,80,30);
panel.add(bl );
12. JDialog: The JDialog control represents atop level window with a border and a title
used to take some form of input from the user. " Unlike JFrame, it doesn't have
maximise and minimise buttons.

Example:
JFrame f new JFrame():
JDialog d=new JDialog(f, "Dialog", true);
JButton ("OK"):
JButton b = new
d.add(b);
Delegation Event Model
Handling in Swing/Explain called the
Q14. Explain Event Swing is based on an approach
mechanism used by
Ihe event handling gencrates an cvcnt and scnds il to
onC of
this mechanism, a source
dclegation event model. In an event. Once the
event
until it recejves
listener simply waits
more listeners. Here the
then returns.
arrives, the listener processes the event and
SOurce Event

Event Oriving Listener


Prograrnming
Model

Handler

Q15. Describe the steps for handling events in Swing


1. Create an instance of the component that generates the event, such as a bution, lex
field, or list.
2. Create an instance of the event listener that will handle the event, such as an
ActionListener, KeyListener, or MouseListener.
3. Register the event listener with the
component using the appropriate method, such as
addActionListener, addKeyListener, or addMouseListener.
4. Implement the appropriate event handling method in the
event listener, such as
actionPerformed, keyPressed, or mouseClicked.
Q16. Define the terms - Events, Event
Sources, Event Listeners
1. Events: An event is an object that
describes a state change in asource. The superclass
for all cvents is
java.util.EventObject. Events are declarcd in java.awt.event and
javax.swing.event
2. Event Sources: An event source is an object that generates an
cvent. When asource
generates an event, it is sent to all registered listeners.
3. Event Listeners: A listener is an objcct that is
notified when an event occurs. For an
event listener to work, it must have been registered with one or
more sources to
receive notification and an appropriate method
should have been implemented to
process the event.
Q17. List important Events and Event
Listeners in java
. ActionEvent: This event is fired when a user performs an action, such as clicking a
button or selecting an item from a menu. It is handled by the
ActionListener
interface.
2. KeyEvent: This event is fired when a user presses or
releases a key on the keyboard.
It is handled by the KeyListener interface.
3. MouseEvent: This event is fired when auser performs a mouse
action, such as
click1ng, dragging, or moving the mouse. It is handled by the MouseListener and
MouseMotionListener interfaces.
4. WindowEvent: This event is fired when a window is opened, closed, activated, or
deactivated. It is handled by the WindowListener interface.
5. ItemEvent: This event is fired when an item in a list or menu is selected or
deselected. It is handled bythe ItemListener interface.
Q18. Explain how you can handle a button click event in Java? Provide an example
To handle a button click event in Java, you need to register an ActionListener for the
button. The ActionListener interface defines a single method, actionPerformed, which is
called when the button is clicked.

Example:
import javax.swing. *;
import java.awt.*;
import java.awt.event.*;
public class ButtonExample extends JFrame implements ActionListener
private JButton button:
public ButtonExample0{
setSize(200,200);
setTitle("Button Example");
button = new JButton("Click Me");
add(button);
button.addActionListener(this);
setVisible(true);

public void actionPerformed(ActionEvent e) {


if (e.getSource() == button) {
JOptionParne.showMessageDialog(this, "Button clicked!");
main(String args[])
public static void
example
} Java. Provide an
ButtonExample(): } KeyListener for the
new key press event in
handle a register a
how youcan you need to JTextField. The
QI9. Explain event in Java, JPanel. or
key press JEranme.
Tohandle a events, such as a keyTyped.
willreceive the key keyReleased, and
component that methods: keyPressed,
defines three
KeyListener interface
Example:
import javax.swing.*;
import java.awt.event.*:
JFrame implements KeyListener
KeyExample extends
public class
private JTextField textField;

public KeyExample()

setSize(200,200);
setTitle("Key Example");
JTextField(20):
textField = new
add(textField):
textField. addKeyListener(this);
setVisible(true);

public void key Pressed( Key Évent e) {


pressed
/ Code to be execuled when a key is
JOptionPane.showMessageDialog( this, "Key pressed: " + e.getKeyChar());

public void keyReleased(KeyEvent e) {


/ Code to be executed when a key is released

public void keyTyped(Key Event e) {


1/Code to beexecuted when a key is typed

public static void main(String|] args) {


new KeyExample();
Q20.
Explain how you can handle a
To handle a
mouse click event mouse click event in
component that will receive the in Java, you need to Java? Provide an
example
MouselListener mouse events, such as a register a
interface defines five MouseLi
JFrame. JPanel, stencr for the
mouseRel eased,
Example: mouseEntered, and mouseExited
methods: or
JButton. The
mouseClicked, mouscPressed,
import javax.swing.*;
import java.awt.event.*:
public class
MouseExampl
private JButton button: e extends JFrame implements
public MouseExample() MouseListener
setSize(200,200);
setTitle("Mouse
button = new
Example");
JButton("Click me!");
add(button);
butsetVisible(true);
ton.addMouseListener(this);
public void
mouseClicked(MouseEvent
I/ Code to be executed
when the
e)
button is clicked
System.out.printin("Button clicked!");
public void
mousePressed(MouseEvent e)
public void
mouseReleased(MouseEvent e)
public void mouseEntered(MouseEvent e)
public void mouseExited(MouseEvent e){

public static void main(String[] args) {


new MouseExample(0:
MouseMotionListener in Java
021. What is the difference between MouseListener and
and mouse button
MouseListener: It is used to handle events related to mouse clicks
types
presses/relcases. It provides five methods that can be implemented to handle different
of mouse events:
released) on a
1. mouseClicked: Invoked when the mouse buton is clicked (pressed and
component.
2. mousePressed: Invokedwhen the mouse button is pressed down on a component.
3. mouseReleased: Invoked when the mouse button is released on a component.
4. mouseEntered: Invoked when the mouse cursor enters a component.
5. mouseExited: Invoked when the mouse cursor exits a component.
MouseMotionListener: It is used to handle events related to mouse movement. It provides
two methods that can be implemented to handle mouse motion events:
1. mouseMoved: Invoked when the mouse cursor is moved on a component.
2. mouseDragged: Invoked when the mouse cursor is moved with a mouse button
pressed down on a component.
Q22. Explain the role of event listeners in Java
Event listeners in Java are used to handle events that are triggered by user actions or
system events, such as button clicks. mouse movements, key presses, and window resizing.
The role of event listeners is to detect when an event occurs and to respond to it by executing
somecode or performing SOme action.
In Java, an event listener is an object that implements an event listener interface, such
as ActionlListener, MouscListener, KeyListencr, or WindowListener. These interfaces define
methods that are called when a particular event occurs, and event listeners register themselves
with the component that is generating the events using the add<event>Listener method of
that component.
When an event occurs, the component notifies all of its registered listeners by calling
the appropriate method of each listener object. The listener then executes the code that is
associated with the event, which can inciude updating the user interface, processing data, or
performing some other action.

You might also like