0% found this document useful (0 votes)
4 views41 pages

CH 10

The document provides an overview of Java Foundation Classes (JFC) and Swing, highlighting their advantages over AWT, such as being platform-independent and using fewer system resources. It details various Swing components, their features, and the event delegation model for handling events in GUI applications. Additionally, it explains specific components like JLabel and JButton, including their constructors and methods.

Uploaded by

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

CH 10

The document provides an overview of Java Foundation Classes (JFC) and Swing, highlighting their advantages over AWT, such as being platform-independent and using fewer system resources. It details various Swing components, their features, and the event delegation model for handling events in GUI applications. Additionally, it explains specific components like JLabel and JButton, including their constructors and methods.

Uploaded by

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

BCA DDU SEM IV

Java Swing Prof.Aayushi Shah

JAVA FOUNDATION CLASSES (JFC)

 Originally in java, User interfaces (controls) were developed using AWT classes.
 But AWT design has many limitations.
 GUI that is created in java, can be viewed on many different kinds of computers.
 With AWT, it is not possible to create a GUI on a Macintosh and have it look the same on a
windows machine. They actually appear different.
 When a java.awt component is drawn using a native (operating system’s) component. So, if the
component is a button, on a windows machine, a window button is created and on a Macintosh,
a Macintosh button is created.
 With AWT it is very difficult to create a truly abstract GUI that can work same on all
platforms.
 Because of all these variations, it is very difficult to actually write an AWT system for one
platform that will look and behave the same as an AWT system on another platform.
 So to solve this problem in 1997, Sun and Netscape jointly designed a feature known as
JFC.
 The Java Foundation Classes (JFC) is a graphical framework used for building portable Java- based
graphical user interfaces (GUIs).

JFC contains:
 Swing – The large UI package
 Cut and Paste – Clipboard Support
 Accessibility Features – For users with disabilities
 The Desktop Colors features
 Java 2D – Improved color, image and text support
 Printing

Three main advantages of using Swing are:


1. It uses fewer system resources.
2. Adds a lot more sophisticated components.
3. Pluggable look and feel.
Swing components are relied on Container (a parent of Panel). Because a Container is fairly uniform
for all systems, you can paint or draw on one without encountering platform dependencies.

Heavyweight vs. Lightweight Components:


Each AWT component is one operating platform window. A large number of such windows slow
system performance and uses more memory and system resources. Such components are called
heavyweight components.

1
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

Swing components are simply drawn as images in their containers. Swing controls are not operating
platform windows, so they use less system resources. Therefore, they are called lightweight
components.
Java AWT Java Swing
AWT components are platform-dependent. Java swing components are platform-
independent.
AWT components are heavyweight. Swing components are lightweight.
AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
AWT provides less components than Swing. Swing provides more powerful components
such as tables, lists, scrollpanes, colorchooser,
tabbedpane etc.
AWT doesn't follows MVC(Model View Controller) Swing follows MVC.
where model represents data, view represents
presentation and controller acts as an interface between
model and view.

 All swing components are derived from the JComponent class.


 JComponent is derived from AWT Container class.
 JComponent is a lightweight class.
 It is possible to mix AWT controls with Swing controls in programs, but AWT controls will
appear on top of Swing controls.
 JFrame, JDialog, JWindow and JApplet are heavyweight swing components.

Common Swing Classes:


 JFrame: Top-level container for Swing applications.
 JPanel: General-purpose container for organizing components.
 JApplet: For embedding applets in web browsers.

 JComponent: The base class for all Swing components, offering features like tooltips and
double buffering.

Swing Features:
1. Light weight components.
2. Borders in many different styles can be drawn around components.
3. Graphics debugging – It is used to watch each line as it‟s drawn and make it flash on

2
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

4. Easy mouseless operations can be done by assigning Short cut keys to components.
5. Tooltips.
6. Easy Scrolling.
7. Pluggable look and feel.
9. New layout managers.

Pane Layering

 JFC uses multiple layers upon which it can add components.


 This layering allows you to overlap components.
 For example, if you want to put a pop-up ToolTip on a button, and you want that ToolTip to
appear directly below that button, even if some other control is there, you can simply paint
on the glass pane.
A Root Pane manages four Panes:
1. Layered Pane
2. Content Pane
3. Menu bar
4. Glass Pane
Layered Pane
The layered pane inside the root pane holds the actual components that appear in applets,
including content pane and menu bars.
The content pane
It is the container of the root pane's visible components.
3
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

The Menu Pane


Used for the root pane's container's menus.
If the container has a menu bar, you generally use the container's setJMenuBar method to put the
menu bar in the appropriate place.
The glass pane
It is hidden by default. If you make the glass pane visible, then it's like a sheet of glass over
all the other parts of the root pane. Used to display tooltips.

Generally speaking, most of the time when you add a component to any JFC Container, you will
add it to the content pane. However, if the component has a specific need to overlay other
components, you need to add it to either the layered pane or the glass pane.

Event Delegation Model


Java follows the Event Delegation Model to handle events in GUI applications.
1. Event Source: The object that generates an event (e.g., button click).

2. Event Listener: The object that listens and responds to an event.

3. Event Object: Encapsulates event information.

Event Listeners and Event Objects


Event Listeners: Interfaces that define methods to handle events. Examples:
 ActionListener: Handles button clicks and other actions.

 MouseListener: Detects mouse events.

 KeyListener: Detects keyboard events.

Event Objects: Carry information about an event. Examples:


 ActionEvent: Contains details about an action.

 MouseEvent: Contains details about mouse interactions.

4
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

 Difference with event model Al Listeners and Event Objects

Event Listeners (AWT Event Objects (AWT Event


Feature Listeners) Objects)
Definition Interfaces that handle Objects that store event-
specific types of events related data
Purpose Listens for events and Stores details about the event
executes appropriate code (source, time, type, etc.)
Examples ActionListener, ActionEvent, MouseEvent,
MouseListener, KeyEvent, etc.
KeyListener, etc.
Usage mplemented in a class and Passed as an argument to
attached to a component listener methods
Where Used? btn.addActionListener(new public void
ActionListener() {...}) actionPerformed(ActionEvent
e) { ... }
Works On? User interactions (clicks, Event data (source, time,
keystrokes, mouse moves) modifier keys, etc.)

1. JApplet:
 JApplet is a subclass of Applet that is used to create Swing-based applets.
 It allows adding Swing components like buttons, labels, and panels inside an
applet.
2. JPanel
 JPanel is a generic container in Swing used to group components.
 It is often used for layout management and for organizing components inside a
frame.
 A JPanel does not have a title bar, close button, or minimize button.

5
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

3. JFrame
 JFrame is the main window in Swing applications.
 It provides a title bar, minimize, maximize, and close buttons.
 Used as the top-level container to add components.
4. JComponent
 JComponent is the base class for all Swing components.
 Every Swing component like JButton, JLabel, JTextField, etc., extends
JComponent.

Swing Components:
The Color Class
 Colors are made of red, green, and blue components from 0 to 255 (the RGB model).
 Example of creating a color object using the public Color(int r, int g, int b) constructor:
o Color c = new Color(128, 100, 100);
 The setBackground(Color c) and setForeground(Color c) methods can be used to change the
colors of a component’s foreground or background.

The Font Class


 You can create a font using the java.awt.Fo
 nt class and set fonts for components using the setFont() method
 The Font constructor is: public Font (String name, int style, int size);
 Example:- Font f=new Font(“Times New Roman”,Font.BOLD,20);
 BOLD and ITALIC are the constant values defined in the font class.

6
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

JLabel :
Constructors
Constructor Description Example
JLabel() Creates a JLabel instance with no JLabel lb=new JLabel()
image and with an empty string for the
title.
JLabel(Icon image) Creates a JLabel instance with the ImageIcon img=new
specified image. ImageIcon(“Animals.jpg”)
JLabel lb = new JLabel(img)
JLabel(Icon image, int Creates a JLabel instance with the ImageIcon img=new
horizontalAlignment) specified image and horizontal ImageIcon(“Animals.jpg”)
alignment. JLabel lb = new
JLabel(img,JLabel.LEFT)
JLabel(String text) Creates a JLabel instance with the JLabel lb = new JLabel(“BCA”)
specified text.
JLabel(String text, Icon Creates a JLabel instance with the ImageIcon img=new
icon, int specified text, image, and horizontal ImageIcon(“Animals.jpg”)
horizontalAlignment) alignment. JLabel lb = new
JLabel(“BCA”,img,JLabel.LEFT)
JLabel(String text, int Creates a JLabel instance with the ImageIcon img=new
horizontalAlignment) specified text and horizontal alignment. ImageIcon(“Animals.jpg”)
JLabel lb = new JLabel(“BCA”,
JLabel.LEFT)

JLabel is mainly used to add a label on our GUI


interface. Difference between JLabel and awt label:
JLabel can support not only text but also images or both. There are two ways to do this.
 Use one of the constructors that accommodate the icon.
ImageIcon img = new ImageIcon(“abc.gif”);
JLabel lb_img = new JLabel(“Hello !”, i, JLabel.RIGHT);
add(lb_img);
 Set the icon later using the setIcon Method.
ImageIcon img = new ImageIcon(“abc.gif”);
JLabel lb_img = new JLabel(“Hello !”);
lb_img.setIcon(img);
add(lb_img);

Main methods to be used with JLabel:-


Methods Constructors Example
String getText() Returns the text string that JLabel lb_bca=new JLabel ("BCA");
the label displays. String str = lb_bca.getText();

7
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

void setText(String text) Defines the single line of JLabel lb_bca=new JLabel ("");
text this component will lb_bca.setText("Welcome bca”);
display.
void setVerticalTextPosition(int Sets the vertical position ImageIcon img = new
textPosition) of the label's text, relative ImageIcon("images//java.jpg");
to its image. JLabel lb_img = new
JLabel("bca",img);
lb_img.setVerticalTextposition(
JLabel.TOP);(Constant values allowed
here are TOP,CENTER and
BOTTOM)
void setIcon(Icon icon) Defines the icon this ImageIcon img = new
component will display. ImageIcon(“abc.gif”);
JLabel lb_img = new JLabel(“Hello !”);
lb_img.setIcon(img);

void Sets the horizontal ImageIcon img = new


setHorizontalTextPosition(int position of the label's text, ImageIcon("images//java.jpg");
textPosition) relative to its image
JLabel lb_img = new
JLabel("bca",img);

lb_img. setHorizontalTextPosition (
JLabel.LEFT);( Constant values
allowed here are LEFT,CENTER and
RIGHT)

JButton

Constructors:-
Constructor Description Example
JButton() Creates a button with no set text or JButton btn=new JButton()
icon.
JButton(Icon icon) Creates a button with an icon. ImageIcon img=new
ImageIcon(“Animals.jpg”)
JButton btn=new JButton(img)
JButton(String text) Creates a button with text. JButton btn=new JButton(“Click”)
JButton(String text, Creates a button with initial text and ImageIcon img=new
Icon icon) an icon. ImageIcon(“Animals.jpg”)
JButton btn=new JButton(”click”,img)
8
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

Difference between Swing button and awt button :


 Swing button uses both strings values and image icons while awt button don’t have the
facility to support imageicons.

Displaying Images in Buttons:


JButton btn_click = new JButton(“Click me” , new ImageIcon(“icon1.jpg”);

Methods Description Example


void setText(String s) It is used to set specified text on JButton btn_click = new JButton();
button btn_click.setText(“Click me”);
String getText() It is used to return the text of the String str = btn_click.getText();
button.
void setEnabled(boolean It is used to enable or disable the btn_click.setEnabled(false);
b) button.
void setIcon(Icon b) It is used to set the specified Icon btn_click.setIcon(new
on the button. ImageIcon(icon1.jpg));
Icon getIcon() It is used to get the Icon of the ImageIcon icon1 = btn_click.getIcon();
button.
void setMnemonic(int a) It is used to set the shortcut key btn_click.setMnemonic(‘c’);
on the button. (here Alt+c will be the shortcut key for
the button)
void It is used to add the action listener btn_click. addActionListener(this);
addActionListener(Action to this object.
Listener a)
void It is used to set the vertical JButton b_dcb = new JButton("Disable
setVerticalTextPosition(int position of the text with relative center Button",new
alignment) to image. ImageIcon("images/right.gif"));
b_dcb.setVerticalTextPosition(JButton.C
ENTER);

void It is used to set the Horizontal JButton b_dcb = new JButton("Disable


setHorizontalTextPosition( position of the text with relative center Button",new
int alignment) to image. ImageIcon("images/right.gif"));
b_dcb.setHorizontalTextPosition(JButton
.LEFT);

void It is used to specify whether to btn_click.setRolloverEnabled(true);


setRolloverEnabled(boolea display rollover icons or not. If
n b) true rollover icons are displayed.
void setRolloverIcon(Icon Icon can be used as a rollover btn_click.setRolloverIcon(new
i) icon, which is displayed when the ImageIcon("images// rollover 2.jpg"))
9
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

mouse is positioned over a


button.
void setPressedIcon(Icon i) Icon can be used as a pressed ImageIcon pressed = new
icon, which is displayed when a ImageIcon("images//rollover 3.jpg");
button is clicked. btn_click.setPressedIcon(pressed);
void setDisabledIcon(Icon Icon can be used as disabled icon, btn_click.setEnabled(true);
i) which is displayed when a button btn_click.setDisabledIcon(new
is enabled false.(disabled) ImageIcon("images//index.jpg"));

Example:
public class Button_image implements ActionListener
{
JButton b_dcb;
JButton b_cb;
JButton b_ecb;
JFrame fr;
public static void main(String[] args)
{
Button_image b=new Button_image();
b.formLoad();

}
public void formLoad()
{
fr=new JFrame();
fr.setVisible(true);
fr.setSize(800,800);
fr.setTitle("button demo");
fr.setLayout(new FlowLayout());

b_dcb=new JButton("Disable center Button",new ImageIcon("D:\\images\\right.gif"));


b_dcb.setVerticalTextPosition(JButton.CENTER);
b_dcb.setHorizontalTextPosition(JButton.LEFT);
b_cb=new JButton("center button",new ImageIcon("D:\\images\\middle.gif"));
b_ecb=new JButton("Enable center Button",new
ImageIcon("D:\\images\\left.gif"));
b_ecb.setVerticalTextPosition(JButton.CENTER);
b_ecb.setHorizontalTextPosition(JButton.RIGHT);
fr.add(b_dcb);
fr.add(b_cb);
fr.add(b_ecb);
b_ecb.setEnabled(false);
b_dcb.addActionListener(this);
b_cb.addActionListener(this);
10
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

b_ecb.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String action=e.getActionCommand();
if (action=="Disable center Button")
{
b_cb.setEnabled(false);
b_dcb.setEnabled(false);
b_ecb.setEnabled(true);
}
else if(action=="Enable center Button")
{
b_cb.setEnabled(true);
b_dcb.setEnabled(true);
b_ecb.setEnabled(false);
}

}
}
O/P

TextArea :
Displays multiple lines of text.
Constructors:
Constructor Description Example
JTextArea() Constructs a new TextArea. JTextArea txt=new JTextArea();
JTextArea(int rows, int Constructs a new empty JTextArea txt=new
cols) TextArea with the specified JTextArea(5,10);
number of rows and columns.
JTextArea(String text) Constructs a new TextArea with String str=”hello bca students of
the specified text displayed. ddu”;
JTextArea txt=new
11
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

JTextArea(str);
JTextArea(String text, int Constructs a new TextArea with String str=”hello bca students of
rows, int cols) the specified text and number of ddu”;
rows and columns. JTextArea txt=new
JTextArea(str,5,10);

Methods:
Methods Description Example
void append(String text) Appends the given text to the String str=”hello bca students”;
end of the document. JTextArea txt=new
JTextArea(str,5,10);
txt.append(“welcome”);
int getColumns() Returns the number of int i = txt.getColumns();
columns in the TextArea.
int getRows() Returns the number of int i = txt. getRows ();
columns in the TextArea.
void insert(String text, int pos) Inserts the specified text at txt.insert(" DDU NADIAD ",10);
the specified position.
void replaceRange(String txt, Replaces text from the txt.replaceRange("HELLO",0,10);
int Start, int end) indicated start to end position
with the new text specified.
void setColumns(int cols) Sets the number of columns txt. setColumns(5);
for this TextArea.
void setRows(int rows) Sets the number of rows for txt. setRows (5);
this TextArea.
void setFont(Font f) Sets the current font. Font f=new Font("Times New
Roman",Font.BOLD,20);
txt.setFont(f);
void setLineWrap(Boolean b) Sets the line-wrapping policy txt. setLineWrap(true)
for the JTextArea. If line-
wrapping is set to true, a line
is wrapped if it does not fit
into the width of the
JTextArea. If it is set to false,
lines are not wrapped even
though it is longer than the
width of the JTextArea. By
default, it is set to false.

void Sets the word-wrapping style txt. setWrapStyleWord(true)


setWrapStyleWord(Boolean b) when line wrapping is set to
true. When it is set to true,
the line wraps at a word

12
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

boundary. Otherwise, the line


wraps at a character
boundary. ` By default, it
is set to false.

With TextArea Scrollbars are not displayed by default.


Textarea can be added to ScrollPane to get scrollbars.
Ex:-
String text = "A JTextArea object represents a multiline area for displaying text.";
JTextArea t2 = new JTextArea(text, 5, 10);
JScrollPane sPane = new JScrollPane(t2,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

Program:-
public class TextArea_Demo implements ActionListener
{
JFrame fr;
JTextArea txta;
JLabel lbl_heading;
JButton btn_append;
JTextField txt_str;
JPanel p1;
String str;
JLabel lbl_msg;
JScrollPane sp;
public static void main(String[] args)
{
TextArea_Demo t =new TextArea_Demo();
t.formLoad();

}
public void formLoad()
{
fr=new JFrame();
p1=new JPanel();
p1.setLayout(new FlowLayout());
str="A JTextArea is a multi-line area that displays plain text. "
+ "It is intended to be a lightweight component";
fr.setTitle("text Area demo");
fr.setSize(600, 400);
fr.setVisible(true);
lbl_heading=new JLabel("TextArea Example");
Font f=new Font("Arail",Font.BOLD,24);
13
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

Font f1=new Font("Arial",Font.ITALIC,24);


txt_str=new JTextField(20);
btn_append=new JButton("ADD");
txta=new JTextArea(20,10);
sp=new JScrollPane(txta);
txta.setLineWrap(true);
txta.setText(str);
txta.setFont(f);
txta.setForeground(Color.BLUE);
lbl_heading.setFont(f);
lbl_msg=new JLabel();
int count=txta.getLineCount();
lbl_msg.setText("Lines in textarea:"+count);
lbl_msg.setFont(f1);
lbl_msg.setForeground(Color.MAGENTA);
fr.add(lbl_heading,BorderLayout.NORTH);
fr.add(sp,BorderLayout.CENTER);
p1.add(txt_str);
p1.add(btn_append);
p1.add(lbl_msg);
fr.add(p1,BorderLayout.SOUTH);
btn_append.addActionListener(this);
fr.revalidate();
}
public void actionPerformed(ActionEvent e)
{
String s1;
s1=txt_str.getText();
if(!s1.equals(""))
{
txta.append('\n'+s1);
int count=txta.getLineCount();
lbl_msg.setText("Lines in textarea:"+count);
txt_str.setText("");
}
else
{
JOptionPane.showMessageDialog(fr,"please enter value blank cannot be
added","Error",JOptionPane.ERROR_MESSAGE);
}
}}

14
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

Checkboxes:

A JCheckBox also has two states: selected and unselected. A group of JCheckBoxes is used when
the user can select zero or more choices from a list of two or more choices.
Constructors
Constructor Description Example
JCheckBox() Creates a default checkbox JCheckBox bold=new
JCheckBox();
JCheckBox(Icon icon) Provides an icon for the JCheckBox bold=new
checkbox JCheckBox(new
ImageIcon(“Animals.jpg”));
JCheckBox(Icon icon, Provides an icon for the JCheckBox bold=new
Boolean selected) checkbox. The second JCheckBox(new
parameter tells whether the ImageIcon(“Animals.jpg”),true);
checkbox should be selected or
not. If true the checkbox will be
selected and false otherwise.
JCheckBox(String text) A checkbox with a simple string JCheckBox bold=new
is created. JCheckBox(“BOLD”);
JCheckBox(String text, A checkbox with a simple string JCheckBox bold=new
Boolean selected) is created. The second JCheckBox(“BOLD”,true);
parameter tells whether the
checkbox should be selected or
not. If true the checkbox will be
selected and false otherwise.
JCheckBox(String text , A checkbox with a simple string JCheckBox bold=new
Icon icon) and imageicon. JCheckBox(“BOLD”, new
ImageIcon(“Animals.jpg”));
JCheckBox(String text , A checkbox with a simple string JCheckBox bold=new
Icon icon, Boolean and imageicon as well as JCheckBox(“BOLD”, new
selected) whether it is selected or not. ImageIcon(“Animals.jpg”),true);

15
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

Main methods used are


boolean isSelected()---returns true if checkbox is selected and false otherwise.
void setSelected(Boolean)---- sets the property of checkbox to true or false as specified.

Program:-

public class Checkbox_demo implements ItemListener


{
JCheckBox Bold;
JCheckBox Italic;
JTextArea txta;
JFrame fr;
JScrollPane sp;
JComboBox cmb_color;
public static void main(String[] args)
{
Checkbox_demo fr=new Checkbox_demo();
fr.formLoad();
}
public void formLoad()
{
fr=new JFrame();
fr.setTitle("checkbox demo");
fr.setSize(300, 300);
fr.setVisible(true);
String str="Hello welcome to BCA sem 4. \n "+
"we are performing programs of java swing and this is an example of checkbox";
JPanel p1=new JPanel();
Bold=new JCheckBox("Bold");
Italic=new JCheckBox("Italic");
p1.setLayout(new FlowLayout());
p1.add(Bold);
p1.add(Italic);
16
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

String cl[]= {"Red","Blue","Pink","Black","Magenta"};


cmb_color=new JComboBox(cl);
cmb_color.setMaximumRowCount(3);
p1.add(cmb_color);
fr.add(p1,BorderLayout.NORTH);
txta=new JTextArea(10,20);
txta.setText(str);
txta.setLineWrap(true);
sp=new JScrollPane(txta);
fr.add(sp,BorderLayout.CENTER);
Bold.addItemListener(this);
Italic.addItemListener(this);
cmb_color.addItemListener(this);
fr.revalidate();
}
public void itemStateChanged(ItemEvent e)
{
int Style=0;
if (Bold.isSelected())
{
Style = Font.BOLD;
}
if (Italic.isSelected())
{
Style = Font.ITALIC;
}
if (Bold.isSelected() &&
Italic.isSelected())
{
Style = Font.BOLD + Font.ITALIC ;
}
Font f= new Font("Times New Roman",
Style,20);
txta.setFont(f);
String user_color=(String)cmb_color
.getSelectedItem();
if(user_color.equals("Red"))
txta.setForeground(Color.RED);
if(user_color.equals("Blue"))
txta.setForeground(Color.BLUE);
if(user_color.equals("Pink"))
txta.setForeground(Color.PINK);
if(user_color.equals("Black"))
txta.setForeground(Color.BLACK);
17
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

if(user_color.equals("Magenta"))
txta.setForeground(Color.MAGENTA);
}}
Radio Buttons:
Constructors:-
Constructor Description Example
JRadioButton() Creates a default radiobutton JRadioButton bold=new
JRadioButton ();
JRadioButton(Icon icon) Provides an icon for the JRadioButton bold=new
radiobutton JRadioButton (new
ImageIcon(“Animals.jpg”));
JRadioButton (Icon icon, Provides an icon for the JRadioButton bold=new
Boolean selected) radiobutton. The second JRadioButton (new
parameter tells whether the ImageIcon(“Animals.jpg”),true);
radiobutton should be selected
or not. If true the radiobutton
will be selected and false
otherwise.
JRadioButton (String text) A radiobutton with a simple JRadioButton bold=new
string is created. JRadioButton (“BOLD”);
JRadioButton (String text, A radiobutton with a simple JRadioButton bold=new
Boolean selected) string is created. The second JRadioButton (“BOLD”,true);
parameter tells whether the
radiobutton should be selected
or not. If true the radiobutton
will be selected and false
otherwise.
JRadioButton (String text , A radiobutton with a simple JRadioButton bold=new
Icon icon) string and imageicon. JRadioButton (“BOLD”, new
ImageIcon(“Animals.jpg”));
JRadioButton (String text , A radiobutton with a simple JRadioButton bold=new
Icon icon, Boolean string and imageicon as well as JRadioButton (“BOLD”, new
selected) whether it is selected or not. ImageIcon(“Animals.jpg”),true);

- Images are displayed with checkbox or radio button, there is no visual indication in
the control to show whether it is selected.
- Use different image icon for a selected checkbox or radio button.
Methods:
boolean isSelected()---returns true if RadioButton is selected and false otherwise.
void setSelected(Boolean)---- sets the property of RadioButton to true or false as specified.

 Selection or deselection of Checkbox or Radiobutton results in


18
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

ItemEvent.
 Handled by ItemListener interface with itemStateChanged() method.
Program:-
public class RadioButton_Demo implements ItemListener
{
JFrame fr;
JRadioButton rb_alpha;
JRadioButton rb_symb;
JRadioButton rb_num;
JLabel img_label;
public static void main(String[] args)
{
RadioButton_Demo rbd=new RadioButton_Demo();
rbd.formLoad();
}
public void formLoad()
{
fr=new JFrame();
fr.setTitle("radiobutton demo");
fr.setSize(600, 400);
fr.setLayout(new FlowLayout());
fr.setVisible(true);

rb_alpha=new JRadioButton("Aplhabets");
rb_symb=new JRadioButton("Numbers");
rb_num=new JRadioButton("Symbols");
img_label=new JLabel("hello");
ButtonGroup grp=new ButtonGroup();
grp.add(rb_alpha);
grp.add(rb_symb);
grp.add(rb_num);
fr.add(rb_alpha);
fr.add(rb_symb);
fr.add(rb_num);
fr.add(img_label);

rb_alpha.addItemListener(this);
rb_symb.addItemListener(this);
rb_num.addItemListener(this);

}
public void itemStateChanged(ItemEvent e)
{
19
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

img_label.setPreferredSize(new Dimension(150, 100));


if (rb_alpha.isSelected())
img_label.setIcon(new ImageIcon("D:\\images\\alphabets.jpg"));
if (rb_symb.isSelected())
img_label.setIcon(new ImageIcon("D:\\images\\symbols.jpg"));
if (rb_num.isSelected())
img_label.setIcon(new ImageIcon("D:\\images\\numbers.jpg"));
}

Scroll Panes:
- A lighweight swing component derived from Jcomponent class.
- Used to scroll other controls.
Constructors:-
Constructor Description Example
JScrollPane() Creates an empty JScrollPane where JScrollPane jsp = new
both horizontal and vertical scrollbars JScrollPane ()
appear when needed.
JScrollPane( Component c) Creates a JScrollPane that displays String str=”hello bca students of
along the specified component, where ddu”;
both horizontal and vertical scrollbars JTextArea txt=new JTextArea(str);
appear whenever the component's JScrollPane jsp = new
contents are larger than the view. JScrollPane (txt)
JScrollPane( Component c, Creates a JScrollPane that displays String str=”hello bca students of
int vsbPolicy, int hsbPolicy) along the specified component whose ddu”;
view position can be controlled with a JTextArea txt=new JTextArea(str);
pair of scrollbars. JScrollPane jsp = new JScrollPane
(txt,
JScrollPane.VERTICAL_SCROL
LBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCR
OLLBAR_AS_NEEDED)

JScrollPane( int vsbPolicy, Creates an empty JScrollPane with JScrollPane jsp = new JScrollPane
int hsbPolicy) specified scrollbar policies. (
JScrollPane.VERTICAL_SCROL
20
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

LBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCR
OLLBAR_AS_NEEDED)

Policy constants:
HORIZONTAL_SCROLLBAR_ALWAYS
HORIZONTAL_SCROLLBAR_AS_NEEDED
HORIZONTAL_SCROLLBAR_NEVER
VERTICAL_SCROLLBAR_ALWAYS
VERTICAL_SCROLLBAR_AS_NEEDED
VERTICAL_SCROLLBAR_NEVER

Methods:
setVerticalScrollbarPolicy ( int Policy) -- Determines when the vertical scrollbar appears in
the scrollpane.
setHorizontalScrollbarPolicy ( int Policy) -- Determines when the Horizontal scrollbar
appears in the scrollpane
setColumnHeaderView ( Component c) --used to put a column header across a scrollpane
setRowHeaderView (Component c)-- used to put a row header across a scrollpane

Example :
String str=”hello bca students of ddu”;
JTextArea txt=new JTextArea(str);
JScrollPane jsp = new JScrollPane (txt,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
JLabel l1 = new JLabel ( “Columns”);
JLabel l2 = new JLabel (“Rows”)
jsp.setColumnHeaderView ( l1) ;
jsp.setRowHeaderView ( l2 );
JScrollPane can be used to scroll large images too.

Sliders
Constructors:
Constructor Description Example
JSlider() Creates a horizontal slider with the JSlider sd = new JSlider();
range 0 to 100 and an initial value
of 50.
JSlider( int orientation) Creates a slider using the specified JSlider sd = new
orientation with the range 0 to 100 JSlider(JSlider.VERTICAL);

21
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

and an initial value of 50.


JSlider (int min, int max) Creates a horizontal slider using the JSlider sd = new JSlider(0, 50);
specified min and max with an
initial value equal to the average of
the min plus max.
JSlider(int min, int max, Creates a horizontal slider using the JSlider sd = new JSlider(0, 50,
int value) specified min, max and value. 25);

JSlider(int orientation, Creates a slider with the specified JSlider sd = new


int min, int max, int orientation and the specified JSlider(JSlider.HORIZONTAL, 0,
value) minimum, maximum, and initial 50, 25);
values.

Methods:
1. setPaintTicks(Boolean flag)-- Determines whether tick marks are painted on the slider.
2. setPaintLabels(true) -- Determines whether labels are painted on the slider.
3. setMajorTickSpacing( int major )--- This method sets the major tick spacing.
4. setMinorTickSpacing( int minor ) -- This method sets the minor tick spacing.
5. void setOrientation(int orientation)--Set the slider's orientation to either
SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
Sliders are similar to scrollbars in that they enable a user to drag a marker point across the screen.
However, sliders are typically used to specify a quantity, as opposed to moving a screen view.
JSlider can display major ticks, minor ticks, or neither as guides for the user.
The slider can be displayed either vertically or horizontally.
JSlider sd = new JSlider(SwingConstants.VERTICAL, 0, 50, 25);
 The first parameter for the constructor is orientation, which can be either
SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
 The next two parameters for the constructor are the minimum and maximum values for the
slider.
 The last parameter is the initial value of the slider.

Configuring The Tick Marks :


By default, a slider doesn‟t display its tick marks. However, we can turn on either the major
or minor tick marks independently, using either setMajorTickSpacing( ) or setMinotTickSpacing( )
respectively.
sd.setMajorTickSpacing(10);
sd.setMinorTickSpacing(2);

Capturing Changes in the Slider :


The ChangeEvent occurs any time the slider is moved. It is a new event in the JFC set which is in
the package: javax.swing.event.

22
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

stateChanged () method is used to write the code which handles event.

Program that shows the usage of SliderBar to implement the RGB Colored Label

public class ColorSlider implements ChangeListener


{
JSlider r = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 50);
JSlider g = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 255);
JSlider b = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 100);
int rc = 0;
int gc =0;
int bc = 0;
JLabel lb;
JFrame fr;
public static void main(String[] args)
{
ColorSlider cs=new ColorSlider();
cs.formLoad();
}
public void formLoad()
{
fr=new JFrame();
fr.setTitle("radiobutton demo");
fr.setSize(600, 400);
fr.setLayout(new FlowLayout());
fr.setVisible(true);
lb=new JLabel("Hello");
r.addChangeListener(this);
b.addChangeListener(this);
g.addChangeListener(this);

r.setPaintTicks(true);
r.setPaintLabels(true);
r.setMajorTickSpacing(40);
r.setMinorTickSpacing(10);

g.setPaintTicks(true);
g.setPaintLabels(true);
g.setMajorTickSpacing(40);
g.setMinorTickSpacing(20);

b.setPaintTicks(true);
b.setPaintLabels(true);
b.setMajorTickSpacing(40);

23
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

b.setMinorTickSpacing(20);

fr.add(r);
fr.add(g);
fr.add(b);
//c.add(lb);
}
public void stateChanged(ChangeEvent e)
{
if(e.getSource()==r)
rc = r.getValue();
if(e.getSource()==g)
gc = g.getValue();
if(e.getSource()==b)
bc = b.getValue();
//lb.setText( rc + " " + gc + " " + bc);
fr.getContentPane().setBackground(new Color(rc,gc,bc));
}
}

Lists
Lists are probably one of the single-most-used UI Components for displaying several items.
Combo Boxes are another variation on a list.
AWT includes a list and combo box which is represented by the Choice Class, but both are limited
to displaying only strings.
JFC adds JList, which is a completely different from AWT‟s Choice in several ways, and it actually
uses the JList class for its pop-up display.
Instead of displaying just string, JList can display any kind of object and can include not only string
but also an associated icon.
Constructors:
Constructor Description Example
24
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

JList() Constructs an empty JList JList jlist = new JList();

JList(Object[] listData) Constructs a JList that displays the String[] items = {"C", "DCO" ,
elements in the specified array. "CE", "AM-I"};
JList jlist = new JList(items);

JList(Vector listData) Constructs a JList that displays the Vector<Object> vec1 = new
elements in the specified Vector. Vector<Object>();
vec1.add(new String("abc"));
vec1.add(new Integer(1));
vec1.add(new String("Hello"));
JList jlist1 = new JList(vec1);

- Can display images also.


- Does not allow to change or add any new data after
creation.
Methods:
1. void setVisibleRowCount ( int count )--- sets the preferred number of rows to display without
requiring scrolling;
2. int getSelectedIndex()---Returns the selected cell index; the selection when only a single item
is selected in the list.
3. int[] getSelectedIndices ()---Returns an array of all of the selected indices, in increasing order.
4. object getSelectedValue () --- Returns the value for the selected cell index; the selected value
when only a single item is selected in the list.
5. object[ ] getSelectedValues()---Returns an array of all the selected values, in increasing order
based on their indices in the list.
6. boolean isSelectedIndex ( int index )--- Returns true if the specified index is selected, else
false.
7. void setSelectedIndex ( int index )-- Selects a single cell.
8. void setSelectedIndices (int[ ] indices )-- Changes the selection to be the set of indices
specified by the given array.
9. void setSelectionMode ( int selectionMode )--- Sets the selection mode for the list.
10. void clearSelection() -- Clears the selection

Selection Modes:

25
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

Program to display a listbox and display the selected values in label


public class ListDemo implements ListSelectionListener
{
JList jlist;
JLabel l_index;
JLabel l_value;
JFrame fr;
public static void main(String[] args)
{
ListDemo l=new ListDemo();
l.formLoad();
}
public void formLoad()
{
fr=new JFrame();
fr.setTitle("list demo");
fr.setSize(600, 400);
fr.setLayout(new FlowLayout());
fr.setVisible(true);

Font f=new Font("Times New Roman",Font.BOLD,24);


l_index=new JLabel("selected index is:-");
l_index.setFont(f);
l_value=new JLabel("selected value is:-");
26
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

l_value.setFont(f);
String[] items = { "C","DCO" , "CE", "AM-I", "CFA", "CE-II", "AM-II","Data
Structure","HTML","BDP"};
jlist = new JList(items);
jlist.setToolTipText("List of subjects");
JScrollPane list_sp = new JScrollPane(jlist);
jlist.setVisibleRowCount(5);
jlist.addListSelectionListener(this);
jlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
fr.add(jlist);
fr.add(l_index);
fr.add(l_value);
fr.revalidate();
}
public void valueChanged(ListSelectionEvent e)
{
l_index.setForeground(Color.RED);
l_value.setForeground(Color.BLUE);
int index=jlist.getSelectedIndex();
l_index.setText("index= " + String.valueOf(index));

Object value = jlist.getSelectedValue();


l_value.setText("value= " +String.valueOf(value));

String str="";
int ind[] = jlist.getSelectedIndices();
for (int i = 0 ; i< ind.length ; i++)
str += ind[i]+" ";
l_index.setText("selected indices are:- "+ " "+str);

Object[ ] sel = jlist.getSelectedValues();


String outString = "";
for (int i = 0 ; i< sel.length ; i++)
outString += sel[i] + " " ;
l_value.setText("selected values are " +outString);
} }

Program to display images in listbox


public class List_image
{
JFrame fr;
JList list;
public static void main(String[] args)
{
27
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

List_image li=new List_image();


li.formLoad();
}
public void formLoad()
{
fr=new JFrame();
fr.setVisible(true);
fr.setSize(400,400);
fr.setTitle("Adding images to listbox");
fr.setLayout(new FlowLayout());

ImageIcon arr[]=new ImageIcon[5];


arr[0]=new ImageIcon("D:\\images\\alphabets.jpg");
arr[1]=new ImageIcon("D:\\images\\numbers.jpg");
arr[2]=new ImageIcon("D:\\images\\symbols.jpg");
list=new JList(arr);
JScrollPane sp=new JScrollPane(list);
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
fr.add(sp);
}}

Progress Bar
 When an activity is going to take a long time to complete, many applications use progress
bars to show the current status, and to help the user know that the process is continuing.
 Awt does not include progress bars but like sliders.
 Draws an updated, colored bar inside it that displays the progress of
some operation. Derived from JComponent class.

Constructors:
Constructor Description Example
JProgressBar( ) Creates a horizontal progress bar that JProgressBar pb=new
displays a border but no progress JProgressBar();
string.
JProgressBar ( int Creates a progress bar with the JProgressBar pb=new
orient) specified orientation, which can be JProgressBar(JProgressBar.HORI
either SwingConstants. VERTICAL ZONTAL);
or SwingConstants.HORIZONTAL.
JProgressBar( int min, Creates a horizontal progress bar with JProgressBar pb=new
int max) the specified minimum and JProgressBar(0,100);
maximum.
JProgressBar ( int Creates a progress bar using the JProgressBar pb=new
28
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

orient , int min, int specified orientation, minimum, and JProgressBar(JProgressBar.HORIZ


max) maximum. ONTAL,0,100);

Orientation : HORIZONTAL or
VERTICAL
Methods :

1. void setMinimum (int min)-- Sets the progress bar's minimum value
2. void setMaximum (int max)-- Sets the progress bar's maximum value
3. void setOrientation( int orientation)-- Sets the progress bar's orientation to newOrientation,
which must be SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
4. void setValue (int val)-- Sets the progress bar's current value to n.
5. int getMaximum()--Returns the progress bar's maximum value
6. int getMinimum()--Returns the progress bar's minimum value
7. int getOrientation( )-- Returns SwingConstants.VERTICAL or
SwingConstants.HORIZONTAL, depending on the orientation of the progress bar.
8. int getValue()--Returns the progress bar's current value

Fires change event when value is changed.

Handled by ChangeListener interface and stateChanged()


method.

Example:

public class PBDemo implements ActionListener,Runnable


{
JFrame fr;
JProgressBar pb;
JButton btn_start;
JLabel lb_disp;
String msg = "";
Thread t;
public static void main(String[] args)
{
PBDemo p=new PBDemo();
p.Formload();

}
public void Formload()
{
fr=new JFrame();
fr.setLayout(new FlowLayout());
fr.getContentPane().setBackground(Color.cyan);
29
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

fr.setVisible(true);
fr.setTitle("progress bar");
fr.setSize(600,600);
pb = new JProgressBar(JProgressBar.HORIZONTAL,0,100);
// pb = new JProgressBar();
//pb.setMinimum (0);
//pb.setMaximum (100);
//pb.setOrientation(JProgressBar.HORIZONTAL);
// pb.setValue(20);
pb.setStringPainted(true);
pb.setForeground(Color.red);
btn_start = new JButton("Start");
btn_start.setMnemonic('s');
btn_start.setToolTipText("click to start process");
lb_disp = new JLabel("Start download by clicking Button");
fr.add(btn_start);
fr.add(pb);
fr.add(lb_disp);
btn_start.addActionListener(this);
t = new Thread(this, "Demo Thread");
}
public void actionPerformed(ActionEvent e)
{
t.start();

}
public void run()
{
int temp = 0;
while(temp < 100)
{
temp = pb.getValue();
try
{
t.sleep(1000);
pb.setValue(temp + 10);
msg = pb.getValue() + "% downloaded...... ";
lb_disp.setText(msg);
}
catch(InterruptedException ie)
{}
}
}
}
30
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

Creating Menu :

Classes: JMenuBar
JMenu
JMenuItem

JMenu class : Constructors:


JMenu()
JMenu( String s)
Methods:
add(Component c)
add(Component c, index i)
addSeparator( )

MenuItem class: Constructors:


JMenuItem(String s)
JmenuItem(String s, Icon i)
JMenuItem(String s, int
Mnemonic)

Program
public class MenuBarDemo implements ActionListener
{
JFrame fr;
JCheckBoxMenuItem bold, itlc;
JTextField t1,t2;
public static void main(String[] args)
{
MenuBarDemo m=new MenuBarDemo();
m.formLoad();
}
public void formLoad()
{
fr=new JFrame();
fr.setVisible(true);
fr.setSize(400,400);

31
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

fr.setLayout(new FlowLayout());
t1 = new JTextField("Your Selection",25);
t2 = new JTextField("Effects ",20);
fr.setLayout(new FlowLayout());
fr.add(t1);
fr.add(t2);

JMenuBar mbar = new JMenuBar();

JMenu jmenu1 = new JMenu("File");


JMenuItem m1 = new JMenuItem("New...");
JMenuItem m2 = new JMenuItem("Open...");
JMenuItem m3 = new JMenuItem("Exit");
jmenu1.add(m1);
jmenu1.add(m2);
jmenu1.addSeparator();
jmenu1.add(m3);
JMenu jmenu2 = new JMenu("Edit");
JMenuItem m4 = new JMenuItem("Cut");
JMenuItem m5 = new JMenuItem("Copy");
JMenuItem m6 = new JMenuItem("Paste");
jmenu2.add(m4);
jmenu2.add(m5);
jmenu2.add(m6);
jmenu2.addSeparator();
bold = new JCheckBoxMenuItem("Bold");
itlc = new JCheckBoxMenuItem("Italic");
jmenu2.add(bold);
jmenu2.add(itlc);
m1.addActionListener(this);
m2.addActionListener(this);
m3.addActionListener(this);
m4.addActionListener(this);
m5.addActionListener(this);
m6.addActionListener(this);
bold.addActionListener(this);
itlc.addActionListener(this);
mbar.add(jmenu1);//file
mbar.add(jmenu2);//edit
fr.setJMenuBar(mbar);
}
public void actionPerformed(ActionEvent e) {
t1.setText("You have selected : " + e.getActionCommand() );
t2.setText( " Bold is " + bold.getState() + " Italic is "+ itlc.getState() );
32
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

}
}

ToolBar
Program
public class ToolBarDemo implements ActionListener,ItemListener
{
JToggleButton b1 = new JToggleButton( new ImageIcon("D:\\images\\bold.jpg"));
JToggleButton b2 = new JToggleButton( new ImageIcon("D:\\images\\italic1.jpg"));

JButton b3 = new JButton( new ImageIcon("D:\\images\\red.jpg"));


JButton b4 = new JButton( new ImageIcon("D:\\images\\blue.jpg"));

JToolBar tb1 = new JToolBar();


JToolBar tb2 = new JToolBar();

JComboBox jb;
JButton b5 = new JButton("Set Rollover");
int Style;
JTextField t1 = new JTextField("Checking Fonts",15);
JFrame fr;
public static void main(String[] args) {
ToolBarDemo t=new ToolBarDemo();
t.formload();
}
public void formload()
{
fr=new JFrame();
fr.setTitle("radiobutton demo");
fr.setSize(600, 400);
fr.setVisible(true);
jb = new JComboBox();
jb.addItem("Times New Roman");
jb.addItem("Comic Sans");
jb.addItem("Arial");

33
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);

jb.addItemListener(this);

tb1.add(b1);
tb1.add(b2);
tb1.addSeparator();
tb1.add(jb);
tb1.addSeparator();
tb1.add(b3);
tb1.add(b4);
tb2.add(b5);
fr.add(tb1, BorderLayout.NORTH);
fr.add(tb2, BorderLayout.SOUTH);
fr.add(t1, BorderLayout.CENTER);

//tb1.setFloatable(true);
tb1.setRollover(false);

public void actionPerformed(ActionEvent e)


{
Style = 0;
if(b1.isSelected())
{
Style = Font.BOLD;
}
if(b2.isSelected())
{
Style = Font.ITALIC;
}
if(e.getSource() == b3)
{
t1.setForeground(Color.RED);
}
if(e.getSource() == b4)
{
t1.setForeground(Color.BLUE);
}
34
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

Font f = new Font((String) jb.getSelectedItem(),Style,20);


t1.setFont(f);
if(e.getSource() == b5)
{
tb1.setRollover(true);
}
}
public void itemStateChanged(ItemEvent e)
{
Font f = new Font((String) jb.getSelectedItem(),Style,20);
t1.setFont(f);
}
}

Table
 One of the key features of a JFC is to display two-dimensional data using a table
component called JTable.
 The Constructor takes a set of Two-Dimentional data, and a set of labels for the
column heads. JTable does not implement its own Scrolling.
 JTable has a convenience method for creating the scroll pane and placing the table and
the table header in the proper location.

Example
public class JTable_demo {

JFrame fr;
JLabel lbl_disp;
JTable t;
public static void main(String[] args)
{
35
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

JTable_demo t=new JTable_demo();


t.formLoad();
}
public void formLoad()
{
fr=new JFrame();
fr.setTitle("table demo");
fr.setSize(400, 400);
fr.setVisible(true);

lbl_disp = new JLabel("Top 10 Employees");

// Adding Data to be displayed


String[][] data = {
{"1","Tom","Manager","40"},
{"2","Peter","Programmer","25"},
{"3","Paul","Leader","30"},
{"4","John","Designer","50"},
{"5","Sam","Analyst","32"},
{"6","David","Developer","28"},
{"7","Ninja","Programmer","21"},
{"8","Kelvin","Developer","26"},
{"9","Jerry","Designer","29"},
{"10","Joshep","Analyst","25"}
};
Font f=new Font("Arial",Font.BOLD,24);
lbl_disp.setFont(f);
lbl_disp.setForeground(Color.blue);
//lbl_disp.setHorizontalAlignment(JLabel.CENTER);
// Column Names
String[] columnName = { "No.","Name","Designation","Age"};
// Initializing JTable
t = new JTable(data, columnName);
t.setGridColor(Color.magenta);
Font f1=new Font("Arial",Font.BOLD,14);
t.setFont(f1);
// Adding Jtable to JScrollPane
fr.add(lbl_disp,BorderLayout.NORTH);
JScrollPane sp = new JScrollPane(t);
fr.add(sp,BorderLayout.CENTER);
fr.revalidate();
}
}

36
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

Borders:
One of the unique characteristics that JFC has added to all components is the capability to have an
adjustable border. What‟s unique about this is that any object can have an arbitrary border placed on it.
A package called java.swing.border contains a number of different borders, each of which can be
applied to a wide variety of swing components.
Any component can have its border set using the setBorder( ) method. There are different types of
borders that we can set according to our requirements.

Consider p1 as the panel created in the program.


1) createEmptyBorder
p1.setBorder (BorderFactory.createEmptyBorder (10, 10,18,18));

2) createLineBorder
public static Border createLineBorder(Color color, int thickness)

Creates a line border with the specified color and width. The width applies to all four sides of the
border.
p1.setBorder (BorderFactory.createLineBorder (Color.red, 5));

3) createRaisedBevelBorder
public static Border createRaisedBevelBorder()
Creates a border with a raised beveled edge, using brighter shades of the component's current
background color for highlighting
p1.setBorder (BorderFactory.createRaisedBevelBorder ());

4) createLoweredBevelBorder
public static Border createLoweredBevelBorder()
Creates a border with a lowered beveled edge, using brighter shades of the component's current
background color for highlighting

p1.setBorder (BorderFactory.createLoweredBevelBorder ());

5) createTitledBorder
public static TitledBorder createTitledBorder(String title)
37
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

Creates a new title border specifying the text of the title, using the default border , using the default
text position (sitting on the top line left)

p1.setBorder (BorderFactory.createTitledBorder ("login"));

Tiltedborder with center justification


TitledBorder tb = BorderFactory.createTitledBorder ("Login");
tb.setTitleJustification (TitledBorder.CENTER);
p1.setBorder (tb);
6) createCompoundBorder :- This can be the combination of any two different kinds of border.
public static CompoundBorder createCompoundBorder(Border outsideBorder,
Border insideBorder)

Creates a compound border specifying the border objects to use for the outside and inside edges.

Border b1 = BorderFactory.createLineBorder (Color.blue, 2);


Border b2 = BorderFactory.createTitledBorder ("login");
p1.setBorder (BorderFactory.createCompoundBorder (b1, b2));

7) createMatteBorder
public static MatteBorder createMatteBorder(int top, int left, int bottom, int right, Color color)
Creates a matte-look border using a solid color.

p1.setBorder(BorderFactory.createMatteBorder (30, 10, 20, 20,Color.red));

Different layout
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
LayoutManager is an interface that is implemented by all the classes of layout managers. There are the
following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
38
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

3. java.awt.GridLayout
4. java.awt.CardLayout
5. javax.swing.BoxLayout

Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west, and
center. Each region (area) may contain one component only. It is the default layout of a frame or
window. The BorderLayout provides five constants for each region:
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
//here f refers to the object of frame
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One component is
displayed in each rectangle.
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
39
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

JButton b7=new JButton("7");


JButton b8=new JButton("8");
JButton b9=new JButton("9");
// adding buttons to the frame
f.add(b1); f.add(b2); f.add(b3);
f.add(b4); f.add(b5); f.add(b6);
f.add(b7); f.add(b8); f.add(b9);
// setting grid layout of 3 rows and 3 columns
f.setLayout(new GridLayout(3,3));

Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another (in a flow).

f = new JFrame();
// creating the buttons
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
40
BCA DDU SEM IV
Java Swing Prof.Aayushi
Shah

JButton b8 = new JButton("8");


JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
// adding the buttons to frame
f.add(b1); f.add(b2); f.add(b3); f.add(b4);
f.add(b5); f.add(b6); f.add(b7); f.add(b8);
f.add(b9); f.add(b10);
f.setLayout(new FlowLayout());

41

You might also like