0% found this document useful (0 votes)
21 views

Java QnA Unit4

Uploaded by

tyct826
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Java QnA Unit4

Uploaded by

tyct826
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Java QnA Unit: 04

Q.1) Explain the delegation event model of java


• Javas event handling mechanism is based on the delegation event model.
• This model handles user interaction with GUI components.
• It defines standard and consistent mechanisms to generate and process
events.
• The advantage of this approach is that the event processing logic is
separated from the user interface logic.
• The working of delegation event model can be summarized as follows:
• A source generates an event and sends it to one or more listeners.
• This event is then handled by the listener.


• A source generates an event in response to user action.
• Then source multicast the event to listeners.
• The listener receives the event and process it.
• An event is an object that describes a state change in a source.
• Example:-JCheckbox(event source) state change from ‘Unchecked’ to
‘Checked’ when used clicks on.
• Event is generated when a user interact with GUI element.
• Examples of user actions that generate events are: pressing buttons,
selecting an item in a list, clicking the mouse, pressing keys of a
keyboard, etc.
• An event source is an object that generates an event. (Eg:-JButton,
JCheckbox, JList, JChoice, JTextField, etc.)
• Sources may generate multiple events.
• A source must register listeners so that it can send notifications to
listeners about an event.
• The general form of registration method is:
• public void addTypeListener(TypeListener el)
• Where Type is the name of the event.
• The method that registers a mouse listener is called
addMouseListener().
• Event classes in java represent events.
• EventObject class is the superclass for all events.
• It is present in java.util package.

Q.2) Explain about event classes and event listener interfaces.


• Event classes in java represent events.
• EventObject class is the superclass for all events.
• It is present in java.util package.

• A listener is an object that is notified when an event occur.
• Listeners must be registered with the event sources.
• The methods that receive and process events are declared in a set of
interfaces present in java.awt.event.

Q.3) What are java foundation classes? Explain important features of JFC.
 They are a comprehensive set of GUI components and services which
dramatically simplify the development of desktop and web applications.
 JFC consists of AWT, Swing, Java2D and few other classes.
 The Swing components are the most notable part of JFC.
 The full range of JFC features is delivered as part of JDK 1.2. Swing is a
toolkit that contains a new set of GUI components with a pluggable look
and feel.
 Part of Java Foundation Classes.
 JFC provides a variety of features:
 1) Pluggable look and feel.
-Java Swing provides a pluggable look and feel architecture, which
allows developers to customize the appearance of their applications.
-Each platform has its own look and feel.
-This architecture allows Swing applications to look and feel like native
applications on any platform.
 2)Layout Managers
-Swing adds more layout managers to those provided by the AWT.
-Layout managers save a lot of time and effort when developing
applications.
-The layout managers are used to set how components within a container
are positioned and sized.
 3)Data Selection and Display Controls
-The controls like JList, JComboBox are data selection controls which
can handle large amounts of data easily.
-JTree is a very flexible control for displaying data organized in a
hierarchical form and JTable is used to display data that is organized in
two-dimensional row and column form and therefore is a natural choice
for representing data returned from queries made to a database.

Q.4) Write short notes on containers and JPanel.


 It is a subclass of Component class.
 A Container is a Component that can hold other Components.
 It is a mechanism to arrange components to form a graphical user
interface.
 The Container class defined all the data and methods common among
Containers.
 It has methods to add/remove components.
 Containers in Swing are classified as heavy weight containers or light
weight containers.
 Top level Containers (heavy weight)
 Examples:-JFrame, JApplet, JWindow, JDialog.
 Light weight container
 Examples:-Jpanel

 It is the simplest container class in java.


 It is an rectangular region to a frame or another panel solely used to hold
a group of components.
 It doesn't have title bar.
 Swing component JPanel is used to create a light weight panel.
 The default layout manager for a JPanel is FlowLayout.
 Constructors:
 JPanel() // Creates a new JPanel using the default layout manager.
 JPanel(LayoutManager layout) // Creates a new panel with the
specified layout manager.
Ex:-
import javax.swing.*;
import java.awt.*; //Color class is in awt package
public class JPanelExample extends JFrame {
public JPanelExample()
{
setSize(400,500); setLayout(null); setTitle("Panel Example");
setVisible(true);
JPanel p1=new JPanel();
JPanel p2=new JPanel();
p1.setBounds(0,0,100,100);
p2.setBounds(100,100,200, 200);
p1.setBackground(Color.red);
p2.setBackground(Color.blue);
JButton b1=new JButton("Btn 1");
JButton b2=new JButton("Btn 2");
b1.setBounds(20,50,75, 25);
b2.setBounds(100,150,75, 25);
p1.add(b1); p2.add(b2); add(p1); add(p2);
}
public static void main(String[] args)
{
JPanelExample f=new JPanelExample();
}
}
Q.5) Explain the constructors and any 4 methods JTextArea.
 Sometimes a single line of text input is not enough for a given task. To
handle these situations, the swing includes a simple multiline editor
called JTextArea.
 A JTextArea object is a multi-line region that displays text.
 It can be set to allow editing or to be read-only. [using setEditable()
method ]
 Following are the constructors for JTextArea:
o JTextArea( )
o JTextArea(int numLines, int numChars)
o JTextArea(String str)
o JTextArea(String str, int numLines, int numChars)
• JTextArea is a subclass of JTextComponent.
 Therefore, it supports the getText( ), setText( ), getSelectedText( ),
select( ), setSelectionStart(), setSelectionEnd(), isEditable( ), and
setEditable( ) methods.
 TextArea adds the following methods:
o void append(String str) //Appends the given text to the end of the
document.
o int getRows() //Returns the number of rows in the TextArea.
o int getColumns() //Returns the number of columns in the
TextArea.
o int getLineCount() //Determines the number of lines contained in
the area.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class sdemo4 extends JFrame implements ActionListener
{
JTextField tf;
JTextArea ta;
public sdemo4()
{
setVisible(true);
setLayout(new FlowLayout());
tf=new JTextField(10);
ta=new JTextArea(4,15);
add(tf);
add(ta);
tf.addActionListener(this);
setSize(500,500);
}
public void actionPerformed(ActionEvent e)
{
String str=tf.getText();
ta.append("\n"+str);
}
public static void main(String args[])
{
test3 t=new test3();
}
}
Q.6) What are the constructors of JCheckBox class? Give a brief description
on its event handling.
• In GUI design, checkboxes are used to take multiple option from a group
of options.
• JCheckBox is an implementation of a check box - an item that can be
selected or deselected, and which displays its state to the user.
• Any number of check boxes in a group can be selected.

Here's a brief description of event handling for JCheckBox:


1. Add an ItemListener: You can add an ItemListener to a JCheckBox using
the addItemListener() method. This listener listens for changes in the
state of the checkbox, i.e., whether it is checked or unchecked.
2. Implement the ItemListener Interface: You need to implement the
ItemListener interface in your code. This interface contains a single
method, itemStateChanged(), which gets called whenever the state of
the checkbox changes.
3. Handle the State Change: Inside the itemStateChanged() method, you
can write the code to handle the state change event. This typically
involves checking the state of the checkbox and performing actions
based on whether it's checked or unchecked.
import javax.swing.*;
import java.awt.event.*;
public class sdemo4 extends JFrame implements ItemListener
{
JLabel l,l1;
JCheckBox s1,s2,s3;
public sdemo4()
{
setLayout(null); setSize(600,600); setVisible(true);
l=new JLabel("Which of the following are your hobbies?");
l.setBounds(50,50,400,50);
s1=new JCheckBox("Playing Guitar");
s2=new JCheckBox("Listening Music");
s3=new JCheckBox("Watching Movies");
s1.setBounds(50,110,200,30);
s2.setBounds(50,150,200,30);
s3.setBounds(50,190,200,30);
l1=new JLabel("");
l1.setBounds(50,250,300,200);
add(l); add(s1); add(s2); add(s3); add(l1);
s1.addItemListener(this);
s2.addItemListener(this);
s3.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
String str1="",str2="",str3="";
if(s1.isSelected())
str1=s1.getLabel()+" ";
if(s2.isSelected())
str2=s2.getLabel()+" ";
if(s3.isSelected())
str3=s3.getLabel()+" ";
l1.setText(str1+str2+str3 );
}
public static void main(String args[]) {
sdemo4 t=new sdemo4();
}
}

Q.7) Write a program for free hand drawing on a JFrame.


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class frhand extends JFrame implements MouseListener,
MouseMotionListener
{
int x1,y1,x2,y2;
public frhand()
{
setLayout(new FlowLayout());
setSize(400,400);
setVisible(true);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mousePressed(MouseEvent e)
{
x1=e.getX();
y1=e.getY();
}
public void mouseDragged(MouseEvent e)
{
x2=e.getX();
y2=e.getY();
Graphics g=getGraphics();
g.drawLine(x1,y1,x2,y2);
x1=x2;
y1=y2;
}
public void mouseClicked(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
public static void main(String args[])
{
frhand t=new frhand();
}
}
Q.8) Describe JButton with the help of an example.
• This class creates a labeled button.
• The application can cause some action to happen when the button is
pushed.
• Button can have icon and rollover icon
• Generate ActionEvent when user clicks button


import javax.swing.*;
import java.awt.*;
public class sdemo2 extends JFrame
{
JButton y, n, m;
public sdemo2()
{
setVisible(true);
setLayout(new FlowLayout());
y = new JButton("Yes");
n = new JButton("No");
m = new JButton("May Be");
add(y);
add(n);
add(m);
setSize(500,500);
}
public static void main(String args[])
{
sdemo2 s=new sdemo2();
}
}

Q.9) Describe JRadioButton with the help of an example.


• In GUI design, radio buttons are used to take one option from a group of
options.
• JRadioButton is an implementation of a radio button - an item that can be
selected or deselected, and which displays its state to the user.
• It is used with a ButtonGroup object to create a single selection group of
radio buttons.

import javax.swing.*;
import java.awt.event.*;
public class sdemo4 extends JFrame implements ActionListener
{
JLabel l,l1;
JRadioButton s1,s2,s3;
public sdemo4()
{
setLayout(null); setSize(600,600); setVisible(true);
l=new JLabel("Which of the following are your hobbies?");
l.setBounds(50,50,400,50);
s1=new JRadioButton("Playing Guitar");
s2=new JRadioButton("Listening Music");
s3=new JRadioButton("Watching Movies");
s1.setBounds(50,110,200,30);
s2.setBounds(50,150,200,30);
s3.setBounds(50,190,200,30);
ButtonGroup bg=new ButtonGroup();
bg.add(s1); bg.add(s2);bg.add(s3);
l1=new JLabel("");
l1.setBounds(50,250,300,200);
add(l); add(s1); add(s2); add(s3); add(l1);
s1.addActionListener(this);
s2.addActionListener(this);
s3.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String str="";
JRadioButton r=(JRadioButton)e.getSource();
if(r==s1)
str+=s1.getLabel()+" ";
if(r==s2)
str+=s2.getLabel()+" ";
if(r==s3)
str+=s3.getLabel()+" ";
l1.setText(str);
}
public static void main(String args[]) {
sdemo4 t=new sdemo4();
}
}

Q.10) Describe JTextField and JPasswordField with the help of an example.


• It is displayed as a field that allows the user to enter a single line of text.
• It is a subclass of JTextComponent class.
• JTextField has a method to establish the string used as the command
string for the action event that gets fired.
• The java.awt.TextField used the text of the field as the command string
for the ActionEvent.
• JTextField will use the command string set with the setActionCommand
method if not null, otherwise it will use the text of the field as a
compatibility with java.awt.TextField.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*; // FlowLayout is in awt
class sdemo3 extends JFrame implements ActionListener{
JButton b1,b2,b3; JLabel l1; JTextField t1,t2;
public sdemo3() {
setVisible(true);
setLayout(new FlowLayout());
t1=new JTextField(25);
t2=new JTextField(25);
add(new JLabel("Enter first number:")); add(t1);
add(new JLabel("Enter Second number:")); add(t2);
b1=new JButton("+"); add(b1);
b2=new JButton("-"); add(b2);
b3=new JButton("*"); add(b3);
l1=new JLabel(" "); add(l1);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
setSize(500,150);
}
public void actionPerformed(ActionEvent e)
{
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
System.out.println(((JButton)e.getSource()).getActionCommand());
if(((JButton)e.getSource()).getActionCommand().equals("+"))
{
l1.setText("Sum="+(n1+n2));
}
if(e.getSource()==b2)
{
l1.setText("Difference="+(n1-n2));
}
if(e.getSource()==b3)
{
l1.setText("Product="+(n1*n2));
}
}
public static void main(String args[]) {
sdemo3 t=new sdemo3();
}
}
• JPasswordField allows the editing of a single line of text where the view
indicates something was typed, but does not show the original characters.
• It is used as a password text field.
• It works exactly like JTextField, except that each character is shown as a
specified character, such as an asterisk.
import javax.swing.*;
import java.awt.*;
class sdemo3 extends JFrame{
JPasswordField p;
public sdemo3() {
setVisible(true);
setLayout(new FlowLayout());
p=new JPasswordField(10);
p.setEchoChar('#');
add(p);
setSize(200,200);
}
public static void main(String args[]) {
sdemo3 t=new sdemo3();
} }

Q.11) Explain any 3 text-entry swing components.


» JTextField:-
• It is displayed as a field that allows the user to enter a single line of text.
• It is a subclass of JTextComponent class.
• JTextField has a method to establish the string used as the command
string for the action event that gets fired.
• The java.awt.TextField used the text of the field as the command string
for the ActionEvent.
• JTextField will use the command string set with the setActionCommand
method if not null, otherwise it will use the text of the field as a
compatibility with java.awt.TextField.

» JpasswordField:-
• JPasswordField allows the editing of a single line of text where the
view indicates something was typed, but does not show the original
characters.
• It is used as a password text field.
• It works exactly like JTextField, except that each character is shown
as a specified character, such as an asterisk.
• Important Methods:
• JPasswordField inherits from JTextField and hence it has all methods
of JTextField.
• It also has following methods defined in it:
• void setEchoChar(char c) //Sets the echo character for this
JPasswordField.
• char getEchoChar() // Returns the character to be used for
echoing.
» JTextArea:-
• Sometimes a single line of text input is not enough for a given task.
To handle these situations, the swing includes a simple multiline
editor called JTextArea.
• A JTextArea object is a multi-line region that displays text.
• It can be set to allow editing or to be read-only. [using setEditable()
method ]
• Following are the constructors for JTextArea:
• JTextArea( )
• JTextArea(int numLines, int numChars)
• JTextArea(String str)
• JTextArea(String str, int numLines, int numChars)

• int getRows() //Returns the number of rows in the TextArea.


• int getColumns() //Returns the number of columns in the
TextArea.
• void append(String str) //Appends the given text to the end of
the document.
• void insert(String str, int index) //Inserts the specified text at the
specified index.

Q.12) What are layout managers? Explain GridLayout in detail.


• Layout managers are used to organize GUI components within a GUI
container.
• It determines the size and position of components inside a Container
such as Applet or Frame.
• Each Container has a layout manager.
• Whenever the dimensions of the container change (e.g. user resizes the
window), layout manager recalculates the absolute coordinates of
components for them to fit the new container size.
• A container can contain another container.
• For example, a window can contain a panel, which is itself a container.
• The layout manager for the window determines how the panel is sized
and positioned inside the window, and the layout manager for the panel
determines how components are sized and positioned inside the panel.
• GridLayout:-
• The GridLayout manager divides the container into a given number of
rows and columns.
• All sections of the grid are equally sized and as large as possible.
• Therefore all components are equally sized.
• Constructors
• GridLayout(int r, int c, int hgap, int vgap)
• r – number of rows in the layout
• c – number of columns in the layout
• hgap – horizontal gaps between components
• vgap – vertical gaps between components
• GridLayout(int r, int c)
• r – number of rows in the layout
• c – number of columns in the layout
• No vertical or horizontal gaps.
• GridLayout()
• A single row and no vertical or horizontal gaps.
• Example:
import javax.swing.*;
import java.awt.*;
class demo extends JFrame
{
demo ()
{
setLayout(new GridLayout(5,5));
for(int i=0; i<25;i++)
{
add(new JButton("Button "+(i+1)));
}
}
public static void main(String args[])
{
demo d = new demo();
d.setTitle("GridLayout Example");
d.setSize(400,150);
d.setVisible(true);
}
}

Q.13) What are the advantages of using layout managers? Explain


BorderLayout in detail.
• No need to mention the absolute coordinates where each component is to
be placed. That is the layout manager automatically handles the
positioning of components.
• No need to specify the dimensions of components. That is the layout
manager automatically handles the dimension of components.

• BorderLayout:-
• A border layout lays out a container, arranging and resizing its
components to fit in five regions: north, south, east, west, and center.
• Each region may contain no more than one component, and is identified
by a corresponding constant: NORTH, SOUTH, EAST, WEST, and
CENTER.
• Constructors:-
• BorderLayout()-----Constructs a new border layout with no gaps
between components.
• BorderLayout(int hgap, int vgap)-----Constructs a border layout with
the specified gaps between components.
• At most five components can be added
• It is the default layout of a Frame.
• If you want more components, add a Panel, then add components to it.
• Following are the Fields present in BorderLayout for setting the region
where the Components are to be added.
• static String CENTER
• static String EAST
• static String WEST
• static String SOUTH
• static String NORTH
• When adding a component to a container with a border layout, use
one of these five constants, for example:
Panel p = new Panel();
Button b1=new Button("CLICK ME");
p.setLayout(new BorderLayout());
p.add(b1, BorderLayout.SOUTH);

Q.14) Briefly explain the following:


a. Mouse event handling:

b. Adapter classes:
• Adapter classes are abstract classes present in java.awt.event package.
• The adapter classes help programmers to do event handling with less
code.
• Every listener that includes more than one abstract method has got a
corresponding adapter class.
• The adapter classes are very special classes that are used to make event
handling very easy.
• There are listener interfaces that have many methods for event handling
and we know that by implementing an interface we have to implement
all the methods of that interface.
• But sometimes we need only one or some methods of the interface.
• In that case, Adapter classes are the best solution.
• Adapter classes contain default implementation for the corresponding
Listener interface.
• The following examples contain the following Adapter classes:
• ContainerAdapter class.
• KeyAdapter class.
• FocusAdapter class.
• WindowAdapter class.
• MouseAdapter class.
• ComponentAdapter class.
• MouseMotionAdapter class.

Q.15) Write a java swing program that display a label with an image.
import javax.swing.*;
public class sdemo1 extends JFrame {
public sdemo1()
{
setSize(400,500); setLayout(null);
setTitle("Label Example"); setVisible(true);
ImageIcon i=new ImageIcon("C:/Users/Agi/Downloads/ix.jpg");
JLabel l=new JLabel(i);
add(l);
l.setBounds(50,50,300,400);
}
public static void main(String[] args) {
sdemo1 f=new sdemo1();
}
}

You might also like