0% found this document useful (0 votes)
35 views45 pages

Swing Componenets New

Swing is a GUI toolkit for Java that includes graphical user interface components like text boxes and buttons, provides a uniform look and feel across platforms, and defines components in the javax.swing package; common Swing components include JButton, JLabel, JTextField and JCheckBox as well as containers like JPanel and menus built from JMenuBar, JMenu, and JMenuItem.

Uploaded by

vedant kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views45 pages

Swing Componenets New

Swing is a GUI toolkit for Java that includes graphical user interface components like text boxes and buttons, provides a uniform look and feel across platforms, and defines components in the javax.swing package; common Swing components include JButton, JLabel, JTextField and JCheckBox as well as containers like JPanel and menus built from JMenuBar, JMenu, and JMenuItem.

Uploaded by

vedant kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Swing Components

 It is a GUI Toolkit for Java.

 Swing is part of the Java Foundation Classes (JFC).

 Swing includes graphical user interface (GUI) components


such as Text Boxes, Buttons, Scroll Bar, Tables, Menus, etc.

 The advantage is uniform behavior on all platforms.

 The Swing classes are defined in package javax.swing.

 Swing has been included as part of the Java Standard Edition 1.2.

1
Class Hierarchy:

2
Class Hierarchy:

3
Component:
It is an object having a graphical representation that can be
displayed on the screen.

Component can be used to interact with the user.

The Component class is the abstract super class of Abstract


Window Toolkit components.

All user interface elements are the subclass of Component class.

It defines over 100 of methods which are responsible for managing


event, positioning and sizing the window, and managing colors.

Examples:
Buttons, Checkboxes, Scrollbars, etc.

4
Methods of Component Class:

Methods Meaning
Graphics getGraphics (): It returns the graphics context for this
component.

int getHeight (): It returns the current height of this component.

int getWidth (): It returns the current width of this component.

Color getForeground (): It is used to get fore ground color of this


component.

Color getBackground (): It is used to get back ground color of this


component.

Font getFont (): It is used to get font of this component.

And more…
5
Container:
Container is the sub class of the Component.

It allows us to add other components within it.

Other Container objects can be stored inside a Container.

Then the outside container is responsible for laying out any


component that it contains.

Example:
Panel.

6
Methods of Container:

Methods Meaning
add (Component): It adds the specified component to
the end of this container.

add (Component, int): It adds the specified component to


this container at the given position.

void paint (Graphics g): It paints the container.

setLayout (LayoutManager mgr): It sets the specified layout manager


for this container.

7
Panel:
The Panel class is concrete sub class of Container.

This class does not have any new methods,


They simply extends Container class.

It is super class of Applet,


i.e. When screen output is directed to an applet,
It is drawn on the surface of a panel object.

Other components can be added to a Panel object.

8
 AWT Component classes Swing Component Classes

Button JButton
Frame JFrame
Panel JPanel
Label JLable
TextField JTextField
CheckBox JCheckBox
Choice JComboBox
List JList
JTree
JTable

And many more…

9
JLabel: -
JLabel (String s)
JLabel (Icon ic)
JLabel (String s, Icon ic, int align)
Where,
String s : It is the caption string of label.
Icon ic : It is the image displayed on label.
int align : It is alignment of an image on label.
LEFT, RIGHT, CENTER, LEADING,
TRAILING
Methods: -
Icon getIcon () : It returns the image of a label.

void setIcon () : It sets an image as icon on label.

String getText () : It returns the caption of label.

void setText () : It sets text as caption on label.

10
JButton: -
It provides the functionality of push button.
It allows an icon, a string, or both to be associated on button.
JButton (String s)
JButton (Icon ic)
JButton (String s, Icon ic)
e.g.
ImageIcon icn = new ImageIcon (“file.gif”);
JButton b1 = new JButton (icn);

JCheckBox: -
JCheckBox (String s)
JCheckBox (Icon ic)
JCheckBox (Icon ic, boolean state)
JCheckBox (String s, boolean state)
JCheckBox (String s, Icon ic)
JCheckBox (String s, Icon ic, boolean state)
11
JRadioButton: -
Radio buttons must be configured into a group.
Only one of the button from group can be selected at any time.
JRadioButton (String s)
JRadioButton (Icon ic)
JRadioButton (String s, boolean state)
JRadioButton (Icon ic, boolean state)
JRadioButton (String s, Icon ic)
JRadioButton (String s, Icon ic, boolean state)

JComboBox: -
It displays a drop-down list that allows list that allows a user to
select a different entry.
JComboBox ()
JComboBox (Vector V)

Where,
V is vector that initializes the combo box.
It may be of any type.

12
JTextArea: -
Text area is multiline text area which is used to display plain text.
JTextArea();
JTextArea(int row, int col);
JTextArea(String text);
JTextArea(String text, int row, int col);

Methods of JTextArea:
void append(String str)
void insert(String str, int pos)

void replaceRange(String str, int start, int end)

void setFont(font)

void setTabSixe(int size)

void setLineWrap(Booloean wp)

void setText(String str);

String getText(); 13
Menus: -
Menus consist of Menu Bar on the top of the window having names of
pull down menus.

Steps: -
 Create menu bar by using JMenuBar class of swing.
JMenuBar mb = new JMenuBar ();

 A MenuBar is a component that we can add it on top of Frame.


setJMenuBar (mb);

 Create object of Menu class and add it in to the menu bar as follows.
JMenu file = new JMenu (“File”);

 Create Menu item by using JMenuItem class and add these menu items
in specific menu.

JMenuItem nw = new JMenuItem (“New”);


JMenuItem sv = new JMenuItem (“Save”);
file.add(nw);
file.add(sv);
14
 We registered the Menu Item to ActionListener.
nw.addActionListener(listobj);

Constructors of all the above classes: -


JMenuBar ()
JMenu (String s)
JMenuItem (String s)
Methods:
add (JMenu menu) : Adds Menu to Menu bar
add (JMenuItem item) : Adds Menu Item in to Manu
void addseparator () : Adds a separator line to the
menu.
void remove(int index) : Removes specific item from
menu
void remove(JMenuItem item) : Removes specific item from
menu
void setJMenuBar(JMenuBar mb): Sets the menu bar for his
frame.

15
Icons in Menu Item: -
We can also add image as icon in as menu item along with text.
We can specify it in constructor as

JMenuItem (String str, Icon icn)

By default the menu item text is placed to the right of the icon.

CheckBox & Radio button in Menu Item: -

We can also add check box and radio button as menu item by
using following constructor.

Checkbox and radio button can be display as menu item as follows…

JCheckBoxMenuItem cbm1 = new JCheckBoxMenuItem (“Read Only”);

JRadioButtonMenuItem rbm1 = new JRadioButtonMenuItem (“Write


Only”);

16
Keyboard Mnemonics and Accelerators: -
We can specify the Keyboard Mnemonics for menu, items follows.
JMenuItem cut = new JMenuItem (“Cut”, ‘T’)

The keyboard mnemonic is displayed automatically in the menu, with the


mnemonic letter underlined. i.e. Cut , Copy.

So when the menu displayed, the user just need to press the T key or C key
to select Cut or Copy menu item form it.

We can also set the mnemonic for menu as follows,


setMnemonic (ch): ch is mnemonic character.
e.g.
JMenu help = new JMenu (“Help”);
help.setMnemonic (‘H’);

Mnemonics are used to select the menu item only form the currently opened
menus.

17
Accelerators: -
These are the keyboard shortcuts that let us select menu item
without ever opening a menu.

e.g.

If we want to set accelerator for the menu item save from the file menu

i.e. CTRL+S

JMenu file = new JMenu (“File”);


JMenuItem save = new JMenuItem (“Save”);
file.add (save);

save.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_S,


InputEvent.CTRL_MASK));

18
Pop – Up Menus: -
A pop up menu is a menu that is not attached to a menu bar
that floats somewhere.

JPopMenu pop = new JPopMenu ();


Then,
We can add different menu item in it as follows

JMenuItem cut = new JMenuItem (“Cut”);


JMenuItem cpy = new JMenuItem (“Copy”);
pop.add (cut);
pop.add (cpy);

We can also set the position of the pop up menu on the frame by using following
method.
pop.show (panel, X, Y);
Where,
panel is parent component on which the pop up menu get displays
X is x-coordinate on panel
Y is y-coordinate on panel

19
Graphics Class:-
The Graphics class is the abstract base class for all
graphics contexts.

It allows an application to draw onto components as


well as onto off-screen images.

The AWT supports a rich assortment of graphics methods. All


graphics are drawn relative to a window.

This can be the main window of an applet,


Or
A stand alone application window.

The origin of each window is top-left corner and it (0, 0).

Coordinates are specified in pixels.


20
A graphics context is encapsulated by the Graphics class and it is
obtained by following two ways.

1. It is passed to an applet when one of its various methods, such as


paint() or update () get called.

2. It is returned by the getGraphics () method of the Component.

Graphics class defines a number of drawing functions.

Each shape can be drawn edge-only or filled.

Objects are drawn and filled by currently selected color,


by default it is black

21
The methods of Graphics class are as follows:
void drawLine (int x1, int y1, int x2, int y2)
Where,
x1 & y1 the coordinate of first point.
x2 & y2 the coordinate of second point.

void drawRect (int x, int y, int width, int height)


void fillRect (int x, int y, int width, int height)
Where,
x & y is the coordinate starting point of the rectangle.
width is the width of the rectangle.
height is the height of the rectangle.

void drawRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight)


void fillRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight)
Where,
x & y is the coordinate of the rectangle..
width – is the width of the rectangle.
height – is the height of the rectangle.
arcWidth – is the horizontal diameter of the arc at the four corners.
arcHeight – is the vertical diameter of the arc at the four corners
22
void clearRect (int x, int y, int width, int height)
Where,
x & y is the coordinate of the rectangle.
width - the width of the rectangle.
height - the height of the rectangle.

void drawOval (int x, int y, int width, int height)


void fillOval (int x, int y, int width, int height)
Where,
x & y is the coordinate of the upper left corner of the oval.
width - the width of the oval to be drawn.
height - the height of the oval to be drawn.

void drawString (String str, int x, int y)


Where,
str - the string to be drawn.
x & y is the position of the left most character of string.
23
import java.awt.*;
class GraphicsPanel extends Panel
{
GraphicsPanel() { }

public void paint(Graphics g)


{
//g.setColor(Color.red);
//g.setFont(new Font("Lucida Console", Font.BOLD, 20));
g.drawString("Graphics Demo", 100, 20);
g.setColor(Color.green);
g.drawLine(50, 50, 250, 50);
g.setColor(Color.orange);
g.drawRect(70, 70, 70, 70);
g.drawOval(180, 70, 70, 70);
g.setColor(Color.blue);
g.fillRect(70, 200, 70, 70);
g.setColor(Color.pink);
g.fillOval (200, 200, 50, 70);
}
}
24
class GraphicsFrame extends Frame
{
GraphicsFrame()
{
setSize(350,350);
setLocation(100,100);
setTitle("Graphics Demo");
GraphicsPanel gp = new GraphicsPanel();
add(gp);
}
}

class GraphicsDemo
{
public static void main(String arg [] )
{
GraphicsFrame gf = new GraphicsFrame();
gf.setVisible(true);
}
}
25
Working with Color:
The AWT color system allows us to specify any color that we want.

It try to find best match color for that color.

Thus our program does not need to be concerned with the difference on
the way color is supported by various hardware devices.

AWT contains Color class which encapsulates the different colors.

Color class defines several color constants


Like
Color.black,
Color.Red,
Color.Blue,
etc to specify a number of common colors.

26
We can also create your own colors by using constructor of Color
class as follows.

Color (int red, int green, int blue)


The first constructor takes three integers that specify the color as a mix of
red, green, and blue. These values must be between 0
and 255.

Color (int rgbValue)


The second constructor takes only one integer value that
contains the mix of red, green, and blue packed in to an integer. The
integer is organized with red in bits 16 to 23, green in bits 8 to
15, and blue in bits 0 to 7.

Color (float red, float green, float blue)


The third constructor takes three float values between 0.0 and 1.0,
that specify the relative mix of red, green, blue.

27
e. g.
1. Color clr = new Color (255,100,100);

2. int cr = (0xff000000 | 0xc << 16) | (0x00 << 8) | 0x00);


Color c = new Color (cr);

3. Color cr = new Color (0.3, 0.6, 1.0);

Then we can use following methods to change the colors:

setForeground (Color c) : It sets foreground color

setBackground (Color c) : It sets background color

setColor (Color c) : It set the current foreground color of


graphics drawing.

Color getColor () : It returns the current color used for


drawing graphics object.
28
Working with Font:
The AWT supports multiply free type fonts.

We can select fonts dynamically by abstracting font manipulation


operations.

The fonts are encapsulated by the Font class with several methods.

The variables defined in Font class:

Variable Meaning
String name Name of the font
float size Size of the font in points
int style Font styles

29
The methods defined in Font class:

Method Meaning
Font getFont (String property) : It returns the font associated with the
system property specified by property. It
returns null if property does not exist.

String getFontName () : It returns the face name of the invoking font.

int getSize () : It returns the size of invoking font, in points.

int getStyle () : It returns the style of the invoking font.

boolean isBold () : It returns true if the font includes BOLD style.


Otherwise returns false.
void setFont (Font fontObj) : It sets Font fontObj that we have created.

30
Method Meaning
boolean isItalic () :It returns true if the font includes
ITALIC style value. Otherwise false.

boolean isPlain () :It returns true of the font includes


PLAIN style value. Otherwise false.

The constructor of the Font class has the following form:


Font (String fontName, int fontStyle, int fontSize)
Where,
fontName specifies the name of the font.
fontStyle specifies the style of the font.
It contains one or more following constants Font.PLAIN
Font.BOLD
Font.ITALIC
fontSize specifies the size of the font in points.
31
Layout Managers:
“A layout manager is an instance of any class that implements the
LayoutManager interface”

Java does not have form designer like VB.

We need to write code to position (Layout) the components.

Each container object has a layout manager associated with it.

The layout manager is set by the setLayout () method.

If we do not use setLayout () Method,


The default layout manger is used.

32
Format:
void setLayout (LayoutManager obj)
Where,
obj is reference to desired layout manger.

If we want to disable the layout manager and


position the component manually,
Then,
We pass the null value to the setLayout () method.

Then,
We determine the shape and position of component manually
using the setBounds ().

33
Layout Managers:
FlowLayout, BorderLayout, GridLayout, CardLayout.

FlowLayout Manager:
It is default Layout manager.

Components are add from the upper-left corner,


left to right and top to bottom.

When no more components are fit on a line,


the next one appears on the next line.

34
Constructor:
FlowLayout fl = new FlowLayout ()
FlowLayout fl = new FlowLayout (int align)
FlowLayout fl = new FlowLayout (int align, int hspace, int vspace)

The Value of align is one of the following:

FlowLayout.LEFT : It aligns the component to Left.


FlowLayout.RIGHT : It aligns the component to Right.
FlowLayout.CENTER : It aligns the component to Center.

35
BorderLayout:
It has four narrow, fixed-width components at the edges
and one large area in the center.

The four sides are referred as north, south, east, and west.

The middle area is called the center.


Constructors:
BorderLayout bl = new BorderLayout ()
BorderLayout bl = new BorderLayout (int hspace, int vspace)

36
BorderLayout defines the constants that specify the regions.
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.NORTH
BorderLayout.EAST
BorderLayout.WEST

When we add a component, we use add () method with constants.


add (Component Obj, Object region)

37
GridLayout:
It lays component in a two-dimensional grid.

We have to define the number of rows and columns.


Constructors:
GridLayout gl = new GridLayout ()
GridLayout gl = new GridLayout (rows, cols)
GridLayout gl = new GridLayout (rows, cols, hspace, vspace)

38
CardLayout:
CardLayout is unique layout managers which stores several
different layouts.

Each layout can be a separate index card in a deck that can be


shuffled so that any card is on top at a given time.

This is useful for user interfaces with optional components


that can be dynamically enabled and disabled upon user input.

This Layout manages two or more cards i.e. containers (usually Panel)
that share the same display space.

Constructors:
CardLayout cl = new CardLayout ()
CardLayout cl =new CardLayout (int hspace, int vspace)

39
CardLayout:
Steps:
1. First create number of different cards i.e. Panels.
2. Add all these cards Panels in one deck i.e. Panel.
3. This main Panel must have CardLayout as Layout Manager.
4. Finally placed this mail Panel in Frame or Window.
5. We must provide some way to select between cards.
i.e. push button or Comb Box.

When card panels are added to a panel, they are given a name.
The format of add() methods is as follows.

void add (Component panelObj, Object name)

Where,
panelObj is the object of panel of cart.
name is the string that specifies the name of the card.
40
Methods to Activate Cards:
Methods Meaning
void first (Container deck) : It shows the first card in the deck.

void last (Container deck) : It shows the last card in the deck.

void next (Container deck) : It shows the next card in the deck.

void previous (Container deck): It shows the previous card in the deck.

void show (Container deck, String cardName):


It shows the card whose name is specified.

41
42
Scrollbar:
Scrollbar is used to select the continuous values between the specified
ranges.
It is collection of several individual parts.

Each end has an arrow, and slider box or thumb.

Clicking on arrow it changes the current value of scrollbar one unit and
moves the thumb in the direction of arrow.

The thumb can be dragged by user to change the value of scrollbar.

It has minimum and maximum values.

It may be oriented horizontally or vertically.

43
Constructor:
Scrollbar sb = new Scrollbar ()

Scrollbar sb = new Scrollbar (int style)

Scrollbar sb = new Scrollbar(int style, int init, int thumbsize, int min,
int max)
Where,
style: It is orientation of scrollbar having following values.
Scorllbar.VERTICAL : Displays Vertical Scrollbar
Scrollbar.HORIZONTAL : Displays Horizontal Scrollbar

init: It is initial value of scrollbar.

thumbsize: It is size of thumb.

min and max: minimum and maximum values of scrollbar.


44
Methods Meaning
void setValues (int initval, int thumbsize, int min, int max):
It is used to set the initial values of scrollbar.

int getValue (): It returns the current values of the scrollbar.

void setValue (int val): It set the current value of the scrollbar.

int getMinimum (): It returns the minimum value of scrollbar.

int getMaximum (): It returns the maximum value of scrollbar.

void setUnitIncrement (int value): It set the unit value of scrollbar when we
drag the thumb.

void setBlockIncrement (int value): It set the block value of scrollbar when we
click on the space of scrollbar.
45

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy