Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

unit 5 java

Uploaded by

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

unit 5 java

Uploaded by

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

Swing

Unit 5
What is swing?
In Java, Swing is a set of graphical user interface (GUI) components that are part of the Java Foundation Classes (JFC) library.
Swing provides a rich set of GUI components, including buttons, text fields, labels, menus, and more, allowing developers to
create interactive and visually appealing desktop applications in Java.
Swing is built on top of the Abstract Window Toolkit (AWT) but provides a more advanced and flexible set of components
compared to AWT. Swing components are lightweight, meaning they are not dependent on the native platform's GUI
components and have a consistent appearance across different operating systems.
Some key features of Swing include:
1. Lightweight components: Swing components are lightweight and independent of the underlying operating system's GUI
components. This allows Swing applications to have consistent behavior and appearance across different platforms.
2. Customizable look and feel: Swing allows developers to customize the look and feel of their applications using pluggable
look and feel (PLAF) mechanisms. This means that developers can choose different styles and themes for their applications.
3. Rich set of components: Swing provides a wide range of GUI components for building user interfaces, including buttons, text
fields, labels, checkboxes, radio buttons, tables, trees, and more.
4. Event-driven programming model: Swing follows an event-driven programming model, where user interactions and system
events trigger responses from the application. Developers can register event listeners to handle these events and update the
application's state accordingly.
5. Layout managers: Swing provides layout managers that help developers arrange GUI components within containers
dynamically. Layout managers handle the positioning and sizing of components based on various factors such as container size,
component preferences, and alignment constraints.
Overall, Swing has been widely used for developing desktop applications in Java due to its flexibility, portability, and extensive
set of features. However, with the introduction of JavaFX, which offers more modern features and improved performance,
Swing has seen decreasing popularity in recent years.
What are swing classes?
Swing classes in Java represent the various components and utilities provided by the Swing framework for building graphical user interfaces
(GUIs). These classes are part of the javax.swing package and its subpackages. Here are some common Swing classes:
1. JFrame: JFrame is a top-level container that represents the main window of a Swing application. It provides methods for managing the
window's appearance, such as setting its size, title, and default close operation.
2. JPanel: JPanel is a container that can hold other Swing components. It is often used to group related components together within a
window or dialog.
3. JButton: JButton is a clickable button component that triggers an action when pressed. It is commonly used to perform actions like
submitting a form or initiating a process.
4.JLabel: JLabel is a non-editable text component that displays a single line of text or an image. It is often used to provide descriptive text or
headings in a GUI.
5. JTextField: JTextField is a text input component that allows users to enter and edit text. It provides methods for getting and setting the
text value entered by the user.
6. JTextArea: JTextArea is a multiline text input component that allows users to enter and edit longer text passages. It provides scrolling
functionality for viewing and editing large amounts of text.
7. JComboBox: JComboBox is a dropdown list component that allows users to select an item from a list of options. It can be configured to
display a predefined list of items or allow users to enter custom text.
8. JCheckBox: JCheckBox is a checkbox component that allows users to toggle between two states: selected and deselected. It is commonly
used for representing binary choices or toggling options.
9. JRadioButton: JRadioButton is a radio button component that allows users to select one option from a group of mutually exclusive
options. It is often used in conjunction with other radio buttons to represent multiple-choice questions or settings.
10. Layout Managers: Layout managers such as BorderLayout, FlowLayout, GridLayout, and GroupLayout are classes used to arrange Swing
components within containers dynamically. They handle the positioning and sizing of components based on various layout constraints.
These are just a few examples of Swing classes. Swing provides a comprehensive set of classes for building GUI applications, including
support for menus, dialogs, tables, trees, and more. Developers can combine these classes to create rich and interactive user interfaces in
Java applications.
Working with Jframe windows in
java:
Thе Java JFramе is an еssеntial componеnt of Java Swing, which is a part of thе Java SWT(Standard Widgеt Toolkit). JFrame
in Java is a class that allows you to crеatе and manage a top-lеvеl window in a Java application. It sеrvеs as thе main window for
GUI-basеd Java applications and providеs a platform-indеpеndеnt way to crеatе graphical usеr intеrfacеs. In Java JFrame is a
part of javax.swing package.
Constructor of Java JFrame
Constructor Description

JFrame() This is the default constructor for JFrame. It creates a new frame with no title

JFrame(String title) This constructor creates a new frame with the specified title.

This constructor creates a JFrame that uses the specified graphics


JFrame(GraphicsConfiguration gc)
configuration.

JFrame(String title, This constructor creates a JFrame with the specified title and using the
GraphicsConfiguration gc) specified graphics configuration.

JFrame(Rectangle bounds) This constructor creates a JFrame with the specified bounds.

JFrame(String title, Rectangle


This constructor creates a JFrame with the specified title and bounds.
bounds)
Methods of Java JFrame
Methods Description
setTitle(String title) Sets the title of the JFrame.

setSize(int width, int height) Sets the size of the JFrame.

setDefaultCloseOperation(int Sets the default close operation for the JFrame. Common options include JFrame.EXIT_ON_CLOSE,
operation) JFrame.HIDE_ON_CLOSE, and JFrame.DO_NOTHING_ON_CLOSE.

setVisible(boolean b) Sets the visibility of the JFrame. Pass true to make it visible and false to hide it.

setLayout(LayoutManager manager) Sets the layout manager for the JFrame, which controls how components are arranged within the frame.

add(Component comp) Adds a Swing component to the JFrame.

remove(Component comp) Removes a component from the JFrame.

validate() Forces the layout manager to recalculate the layout of components within the JFrame.

setResizable(boolean resizable) Controls whether the user can resize the JFrame.

setIconImage(Image image) Sets the icon (image) for the JFrame window.
Parent Classes of JFrame Methods
Java JFrame is the part of Java Swing and the classes from where all the methods associated with JFrame are inherited are
mentioned below:
1. java.awt.Frame
2. java.awt.Container
3. java.awt.Window
4. javax.swing.JFrame
Some Fields for Java JFrame
Fields Description
A field that specifies the default operation to perform when
EXIT_ON_CLOSE (int) the user closes the JFrame. It’s typically used with the
setDefaultCloseOperation() method.

It is constant that specifies an operation to perform when the


DISPOSE_ON_CLOSE (int) user closes the JFrame.It disposes of the JFrame but doesn’t
exit the application.

HIDE_ON_CLOSE (int) Specifies that the JFrame should be hidden but not disposed
of when the user closes it.

Indicates that no action should be taken when the user closes


DO_NOTHING_ON_CLOSE (int) the JFrame.
Programs to
// Java Swing Program to demonstrate
implement JFrame
// a simple JFrame
import javax.swing.JFrame; Output:
import javax.swing.JLabel;
// Driver Class
public class MyJFrame {
// main function
public static void main(String[] args)
{
// Create a new JFrame
JFrame frame = new JFrame("My First JFrame");
// Create a label
JLabel label = new JLabel("Geeks Premier League 2023");
// Add the label to the frame
frame.add(label);
// Set frame properties
frame.setSize(300,200); // Set the size of the frame
// Close operation
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make the frame visible
frame.setVisible(true);
}
}
Working with graphics in swing
Graphics is an abstract class provided by Java AWT which is used
to draw or paint on the components. It consists of various fields
which hold information like components to be painted, font, color,
XOR mode, etc., and methods that allow drawing various shapes
on the GUI components. Graphics is an abstract class and thus
cannot be initialized directly. Objects of its child classes can be
obtained in the following two ways.
1. Inside paint() or update() method
It is passed as an argument to paint and update methods and
therefore can be accessed inside these methods. paint() and
update() methods are present in the Component class and thus
can be overridden for the component to be painted.
• void paint(Graphics g)
• void update(Graphics g)
Example:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyFrame extends Frame {
public MyFrame()
{ Output:
setVisible(true);
setSize(300, 200);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.drawRect(100, 100, 100, 50);
}
public static void main(String[] args)
{
new MyFrame();
}
2. getGraphics() method
This method is present in the Component class and thus can be called on any
Component in order t
public Graphics getGraphics(): Creates a graphics context for the component. This
method will return null if the component is currently not displayable.o get the
Graphics object for the component.
Note: Painting must be preferably done using the paint() method. Graphics drawn
via object obtained from getGraphics() method are temporary and are lost when the
component is repainted again. Drawing might happen right away but repainting
may take some time and therefore remove the effects of code done through
getGraphics().
Example:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyFrame extends Frame {
public MyFrame()
{
setVisible(true);
setSize(300, 200);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
System.out.println("painting...");
}
public static void main(String[] args)
{
MyFrame f = new MyFrame();
Graphics g = f.getGraphics();
try {
Thread.sleep(1000);
}
catch (Exception e) {
}
System.out.println("drawing...");
g.drawRect(100, 100, 100, 50);
System.out.println("drawn...");
}
Commonly used methods of Graphics class
1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with
the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with
the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between
the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10.public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11.public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
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);
}
Working With Colour
The Color class is a part of Java Abstract Window Toolkit(AWT) package. The Color class creates color by using
the given RGBA values where RGBA stands for RED, GREEN, BLUE, ALPHA or using HSB value where HSB
stands for HUE, SATURATION, BRIcomponents. The value for individual components RGBA ranges from 0 to
255 or 0.0 to 0.1. The value of alpha determines the opacity of the color, where 0 or 0.0 stands fully transparent
and 255 or 1.0 stands opaque.
Constructors of Color Class
1. Color(ColorSpace c, float[] co, float a) : Creates a color in the specified ColorSpace with the color
components specified in the float array and the specified alpha.
2. Color(float r, float g, float b) : creates a opaque color with specified RGB components(values are in range 0.0
– 0.1)
3. Color(float r, float g, float b, float a) : creates a color with specified RGBA components(values are in range
0.0 – 0.1)
4. Color(int rgb): Creates an opaque RGB color with the specified combined RGB value consisting of the red
component in bits 16-23, the green component in bits 8 – 15, and the blue component in bits 0-7.
5. Color(int rgba, boolean b): Creates an sRGB color with the specified combined RGBA value consisting of the
alpha component in bits 24-31, the red component in bits 16 – 23, the green component in bits 8
– 15, and the blue component in bits 0 – 7.
6. Color(int r, int g, int b) : Creates a opaque color with specified RGB components(values are in range 0 – 255)
7. Color(int r, int g, int b, int a) : Creates a color with specified RGBA components(values are in range 0 – 255)
Commonly Used Methods In Color Class
method explanation
brighter() creates a new Color that is a brighter version of this Color.
createContext(ColorModel cm,
Rectangle r, Rectangle2D r2d, creates and returns a PaintContext used to generate a solid color field pattern.
AffineTransform x,
RenderingHints h)
darker() /td> creates a new Color that is a darker version of this Color.

decode(String nm) converts a String to an integer and returns the specified opaque Color.
equals(Object obj) determines whether another Color object is equal to this Color.
getAlpha() returns the alpha component in the range 0-255.
getBlue() returns the blue component in the range 0-255 .
getColor(String nm) Finds a color in the system properties.
getColor(String nm, Color v) Finds a color in the system properties.
getColor(String nm, int v) Finds a color in the system properties.
getColorComponents(ColorSpace returns a float array containing only the color components of the Color in the ColorSpace specified by the cspace parameter.
cspace, float[] compArray)
getColorComponents(float[] returns a float array containing only the color components of the Color, in the ColorSpace of the Color.
compArray)
getColorSpace() returns the ColorSpace of this Color.
getGreen() returns the green component in the range 0-255 in the default sRGB space.
getRed() returns the red component in the range 0-255 in the default sRGB space.
getRGB() Returns the RGB value representing the color in the default sRGB ColorModel.
getHSBColor(float h, float s, float Creates a Color object based on the specified values for the HSB color model.
b)
getTransparency() returns the transparency mode for this Color.
hashCode() computes the hash code for this Color.
HSBtoRGB(float h, float s, float b) Converts the HSB value to RGB value
RGBtoHSB(int r, int g, int b, converts the RGB value to HSB value
float[] hsbvals)
Adding and removing controls
Programs can be written to add different kinds of controls to your application. You can add single control or you can also add
multiple controls to your application by writing an appropriate program. Similarly, you can remove the added control with the
help of a program.
In order to include a control in a window, we must add it to the window. So, we must first create an instance of the desired
control and then add it to a window by calling add( ), which is defined by Container. The add ( ) method has several forms. The
following form is the one that is used for the first part of this
Component add(Component compObj)
Here, compObj is an instance of the control that we want to add. A reference to compObj is returned. Once a control has been
added, it will automatically be visible whenever its parent window is displayed. Sometimes we will want to remove a control
from a window when the control is no longer needed. For doing this, call remove( ). This method is also defined by Container. It
has this general form:
void remove(Component obj)
Here, obj is a reference to the control that we want to remove. We can remove all controls by calling removeAll( ).
To add a control to a collection programmatically
• Create an instance of the control to be added.
• Set properties of the new control.
• Add the control to the Controls collection of the parent control.
To remove controls from a collection programmatically
• Remove the event handler from the event
• Use the Remove method to delete the desired control from the panel’s Control collection.
Responding To Controls
Responding to controls in a Java Swing application involves adding event listeners to
the controls (such as buttons, text fields, etc.) and defining the actions to be performed
when these controls trigger events. Here's how you can respond to controls in Swing:
1. Adding Event Listeners
You need to add event listeners to the controls to handle user interactions. For
example, you can add an action listener to a button to respond to clicks, or add a
document listener to a text field to respond to text changes.
Example:
import javax.swing.*;
import java.awt.event.*;
public class MyApplication extends JFrame {
public MyApplication() {
setTitle("My Application");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a button
JButton button = new JButton("Click Me");
// Add action listener to the button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Action to perform when the button is clicked
JOptionPane.showMessageDialog(MyApplication.this, "Button Clicked!");
}
});
// Add the button to the frame
getContentPane().add(button);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new MyApplication().setVisible(true);
});
}
Output:

When you click on click me


2. Defining Actions: Inside the event listener, you define the actions to be
performed when the control triggers an event. For example, when a button is
clicked, you can show a message dialog, update the GUI, or perform any other task
based on your application’s logic.
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Action to perform when the button is clicked
JOptionPane.showMessageDialog(MyApplication.this, "Button Clicked!");
}
});
By adding event listeners and defining actions to respond to controls in your Java
Swing application, you can create interactive user interfaces that allow users to
interact with your application and trigger specific actions based on their inputs.
Jlabels:
JLabel is a class of java Swing . JLabel is used to display a short string or an image icon. JLabel can
display text, image or both . JLabel is only a display of text or image and it cannot get focus . JLabel is
inactive to input events such a mouse focus or keyboard focus. By default labels are vertically centered
but the user can change the alignment of label.
Constructor of the class are :
1.JLabel() : creates a blank label with no text or image in it.
2.JLabel(String s) : creates a new label with the string specified.
3.JLabel(Icon i) : creates a new label with a image on it.
4.JLabel(String s, Icon i, int align) : creates a new label with a string, an image and a specified
horizontal alignment
Commonly used methods of the class are :
5.getIcon() : returns the image that the label displays
6.setIcon(Icon i) : sets the icon that the label will display to image i
7.getText() : returns the text that the label will display
8.setText(String s) : sets the text that the label will display to string s
Example1:
// Java Program to create a
// blank label and add text to it.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class text extends JFrame {
// frame
static JFrame f;
// label to display text
static JLabel l;
// default constructor
text()
{
}
// main class
public static void main(String[] args)
{
// create a new frame to store text field and button
f = new JFrame("label");
// create a label to display text
l = new JLabel();
// add text to label
l.setText("label text");
// create a panel
JPanel p = new JPanel();
// add label to panel
p.add(l);
// add panel to frame
f.add(p);
// set the size of frame
f.setSize(300, 300);
f.show();
}
Example 2:
// Java Program to create a label
// and add image to it .
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class text extends JFrame {
// frame
static JFrame f;
// label to display text
static JLabel l;
// default constructor
text()
{
}
// main class
public static void main(String[] args)
{
// create a new frame to store text field and button
f = new JFrame("label");
// create a new image icon
ImageIcon i = new ImageIcon("f:/image.png");
// create a label to display image
l = new JLabel(i);
// create a panel
JPanel p = new JPanel();
// add label to panel
p.add(l);
// add panel to frame
f.add(p);
// set the size of frame
f.setSize(500, 500);
f.show();
}
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
JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:


Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) It is used to add the action listener to this object.
Example1:
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Example2: j button with action
listener
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
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.
Commonly
Constructor used Constructors:
Description
JCheckBox() Creates an initially unselected check box button with no text, no
icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it is
selected) initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the Action
supplied.
Commonly
Methods used Methods: Description
AccessibleContext It is used to get the AccessibleContext
getAccessibleContext() associated with this JCheckBox.
protected String paramString() It returns a string representation of
this JCheckBox.
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();
Checkbox group:
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only one check box button is allowed to be in "on"
state and remaining check box button in "off" state. It inherits the object class.
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special control for creating radio buttons in AWT.
Example:

import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, 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 CheckboxGroupExample();
}
Choice control:
Choice class is part of Java Abstract Window Toolkit(AWT). The Choice class presents a pop- up menu for the user, the user may select an item
from the popup menu. The selected item appears on the top. The Choice class inherits the Component.
Constructor for the Choice class
• Choice() : creates an new empty choice menu .
Choice Class Methods
Sr. no. Method name Description
1. void add(String item) It adds an item to the choice menu.
2. void It adds the item listener that receives item events from the choice menu.
addItemListener(ItemListe
ner l)
3. void addNotify() It creates the peer of choice.
4. AccessibleContext It gets the accessbile context related to the choice.
getAccessibleContext()
5. String getItem(int index) It gets the item (string) at the given index position in the choice menu.
6. int getItemCount() It returns the number of items of the choice menu.
7. ItemListener[] It returns an array of all item listeners registered on choice.
getItemListeners()
8. T[] Returns an array of all the objects currently registered as FooListeners upon this
getListeners(Class listenerT Choice.
ype)
9. int getSelectedIndex() Returns the index of the currently selected item.
10. String getSelectedItem() Gets a representation of the current choice as a string.
11. Object[] Returns an array (length 1) containing the currently selected item.
getSelectedObjects()
12. void insert(String item, int Inserts the item into this choice at the specified position.
index)
15. protected void Processes item events occurring on this Choice menu by dispatching them to any
processItemEvent registered ItemListener objects.
(ItemEvent e)
16. void remove(int position) It removes an item from the choice menu at the given index position.
17. void remove(String item) It removes the first occurrence of the item from choice menu.
18. void removeAll() It removes all the items from the choice menu.
19. void removeItemListener It removes the mentioned item listener. Thus is doesn't receive item events from the
(ItemListener l) choice menu anymore.
20. void select(int pos) It changes / sets the selected item in the choice menu to the item at given index
position.
21. void select(String str) It changes / sets the selected item in the choice menu to the item whose string value is
equal to string specified in the argument.
Example:
// importing awt class
import java.awt.*;
public class ChoiceExample1 {
// class constructor
ChoiceExample1() {
// creating a frame
Frame f = new Frame();
// creating a choice component
Choice c = new Choice();
// setting the bounds of choice menu
c.setBounds(100, 100, 75, 75);
// adding items to the choice menu
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
// adding choice menu to frame
f.add(c);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new ChoiceExample1();
}
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.
Commonly used Constructors:
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified
array.
JList(ListModel<ary> Creates a JList that displays elements from the specified,
Commonly
dataModel) used Methods:non-null, model.
Methods Description
Void It is used to add a listener to the list, to be notified each time a change to
addListSelectionListener(Li the selection occurs.
stSelectionListener
listener)
int getSelectedIndex() It is used to return the smallest selected cell index.
ListModel getModel() It is used to return the data model that holds a list of items displayed by
the JList component.
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();
}
Jtextfeild:
JTextField is a part of javax.swing package. The class JTextField is a component that allows editing of a
single line of text. JTextField inherits the JTextComponent class and uses the interface SwingConstants.
The constructor of the class are :
1.JTextField() : constructor that creates a new TextField
2.JTextField(int columns) : constructor that creates a new empty TextField with specified number of
columns.
3.JTextField(String text) : constructor that creates a new empty text field initialized with the given
string.
4.JTextField(String text, int columns) : constructor that creates a new empty textField with the given
string and a specified number of columns .
5.JTextField(Document doc, String text, int columns) : constructor that creates a textfield that uses
the given text storage model and the given number of columns.
Methods of the JTextField are:
6.setColumns(int n) :set the number of columns of the text field.
7.setFont(Font f) : set the font of text displayed in text field.
8.addActionListener(ActionListener l) : set an ActionListener to the text field.
9.int getColumns() :get the number of columns in the textfield.
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);
}
JtextArea:
JTextArea is a part of java Swing package . It represents a multi line area that displays text. It is used to edit
the text . JTextArea inherits JComponent class. The text in JTextArea can be set to different available fonts
and can be appended to new text . A text area can be customized to the need of user .

Constructors of JTextArea are:


1.JTextArea() : constructs a new blank text area .
2.JTextArea(String s) : constructs a new text area with a given initial text.
3.JTextArea(int row, int column) : constructs a new text area with a given number of rows and columns.
4.JTextArea(String s, int row, int column) : constructs a new text area with a given number of rows and
columns and a given initial text.
Commonly used methods :
5.append(String s) : appends the given string to the text of the text area.
6.getLineCount() : get number of lines in the text of text area.
7.setFont(Font f) : sets the font of text area to the given font.
8.setColumns(int c) : sets the number of columns of the text area to given integer.
9.setRows(int r) : sets the number of rows of the text area to given integer.
10.getColumns() : get the number of columns of text area.
Example:
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
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.
Constructors:
1.JMenuBar() : Creates a new MenuBar.
2.JMenu() : Creates a new Menu with no text.
3.JMenu(String name) : Creates a new Menu with a specified name.
4.JMenu(String name, boolean b) : Creates a new Menu with a specified name and boolean
value specifies it as a tear-off menu or not. A tear-off menu can be opened and dragged away
from its parent menu bar or menu.
Commonly used methods:
5.add(JMenu c) : Adds menu to the menu bar. Adds JMenu object to the Menu bar.
6.add(Component c) : Add component to the end of JMenu
7.add(Component c, int index) : Add component to the specified index of JMenu
8.add(JMenuItem menuItem) : Adds menu item to the end of the menu.
9.add(String s) : Creates a menu item with specified string and appends it to the end of menu.
Example:
import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
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.
Commonly used Constructors:
1.JDialog() : creates an empty dialog without any title or any specified owner
2.JDialog(Frame o) :creates an empty dialog with a specified frame as its owner
3.JDialog(Frame o, String s) : creates an empty dialog with a specified frame as its owner
and a specified title
4.JDialog(Window o) : creates an empty dialog with a specified window as its owner
5.JDialog(Window o, String t) : creates an empty dialog with a specified window as its
owner and specified title.
6.JDialog(Dialog o) :creates an empty dialog with a specified dialog as its owner
7.JDialog(Dialog o, String s) : creates an empty dialog with a specified dialog as its owner
and specified title.
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();
}
Event Handling:
Changing the state of an object is known as an event. For
example, click on button, dragging mouse etc. The java.awt.event
package provides many event classes and Listener interfaces for
event handling.
Java Event classes Event
and Listener interfaces
Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and
MouseMotionListener
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:
• 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){}
Java Event Handling Code
• We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
Example:
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame 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
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}

You might also like