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

AOT Unit 2

Swing is a Java GUI library that improves upon AWT. It includes more components, expanded features, and event handling. Swing uses MVC architecture and is platform independent. Example programs demonstrate creating buttons, labels, and checkboxes with Swing.

Uploaded by

BABY ABHI RAJ
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)
23 views

AOT Unit 2

Swing is a Java GUI library that improves upon AWT. It includes more components, expanded features, and event handling. Swing uses MVC architecture and is platform independent. Example programs demonstrate creating buttons, labels, and checkboxes with Swing.

Uploaded by

BABY ABHI RAJ
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/ 34

UNIT-II

Introduction to Swing
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit
[AWT]. Java Swing offers much-improved functionality over AWT, new components, expanded
components features, and excellent event handling with drag-and-drop support.
Introduction of Java Swing
Swing has about four times the number of User Interface [UI] components as AWT and is part of
the standard Java distribution. By application GUI requirements, AWT is a limited
implementation, not quite capable of providing the components required for developing complex
GUIs required in modern commercial applications. The AWT component set has quite a few bugs
and does take up a lot of system resources when compared to equivalent Swing resources. Netscape
introduced its Internet Foundation Classes [IFC] library for use with Java. Its Classes became very
popular with programmers creating for commercial applications.
Swing is a Set of API (API- Set of Classes and Interfaces)
Swing is Provided to Design Graphical User Interfaces
Swing is an Extension library to the AWT (Abstract Window Toolkit) 5:00 5:30 pm
Includes New and improved Components that have been enhancing the looks and
Functionality of GUIs
Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets and
Applets
It Employs model/view design architecture.
Swing is more portable and more flexible than AWT, the Swing is built on top of the
AWT.
Swing is Entirely written in Java.
Java Swing Components are Platform-independent, and The Swing Components are
lightweight.
Swing Supports a Pluggable look and feel and Swing provides more powerful
components.
such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
Further Swing Follows MVC.
Difference between Java Swing and Java AWT
There are certain points from which Java Swing is different than Java AWT as mentioned below:
Java AWT Java Swing

Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
applications in Java. and is used to create various applications.

The components of Java Swing are


Components of AWT are heavy weighted.
lightweight.

Components are platform dependent. Components are platform independent.

Execution Time is more than Swing. Execution Time is less than AWT.

Swing components requires javax.swing


AWT components require java.awt package.
package.
What is JFC?
JFC stands for Java Foundation Classes. JFC is the set of GUI components that simplify desktop
Applications. Many programmers think that JFC and Swing are one and the same thing, but that is
not so. JFC contains Swing [A UI component package] and quite a number of other items:
Cut and paste: Clipboard support.
Accessibility features: Aimed at developing GUIs for users with disabilities.
The Desktop Colors Features were first introduced in Java 1.1
Java 2D: it has Improved colors, images, and text support.
Features Of Swing Class
Pluggable look and feel.
Uses MVC architecture.
Lightweight Components
Platform Independent
Advanced features such as JTable, JTabbedPane, JScollPane, etc.
Java is a platform-independent language and runs on any client machine, the GUI look
and feel, owned and delivered by a platform-specific O/S, simply does not affect an
GUI constructed using Swing components.
Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight
component development. For a component to qualify as lightweight, it must not depend
on any non-Java [O/s based) system classes. Swing components have their own view
supported by look and feel classes.
Pluggable Look and Feel: This feature enable the user to switch the look and feel of
Swing components without restarting an application. The Swing library supports
look and feels that remain the same across all platforms wherever the
program runs. The Swing library provides an API that gives real flexibility in
determining the look and feel of the GUI of an application
Highly customizable Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
Rich controls Swing provides a rich set of advanced controls like Tree TabbedPane,
slider, colorpicker, and table controls.
Swing Classes Hierarchy

The MVC Connection


In general, a visual component is a composite of three distinct aspects:
1. The way that the component looks when rendered on the screen.
2. The way such that the component reacts to the user.
3. The state information associated with the component.
Over the years, one component architecture has proven itself to be exceptionally
effective: Model-View-Controller or MVC for short.
In MVC terminology, the model corresponds to the state information associated with
the Component.
The view determines how the component is displayed on the screen, including any
aspects of the view that are affected by the current state of the model.
The controller determines how the component reacts to the user.
The simplest Swing components have capabilities far beyond AWT components as follows:
Swing buttons and labels can be displaying images instead of or in addition to text.
The borders around most Swing components can be changed easily. For example, it is
easy to put a 1-pixel border around the outside of a Swing label.
Swing components do not have to be rectangular. Buttons, for example, can be round.
Now The Latest Assertive technologies such as screen readers can easily get
information from Swing components. Example: A screen reader tool can easily capture
the text that is displayed on a Swing button or label.
Example of Java Swing Programs
Example 1: Develop a program using label (swing) to display the message WEB Site

Java

// Java program using label (swing)


// to display the message WEB Site
import java.io.*;
import javax.swing.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating instance of JFrame
JFrame frame = new JFrame();

// Creating instance of JButton


JButton button = new JButton(" GFG WebSite Click");

// x axis, y axis, width, height


button.setBounds(150, 200, 220, 50);

// adding button in JFrame


frame.add(button);

// 400 width and 500 height


frame.setSize(500, 600);

// using no layout managers


frame.setLayout(null);

// making the frame visible


frame.setVisible(true);
}
}

Output:

Example 2: Write a program to create three buttons with caption OK, SUBMIT, CANCEL.

Java

// Java program to create three buttons


// with caption OK, SUBMIT, CANCEL
import java.awt.*;

class button {
button()
{
Frame f = new Frame();

// Button 1 created
// OK button
Button b1 = new Button("OK");
b1.setBounds(100, 50, 50, 50);
f.add(b1);

// Button 2 created
// Submit button
Button b2 = new Button("SUBMIT");
b2.setBounds(100, 101, 50, 50);
f.add(b2);

// Button 3 created
// Cancel button
Button b3 = new Button("CANCEL");
b3.setBounds(100, 150, 80, 50);
f.add(b3);

f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String a[]) { new button(); }


}

Output:

Example 3: Program to Add Checkbox in the Frame

Java

// Java Swing Program to Add Checkbox


// in the Frame
import java.awt.*;

// Driver Class
class Lan {
// Main Function
Lan()
{
// Frame Created
Frame f = new Frame();

Label l1 = new Label("Select known Languages");

l1.setBounds(100, 50, 120, 80);


f.add(l1);
// CheckBox created
Checkbox c2 = new Checkbox("Hindi");
c2.setBounds(100, 150, 50, 50);
f.add(c2);

// CheckBox created
Checkbox c3 = new Checkbox("English");
c3.setBounds(100, 200, 80, 50);
f.add(c3);

// CheckBox created
Checkbox c4 = new Checkbox("marathi");
c4.setBounds(100, 250, 80, 50);
f.add(c4);

f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String ar[]) { new Lan(); }


}

Output:

Components of Swing Class the percentage


Class Description

A Component is the Abstract base class for


Component
about the non-menu user-interface controls
Class Description

of Java SWING. Components are


representing an object with a graphical
representation.

A Container is a component that can


Container
container Java SWING Components

A JComponent is a base class for all swing


UI Components In order to use a swing
component that inherits from JComponent,
JComponent
the component must be in a containment
hierarchy whose root is a top-level Java
Swing container.

A JLabel is an object component for placing


JLabel
text in a container.

JButton This class creates a labeled button.

A JColorChooser provides a pane of controls


JColorChooser designed to allow the user to manipulate and
select a color.

A JCheckBox is a graphical (GUI)


JCheckBox component that can be in either an on-(true)
or off-(false) state.

The JRadioButton class is a graphical (GUI)


JRadioButton component that can be in either an on-(true)
or off-(false) state. in the group

A JList component represents the user with


JList
the scrolling list of text items.

A JComboBox component is Presents the


JComboBox
User with a show up Menu of choices.

A JTextField object is a text component that


JTextField will allow for the editing of a single line of
text.

A JPasswordField object it is a text


JPasswordField
component specialized for password entry.
Class Description

A JTextArea object is a text component that


JTextArea allows for the editing of multiple lines of
text.

A ImageIcon control is an implementation of


Imagelcon the Icon interface that paints Icons from
Images

A JScrollbar control represents a scroll bar


JScrollbar component in order to enable users to Select
from range values.

JOptionPane provides set of standard dialog


JOptionPane boxes that prompt users for a value or
Something.

A JFileChooser it Controls represents a


JFileChooser dialog window from which the user can
select a file.

As the task progresses towards completion,


JProgressBar the progress bar displays the tasks
percentage on its completion.

A JSlider this class is letting the user


JSlider graphically (GUI) select by using a value by
sliding a knob within a bounded interval.

A JSpinner this class is a single line input


where the field that lets the user select by
JSpinner
using a number or an object value from an
ordered sequence.

JApplet in Java
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The
JApplet class extends the Applet class.

Example of EventHandling in JApplet:

1. import java.applet.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class EventJApplet extends JApplet implements ActionListener{
5. JButton b;
6. JTextField tf;
7. public void init(){
8.
9. tf=new JTextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new JButton("Click");
13. b.setBounds(80,150,70,40);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is invoked only once.

myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Java 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.

JButton class declaration

Let's see the declaration for javax.swing.JButton class.

1. public class JButton extends AbstractButton implements Accessible


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.

Java JButton Example


1. import javax.swing.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton("Click Here");
6. b.setBounds(50,100,95,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }

Output:
Java JToggleButton

JToggleButton is used to create toggle button, it is two-states button to switch on or off.

Nested Classes

Modifier Class Description


and
Type

protected JToggleButton.AccessibleJToggleButton This class implements accessibility


class support for the JToggleButton class.

static class JToggleButton.ToggleButtonModel The ToggleButton model

Constructors

Constructor Description

JToggleButton() It creates an initially unselected toggle button without setting


the text or image.

JToggleButton(Action a) It creates a toggle button where properties are taken from the
Action supplied.

JToggleButton(Icon icon) It creates an initially unselected toggle button with the


specified image but no text.

JToggleButton(Icon icon, boolean It creates a toggle button with the specified image and
selected) selection state, but no text.

JToggleButton(String text) It creates an unselected toggle button with the specified text.

JToggleButton(String text, boolean It creates a toggle button with the specified text and selection
selected) state.
JToggleButton(String text, Icon It creates a toggle button that has the specified text and
icon) image, and that is initially unselected.

JToggleButton(String text, Icon It creates a toggle button with the specified text, image, and
icon, boolean selected) selection state.

Methods

Modifier and Method Description


Type

AccessibleContext getAccessibleContext() It gets the AccessibleContext associated with this


JToggleButton.

String getUIClassID() It returns a string that specifies the name of the l&f
class that renders this component.

protected String paramString() It returns a string representation of this


JToggleButton.

void updateUI() It resets the UI property to a value from the current


look and feel.

JToggleButton Example
1. import java.awt.FlowLayout;
2. import java.awt.event.ItemEvent;
3. import java.awt.event.ItemListener;
4. import javax.swing.JFrame;
5. import javax.swing.JToggleButton;
6.
7. public class JToggleButtonExample extends JFrame implements ItemListener {
8. public static void main(String[] args) {
9. new JToggleButtonExample();
10. }
11. private JToggleButton button;
12. JToggleButtonExample() {
13. setTitle("JToggleButton with ItemListener Example");
14. setLayout(new FlowLayout());
15. setJToggleButton();
16. setAction();
17. setSize(200, 200);
18. setVisible(true);
19. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. private void setJToggleButton() {
22. button = new JToggleButton("ON");
23. add(button);
24. }
25. private void setAction() {
26. button.addItemListener(this);
27. }
28. public void itemStateChanged(ItemEvent eve) {
29. if (button.isSelected())
30. button.setText("OFF");
31. else
32. button.setText("ON");
33. }
34. }

Output

Java 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.

JCheckBox class declaration

Let's see the declaration for javax.swing.JCheckBox class.

1. public class JCheckBox extends JToggleButton implements Accessible


Commonly used Constructors:

Constructor Description

JJCheckBox() 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 used Methods:

Methods Description

AccessibleContext It is used to get the AccessibleContext associated with this


getAccessibleContext() JCheckBox.

protected String paramString() It returns a string representation of this JCheckBox.

Java JCheckBox Example


1. import javax.swing.*;
2. public class CheckBoxExample
3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new JCheckBox("C++");
7. checkBox1.setBounds(100,100, 50,50);
8. JCheckBox checkBox2 = new JCheckBox("Java", true);
9. checkBox2.setBounds(100,150, 50,50);
10. f.add(checkBox1);
11. f.add(checkBox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}

Output:

Java JRadioButton

The JRadioButton class is used to create a radio button. It is used to choose one option from multiple
options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration

Let's see the declaration for javax.swing.JRadioButton class.

1. public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified text.

JRadioButton(String s, boolean Creates a radio button with the specified text and selected
selected) status.
Commonly used Methods:

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.

Java JRadioButton Example


1. import javax.swing.*;
2. public class RadioButtonExample {
3. JFrame f;
4. RadioButtonExample(){
5. f=new JFrame();
6. JRadioButton r1=new JRadioButton("A) Male");
7. JRadioButton r2=new JRadioButton("B) Female");
8. r1.setBounds(75,50,100,30);
9. r2.setBounds(75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. bg.add(r1);bg.add(r2);
12. f.add(r1);f.add(r2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new RadioButtonExample();
19. }
20. }

Output:
Java JComboBox

The object of Choice class is used to show popup menu of choices. Choice selected by user is shown
on the top of a menu. It inherits JComponent class.

JComboBox class declaration

Let's see the declaration for javax.swing.JComboBox class.

1. public class JComboBox extends JComponent implements ItemSelectable, ListDataListener


, ActionListener, Accessible

Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] Creates a JComboBox that contains the elements in the


items) specified array.

JComboBox(Vector<?> Creates a JComboBox that contains the elements in the


items) specified Vector.

Commonly used Methods:

Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is
editable.

void addActionListener(ActionListener It is used to add the ActionListener.


a)

void addItemListener(ItemListener i) It is used to add the ItemListener.

Java JComboBox Example


1. import javax.swing.*;
2. public class ComboBoxExample {
3. JFrame f;
4. ComboBoxExample(){
5. f=new JFrame("ComboBox Example");
6. String country[]={"India","Aus","U.S.A","England","Newzealand"};
7. JComboBox cb=new JComboBox(country);
8. cb.setBounds(50, 50,90,20);
9. f.add(cb);
10. f.setLayout(null);
11. f.setSize(400,500);
12. f.setVisible(true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. }
17. }

Output:
Java JTextField

The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.

JTextField class declaration

Let's see the declaration for javax.swing.JTextField class.

1. public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.

JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.

JTextField(int columns) Creates a new empty TextField with the specified number of
columns.

Commonly used Methods:

Methods Description

void It is used to add the specified action listener to receive


addActionListener(ActionListener l) action events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so that it


removeActionListener(ActionListener no longer receives action events from this textfield.
l)

Java JTextField Example


1. import javax.swing.*;
2. class TextFieldExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("TextField Example");
7. JTextField t1,t2;
8. t1=new JTextField("Welcome to Javatpoint.");
9. t1.setBounds(50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. t2.setBounds(50,150, 200,30);
12. f.add(t1); f.add(t2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }

Output:

Java JLabel

The object of JLabel class is a component for placing text in a container. It is used to display a single
line of read only text. The text can be changed by an application but a user cannot edit it directly. It
inherits JComponent class.

JLabel class declaration

Let's see the declaration for javax.swing.JLabel class.

1. public class JLabel extends JComponent implements SwingConstants, Accessible


Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no image and with an empty


string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.

Commonly used Methods:

Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will
display.

void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents along the X
axis.

Java JLabel Example


1. import javax.swing.*;
2. class LabelExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("Label Example");
7. JLabel l1,l2;
8. l1=new JLabel("First Label.");
9. l1.setBounds(50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. l2.setBounds(50,100, 100,30);
12. f.add(l1); f.add(l2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }

Output:

Java JTabbedPane

The JTabbedPane class is used to switch between a group of components by clicking on a tab with a
given title or icon. It inherits JComponent class.

JTabbedPane class declaration

Let's see the declaration for javax.swing.JTabbedPane class.

1. public class JTabbedPane extends JComponent implements Serializable, Accessible, Swing


Constants

Commonly used Constructors:

Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default tab placement


of JTabbedPane.Top.

JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab


placement.

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab


tabLayoutPolicy) placement and tab layout policy.
Java JTabbedPane Example
1. import javax.swing.*;
2. public class TabbedPaneExample {
3. JFrame f;
4. TabbedPaneExample(){
5. f=new JFrame();
6. JTextArea ta=new JTextArea(200,200);
7. JPanel p1=new JPanel();
8. p1.add(ta);
9. JPanel p2=new JPanel();
10. JPanel p3=new JPanel();
11. JTabbedPane tp=new JTabbedPane();
12. tp.setBounds(50,50,200,200);
13. tp.add("main",p1);
14. tp.add("visit",p2);
15. tp.add("help",p3);
16. f.add(tp);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String[] args) {
22. new TabbedPaneExample();
23. }}

Output:
Java JScrollPane

A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a
scroll pane to display a large component or a component whose size can change dynamically.

Constructors

Constructor Purpose

JScrollPane() It creates a scroll pane. The Component parameter, when present, sets
the scroll pane's client. The two int parameters, when present, set the
JScrollPane(Component) vertical and horizontal scroll bar policies (respectively).

JScrollPane(int, int)

JScrollPane(Component,
int, int)

Useful Methods

Modifier Method Description

void setColumnHeaderView(Component) It sets the column header for the scroll pane.

void setRowHeaderView(Component) It sets the row header for the scroll pane.

void setCorner(String, Component) It sets or gets the specified corner. The int
parameter specifies which corner and must be
Component getCorner(String) one of the following constants defined in
ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

void setViewportView(Component) Set the scroll pane's client.

JScrollPane Example
1. import java.awt.FlowLayout;
2. import javax.swing.JFrame;
3. import javax.swing.JScrollPane;
4. import javax.swing.JtextArea;
5.
6. public class JScrollPaneExample {
7. private static final long serialVersionUID = 1L;
8.
9. private static void createAndShowGUI() {
10.
11. // Create and set up the window.
12. final JFrame frame = new JFrame("Scroll Pane Example");
13.
14. // Display the window.
15. frame.setSize(500, 500);
16. frame.setVisible(true);
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18.
19. // set flow layout for the frame
20. frame.getContentPane().setLayout(new FlowLayout());
21.
22. JTextArea textArea = new JTextArea(20, 20);
23. JScrollPane scrollableTextArea = new JScrollPane(textArea);
24.
25. scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROL
LBAR_ALWAYS);
26. scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR
_ALWAYS);
27.
28. frame.getContentPane().add(scrollableTextArea);
29. }
30. public static void main(String[] args) {
31.
32.
33. javax.swing.SwingUtilities.invokeLater(new Runnable() {
34.
35. public void run() {
36. createAndShowGUI();
37. }
38. });
39. }
40. }
Output:

Java 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.

JList class declaration

Let's see the declaration for javax.swing.JList class.

1. public class JList extends JComponent implements Scrollable, Accessible

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, non-null,
dataModel) model.

Commonly used Methods:

Methods Description

Void It is used to add a listener to the list, to be notified


addListSelectionListener(ListSelectionListener each time a change to the selection occurs.
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.

void setListData(Object[] listData) It is used to create a read-only ListModel from an


array of objects.

Java JList Example


1. import javax.swing.*;
2. public class ListExample
3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>();
7. l1.addElement("Item1");
8. l1.addElement("Item2");
9. l1.addElement("Item3");
10. l1.addElement("Item4");
11. JList<String> list = new JList<>(l1);
12. list.setBounds(100,100, 75,75);
13. f.add(list);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }}

Output:
Java JTree

The JTree class is used to display the tree structured data or hierarchical data. JTree is a complex
component. It has a 'root node' at the top most which is a parent for all nodes in the tree. It inherits
JComponent class.

JTree class declaration

Let's see the declaration for javax.swing.JTree class.

1. public class JTree extends JComponent implements Scrollable, Accessible

Commonly used Constructors:

Constructor Description

JTree() Creates a JTree with a sample model.

JTree(Object[] Creates a JTree with every element of the specified array as the child of a new
value) root node.

JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which displays the root
root) node.

Java JTree Example


1. import javax.swing.*;
2. import javax.swing.tree.DefaultMutableTreeNode;
3. public class TreeExample {
4. JFrame f;
5. TreeExample(){
6. f=new JFrame();
7. DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
8. DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
9. DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
10. style.add(color);
11. style.add(font);
12. DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
13. DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
14. DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
15. DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
16. color.add(red); color.add(blue); color.add(black); color.add(green);
17. JTree jt=new JTree(style);
18. f.add(jt);
19. f.setSize(200,200);
20. f.setVisible(true);
21. }
22. public static void main(String[] args) {
23. new TreeExample();
24. }}

Output:

Java JTable

The JTable class is used to display data in tabular form. It is composed of rows and columns.

JTable class declaration

Let's see the declaration for javax.swing.JTable class.

Commonly used Constructors:

Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

Java JTable Example


1. import javax.swing.*;
2. public class TableExample {
3. JFrame f;
4. TableExample(){
5. f=new JFrame();
6. String data[][]={ {"101","Amit","670000"},
7. {"102","Jai","780000"},
8. {"101","Sachin","700000"}};
9. String column[]={"ID","NAME","SALARY"};
10. JTable jt=new JTable(data,column);
11. jt.setBounds(30,40,200,300);
12. JScrollPane sp=new JScrollPane(jt);
13. f.add(sp);
14. f.setSize(300,400);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new TableExample();
19. }
20. }

Output:

Introduction to JavaBeans

JavaBeans is a portable, platform-independent model written in Java Programming Language. Its


components are referred to as beans.

In simple terms, JavaBeans are classes which encapsulate several objects into a single object. It helps
in accessing these object from multiple places. JavaBeans contains several elements like Constructors,
Getter/Setter Methods and much more.

JavaBeans has several conventions that should be followed:

Beans should have a default constructor (no arguments)


Beans should provide getter and setter methods
o A getter method is used to read the value of a readable property
o To update the value, a setter method should be called
Beans should implement java.io.serializable, as it allows to save, store and restore the state of
a JavaBean you are working on

What are JavaBean Properties?


A JavaBean property can be accessed by the user of the object. The feature can be of any Java data type,
containing the classes that you define. It may be of the following mode: read, write, read-only, or write-
only. JavaBean features are accessed through two methods:

1. getEmployeeName ()

For example, if the employee name is firstName, the method name would be getFirstName() to read
that employee name. This method is known as an accessor. Properties of getter methods are as
follows:

1. Must be public in nature


2. Return-type should not be void
3. The getter method should be prefixed with the word get
4. It should not take any argument

2.setEmployeeName ()

For example, if the employee name is firstName, the method name would be setFirstName() to write
that employee name. This method is known as a mutator. Properties of setter methods:

1. Must be public in nature


2. Return-type should be void
3. The setter method has to be prefixed with the word set
4. It should take some argument

Now that you have attained some theoretical knowledge about JavaBeans, let us move on and
understand the implementation process.

Example Program: Implementation of JavaBeans


The example program shown below demonstrates how to implement JavaBeans.

1public class Employee implements java.io.Serializable


2{
3private int id;
4private String name;
5public Employee()
6 {
7 }
8public void setId(int id)
9 {
10 this.id = id;
11 }
12public int getId()
13 {
14 return id;
15 }
16public void setName(String name)
17 {
18 this.name = name;
19 }
20public String getName()
21 {
22 return name;
23 }
24}
Next program is written in order to access the JavaBean class that we created above:

1public class Employee1 {


2public static void main(String args[])
3{
4 Employee s = new Employee();
5 s.setName("Chandler");
6 System.out.println(s.getName());
7}
8}
Output:

Chandler

Advantages of Javabeans

The best thing about Java beans is that you have to write code only once and can run
anywhere.
You can work on several local platforms.
The developer can control properties, methods, and events.
At design time, a user can configure JavaBeans without any disturbance.

have to make the extra effort to create a suitable environment to support JavaBean.
JavaBeans are compatible in nature.
Public T getN()
Public void setN( T arg)

private double depth,height,width;


public double getDepth()
{
reaturn depth;
}
public void setDepth(double d)
{
depth=d;
}
public void getHeight()
{
return height;
}
public void setHeight(double h)
{
height=h;
}
public double getWidth()
{
return width;
}
public void setWidth(double w)
{
width=w;
}

Public T getN(int index);


Public void setN(int index, T value);
Public t[] getN();
Public void setN( T values[]);

package sunw.demo.indexdemo;
public class indexdemo
{
private final static int n=5;
private boolean X[];
public indexdemo()
{
x=new boolean[n];
for(int i=0;i<n;i++)
X[i]=false;
}
public boolean getX(int index)
{
return X[index];
}
public void setX(int index,boolean value)
{
X[index]=value;
}
public void setX(boolean values[])
{
X=values;
}
}

You might also like