0% found this document useful (0 votes)
11 views25 pages

Swing

Swing is a Java Foundation Classes library that extends AWT, offering enhanced functionality and a wider range of UI components for building complex GUIs. It employs a model/view design architecture, is platform-independent, and supports a pluggable look and feel, making it more flexible than AWT. Key components of Swing include JButton, JLabel, JTextField, JComboBox, and JCheckBox, each providing various functionalities for user interaction.

Uploaded by

pvy1524
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)
11 views25 pages

Swing

Swing is a Java Foundation Classes library that extends AWT, offering enhanced functionality and a wider range of UI components for building complex GUIs. It employs a model/view design architecture, is platform-independent, and supports a pluggable look and feel, making it more flexible than AWT. Key components of Swing include JButton, JLabel, JTextField, JComboBox, and JCheckBox, each providing various functionalities for user interaction.

Uploaded by

pvy1524
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/ 25

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 today’s 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 GUI’s 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)
 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.

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
application’s 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 Java’s 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
components’ 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.

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.

Components of Swing Class


Class Description

A Component is the Abstract base class for about the


non-menu user-interface controls of Java SWING.
Component
Components are representing an object with a graphical
representation.

A Container is a component that can container Java


Container
SWING Components

A JComponent is a base class for all swing UI


Components In order to use a swing component that
JComponent inherits from 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 text in a


JLabel
container.

JButton This class creates a labeled button.

A JColorChooser provides a pane of controls designed to


JColorChooser
allow the user to manipulate and select a color.
Class Description

A JCheckBox is a graphical (GUI) component that can be


JCheckBox
in either an on-(true) or off-(false) state.

The JRadioButton class is a graphical (GUI) component


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

A JList component represents the user with the scrolling


JList
list of text items.

A JComboBox component is Presents the User with a


JComboBox
show up Menu of choices.

A JTextField object is a text component that will allow for


JTextField
the editing of a single line of text.

A JPasswordField object it is a text component


JPasswordField
specialized for password entry.

A JTextArea object is a text component that allows for


JTextArea
the editing of multiple lines of text.

A ImageIcon control is an implementation of the Icon


Imagelcon
interface that paints Icons from Images

A JScrollbar control represents a scroll bar component in


JScrollbar
order to enable users to Select from range values.
Class Description

JOptionPane provides set of standard dialog boxes that


JOptionPane
prompt users for a value or Something.

A JFileChooser it Controls represents a dialog window


JFileChooser
from which the user can select a file.

As the task progresses towards completion, the progress


JProgressBar
bar displays the tasks percentage on its completion.

A JSlider this class is letting the user graphically (GUI)


JSlider 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


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

A container holds a group of components. It provides a space where a component can be


managed and displayed. Containers are of two types:

1. Top level Containers

o It inherits Component and Container of AWT.

o It cannot be contained within other containers.

o Heavyweight.

o Example: JFrame, JDialog, JApplet

2. Lightweight Containers

o It inherits JComponent class.

o It is a general purpose container.


o It can be used to organize related components together.

o Example: JPanel

Swing JButton

JButton class provides functionality of a button. It is used to create button component. JButton
class has three constuctors,

Example of JButton

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testswing extends JFrame
{

testswing()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes Button.
JButton bt2 = new JButton("No"); //Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout object
setSize(400, 400); //setting size of Jframe
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.

setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}
JLabel
JLabel is a class of java Swing . JLabel is used to display a short string or an image icon.
JLabel can display text, image or both . JLabel is only a display of text or image and it cannot
get focus . JLabel is inactive to input events such a mouse focus or keyboard focus. By default
labels are vertically centered but the user can change the alignment of label.
Constructor of the class are :

1. JLabel() : creates a blank label with no text or image in it.


2. JLabel(String s) : creates a new label with the string specified.
3. JLabel(Icon i) : creates a new label with a image on it.
4. JLabel(String s, Icon i, int align) : creates a new label with a string, an image and a
specified horizontal alignment

Commonly used methods of the class are :

1. getIcon() : returns the image that the label displays


2. setIcon(Icon i) : sets the icon that the label will display to image i
3. getText() : returns the text that the label will display
4. setText(String s) : sets the text that the label will display to string s

Icon
Many Swing components, such as labels, buttons, and tabbed panes, can be decorated with
an icon — a fixed-sized picture. An icon is an object that adheres to the Icon interface. Swing
provides a particularly useful implementation of the Icon interface: ImageIcon, which paints an
icon from a GIF, JPEG, or PNG image.

The program uses one image icon to contain and paint the yellow splats. One statement creates
the image icon and two more statements include the image icon on each of the two labels:

ImageIcon icon = createImageIcon("images/middle.gif","a pretty but meaningless splat");


label1 = new JLabel("Image and Text", icon, JLabel.CENTER);
...
label3 = new JLabel(icon);

JTextField

JTextField is a part of javax.swing package. The class JTextField is a component that allows
editing of a single line of text. JTextField inherits the JTextComponent class and uses the
interface SwingConstants.

The constructor of the class are :


1. JTextField() : constructor that creates a new TextField
2. JTextField(int columns) : constructor that creates a new empty TextField with specified
number of columns.
3. JTextField(String text) : constructor that creates a new empty text field initialized with
the given string.
4. JTextField(String text, int columns) : constructor that creates a new empty textField with
the given string and a specified number of columns .
5. JTextField(Document doc, String text, int columns) : constructor that creates a textfield
that uses the given text storage model and the given number of columns.

Methods of the JTextField are:


1. setColumns(int n) :set the number of columns of the text field.
2. setFont(Font f) : set the font of text displayed in text field.
3. addActionListener(ActionListener l) : set an ActionListener to the text field.
4. int getColumns() :get the number of columns in the textfield

JComboBox

JComboBox is a part of Java Swing package. JComboBox inherits JComponent class .


JComboBox shows a popup menu that shows a list and the user can select a option from that
specified list . JComboBox can be editable or read- only depending on the choice of the
programmer .
Constructor of the JComboBox are:

1. JComboBox() : creates a new empty JComboBox .


2. JComboBox(ComboBoxModel M) : creates a new JComboBox with items from specified
ComboBoxModel
3. JComboBox(E [ ] i) : creates a new JComboBox with items from specified array.
4. JComboBox(Vector items) : creates a new JComboBox with items from the specified
vector
Commonly used Methods are :

1. addItem(E item) : adds the item to the JComboBox


2. addItemListener( ItemListener l) : adds a ItemListener to JComboBox
3. getItemAt(int i) : returns the item at index i
4. getItemCount(): returns the number of items from the list
5. getSelectedItem() : returns the item which is selected
6. removeItemAt(int i) : removes the element at index i
7. setEditable(boolean b) : the boolean b determines whether the combo box is editable or
not .If true is passed then the combo box is editable or vice versa.
8. setSelectedIndex(int i): selects the element of JComboBox at index i.
9. showPopup() :causes the combo box to display its popup window.
10. setUI(ComboBoxUI ui): sets the L&F object that renders this component.
11. setSelectedItem(Object a): sets the selected item in the combo box display area to the
object in the argument.
12. setSelectedIndex(int a): selects the item at index anIndex.
13. setPopupVisible(boolean v): sets the visibility of the popup.
14. setModel(ComboBoxModel a) : sets the data model that the JComboBox uses to obtain
the list of items.
15. setMaximumRowCount(int count): sets the maximum number of rows the JComboBox
displays.
16. setEnabled(boolean b): enables the combo box so that items can be selected.
17. removeItem(Object anObject) : removes an item from the item list.
18. removeAllItems(): removes all items from the item list.
19. removeActionListener(ActionListener l): removes an ActionListener.
20. isPopupVisible() : determines the visibility of the popup.
21. addPopupMenuListener(PopupMenuListener l) : adds a PopupMenu listener which will
listen to notification messages from the popup portion of the combo box.
22. getActionCommand() : returns the action command that is included in the event sent to
action listeners.
23. getEditor(): returns the editor used to paint and edit the selected item in the JComboBox
field.
24. getItemCount() : returns the number of items in the list.
25. getItemListeners(): returns an array of all the ItemListeners added to this JComboBox
with addItemListener().
26. createDefaultKeySelectionManager() : returns an instance of the default key-selection
manager.
27. fireItemStateChanged(ItemEvent e) : notifies all listeners that have registered interest for
notification on this event type.
28. firePopupMenuCanceled() : notifies PopupMenuListeners that the popup portion of the
combo box has been canceled.
29. firePopupMenuWillBecomeInvisible() : notifies PopupMenuListeners that the popup
portion of the combo box has become invisible.
30. firePopupMenuWillBecomeVisible() : notifies PopupMenuListeners that the popup
portion of the combo box will become visible.
31. setEditor(ComboBoxEditor a): sets the editor used to paint and edit the selected item in
the JComboBox field.
32. setActionCommand(String a) : sets the action command that should be included in the
event sent to actionListeners.
33. getUI() : returns the look and feel object that renders this component.
34. paramString() : returns a string representation of this JComboBox.
35. getUIClassID() : returns the name of the Look and feel class that renders this component.
36. getAccessibleContext() : gets the AccessibleContext associated with this JComboBox

JCheckBox
JCheckBox is a part of Java Swing package . JCheckBox can be selected or deselected . It
displays it state to the user . JCheckBox is an implementation to checkbox . JCheckBox
inherits JToggleButton class.
Constructor of the class are :
1. JCheckBox() : creates a new checkbox with no text or icon
2. JCheckBox(Icon i) : creates a new checkbox with the icon specified
3. JCheckBox(Icon icon, boolean s) : creates a new checkbox with the icon specified and the
boolean value specifies whether it is selected or not.
4. JCheckBox(String t) :creates a new checkbox with the string specified
5. JCheckBox(String text, boolean selected) :creates a new checkbox with the string
specified and the boolean value specifies whether it is selected or not.
6. JCheckBox(String text, Icon icon) :creates a new checkbox with the string and the icon
specified.
7. JCheckBox(String text, Icon icon, boolean selected): creates a new checkbox with the
string and the icon specified and the boolean value specifies whether it is selected or not.

Methods to add Item Listener to checkbox.


1. addActionListener(ItemListener l): adds item listener to the component
2. itemStateChanged(ItemEvent e) : abstract function invoked when the state of the item to
which listener is applied changes
3. getItem() : Returns the component-specific object associated with the item whose state
changed
4. getStateChange() : Returns the new state of the item. The ItemEvent class defines two
states: SELECTED and DESELECTED.
5. getSource() : Returns the component that fired the item event.
Commonly used methods:
1. setIcon(Icon i) : sets the icon of the checkbox to the given icon
2. setText(String s) :sets the text of the checkbox to the given text
3. setSelected(boolean b) : sets the checkbox to selected if boolean value passed is true or
vice versa
4. getIcon() : returns the image of the checkbox
5. getText() : returns the text of the checkbox
6. updateUI() : resets the UI property with a value from the current look and feel.
7. getUI() : returns the look and feel object that renders this component.
8. paramString() : returns a string representation of this JCheckBox.
9. getUIClassID() : returns the name of the Look and feel class that renders this component.
10. getAccessibleContext() : gets the AccessibleContext associated with this JCheckBox.
11. isBorderPaintedFlat() : gets the value of the borderPaintedFlat property.
12. setBorderPaintedFlat(boolean b) : sets the borderPaintedFlat property,

RadioButtons
RadioButtons are a part of Javax package. RadioButtons are mainly used to create a series of
items where only one can be selected. When a Radio button is pressed and released an Action
event is sent, this Action Event can be handled using an Event Handler.
RadioButton can be added to Toggle Group so that the user cannot select more than one item .
By default a radio button is not a part of any toggle group. The selected item of a toggle group
can be found using getSelectedToggle() function.
Constructors of the RadioButton class:
1. RadioButton():Creates a radio button with an empty string for its label.
2. RadioButton(String t):Creates a radio button with the specified text as its label
Commonly used methods:
method explanation

getText() returns the textLabel for radio button

isSelected() returns whether the radiobutton is selected or not

setSelected(boolean b) sets whether the radiobutton is selected or not

setToggleGroup(ToggleGroup
sets the toggle group for the radio button
tg)

Toggles the state of the radio button if and only if the


fire() RadioButton has not already selected or is not part of a
ToggleGroup.

Advanced Swing Component:

JTabbedPane
JTabbedPane is a GUI(Graphical User Interface) component in the Java Swing library that
allows you to create a tabbed pane interface. A tabbed pane is a container that can store and
organize multiple components into distinct tabs. It contains a collection of tabs. When you
click on a tab, only data related to that tab will be displayed. JTabbedPane comes under the
Java Swing package.

Key Features of JTabbedPane


 Tabs: Each tab in a JTabbedPane is normally represented by a title or icon, and clicking on
a particular tab shows the information only related to that tab.
 Tab Placement: JTabbedPane provides many tab placement options, such as top, bottom,
left, or right sides of the pane, allowing you to customize the layout.
 Scrolling: If the tabs don't fit in the visible region, JTabbedPane provides scrolling options
to navigate through them.
 Event Handling: You can add event listeners to JTabbedPane to respond to tab selection
or deselection events, allowing you to do actions when the user switches between tabs.
Constructors used in JTabbedPane
Constructor Description

The JTabbedPane class in Java Swing has a default, no-argument


constructor called JTabbedPane(). This constructor initializes an
empty tabbed pane with no tabs and no initial content when a
JTabbedPane() JTabbedPane is created.

The JTabbedPane(int tabPlacement) constructor allows to creation


of a JTabbedPane with a defined initial location for the tabs. The tab
JTabbedPane(int placement option specifies whether the tabs appear at the top,
tabPlacement) bottom, left, or right of the tabbed pane.

Some commonly used methods of the JTabbedPane


Method Description

addTab(String title, Component Creates a new tab with the given title and
component) content.

removeTabAt(int index) Removes the tab at the given index.

Returns the number of tabs present in the


getTabCount() JTabbedPane.

setSelectedIndex(int index) Sets the chosen tab to the index given.

getSelectedIndex() Returns the index of the currently selected tab.

The classes from which JTabbedPane methods are inherited


 java.awt.Container
 javax.swing.JComponent
 javax.swing.JTabbedPane
 javax.swing.JContainer
Example of JTabbed Pane

import javax.swing.*;
import java.awt.*;

// Driver Class
public class TabbedUIExample1 {
// main function
public static void main(String[] args) {
// Run the Swing application on the Event Dispatch Thread (EDT)
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Create a new JFrame (window)
JFrame window = new JFrame("JTabbedPane Example");
// Close operation when the window is closed
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close
operation when the window is closed
// Set the initial size of the window
window.setSize(400, 300);

// Create a JTabbedPane, which will hold the tabs


JTabbedPane tabPanel = new JTabbedPane();

// Create the first tab (page1) and add a JLabel to it


JPanel page1 = new JPanel();
page1.add(new JLabel("This is Tab 1"));

// Create the second tab (page2) and add a JLabel to it


JPanel page2 = new JPanel();
page2.add(new JLabel("This is Tab 2"));

// Create the third tab (page3) and add a JLabel to it


JPanel page3 = new JPanel();
page3.add(new JLabel("This is Tab 3"));

// Add the three tabs to the JTabbedPane


tabPanel.addTab("Tab 1", page1);
tabPanel.addTab("Tab 2", page2);
tabPanel.addTab("Tab 3", page3);

// Add the JTabbedPane to the JFrame's content


window.add(tabPanel);

// Make the JFrame visible


window.setVisible(true);
}
});
}
}

JScrollPane
Java JScrollPane is a component in the Java Swing library that provides a scrollable view of
another component, usually a JPanel or a JTextArea. it provides a scrolling functionality to the
display for which the size changes dynamically. It is useful to display the content which exceeds
the visible area of the window. In this article, we are going to see some constructors, methods,
and examples of JScrollPane.

Constructor of JScrollPane
Constructors Descriptions

It is a default constructor that creates an empty


JScrollPane()
JScrollPane.

This constructor creates a JScrollPane with the


JScrollPane(Component comp)
specified view component as the scrollable content.
Constructors Descriptions

JScrollPane(int vertical, int This constructor creates an empty JScrollPane with the
horizontal) specified vertical and horizontal scrollbar.

JScrollPane(LayoutManager This constructor creates a JScrollPane with the


layout) specified layout manager.

Methods of JScrollPane
Methods Description

void setVerticalScrollBarPolicy(int
Sets the vertical scrollbar policy
vertical)

void setHorizontalScrollBarPolicy(int
Sets the horizontal scrollbar policy
horizontal)

void
setColumnHeaderView(Component sets the column header for the JScrollPane
comp)

void setRowHeaderView(Component
sets the rowheader for the JScrollPane
comp)

setCorner(String key, Component It is used to set a component to be displayed in


corner) one of the corners of the scroll pane

It is used to retrieve the component that has been


Component getCorner(String key) previously set in one of the corners of the scroll
pane using the setCorner method

void setViewportView(Component It is used to set the component that will be


comp) displayed in the viewport of the scroll pane
Example of JScrollPane

import javax.swing.*;
import java.awt.*;

// Driver Class
public class SimpleJScrollPaneExample {
// main function
public static void main(String[] args) {

JFrame frame = new JFrame("Simple JScrollPane Example");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

// Create a JPanel to hold a list of labels.


JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

// Add a large number of labels to the panel.


for (int i = 1; i <= 50; i++) {

JLabel label = new JLabel("Label " + i);


panel.add(label);

// Create a JScrollPane and set the panel as its viewport.


JScrollPane scrollPane = new JScrollPane(panel);

// Add the JScrollPane to the frame.


frame.add(scrollPane);
frame.setVisible(true);
}
}
Output:

JTree

The JTree is a type of GUI(Graphic User Interface) that displays information in a hierarchical
way. This intricate component part provides a quite elegant substance of representing
relationships among elements in a tree-like structure. In this exploration, we'll delve into the
essence of the JTree class, examining its declaration, normally used constructors and examples.
JTree Class Declaration
The JTree class is an extension of the JComponent class, inheriting its capabilities. It also
implements the Scrollable and Accessible interfaces, enhancing its functionality and
accessibility.
public class JTree extends JComponent implements Scrollable, Accessible

Commonly Used Constructors


Constructor Description

This constructor creates a JTree with a sample model. It serves as a


quick way to initialize a tree structure without specifying a custom
JTree() model.

JTree is created with each element of the specified array becoming a


JTree(Object[] child of a new root node. This constructor is useful when you want to
value) build a tree structure based on an array of values.

JTree is created with the specified TreeNode as its root. This allows you
JTree(TreeNode to define a custom structure for your tree by providing a root node
root) explicitly.
Example of Java JTree:
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class DynamicTreeExample {


public static void main(String[] args)
{
// Creating the frame
JFrame frame = new JFrame(
"GeeksforGeeks - Java JTree Example");

// Creating the root node


DefaultMutableTreeNode root
= new DefaultMutableTreeNode("Root");

// Creating child nodes


DefaultMutableTreeNode parent1
= new DefaultMutableTreeNode("Parent 1");
DefaultMutableTreeNode child1_1
= new DefaultMutableTreeNode("Child 1.1");
DefaultMutableTreeNode child1_2
= new DefaultMutableTreeNode("Child 1.2");

// Adding child nodes to the parent1


parent1.add(child1_1);
parent1.add(child1_2);

// Creating another set of child nodes


DefaultMutableTreeNode parent2
= new DefaultMutableTreeNode("Parent 2");
DefaultMutableTreeNode child2_1
= new DefaultMutableTreeNode("Child 2.1");
DefaultMutableTreeNode child2_2
= new DefaultMutableTreeNode("Child 2.2");

// Adding child nodes to the parent2


parent2.add(child2_1);
parent2.add(child2_2);

// Adding parent nodes to the root


root.add(parent1);
root.add(parent2);
// Creating the JTree
JTree tree = new JTree(root);

// Adding the JTree to the frame within a scroll


// pane
frame.add(new JScrollPane(tree));

// Setting frame properties


frame.setSize(400, 400);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Output:

JTable

The JTable class is a part of Java Swing Package and is generally used to display or edit two-
dimensional data that is having both rows and columns. It is similar to a spreadsheet. This
arranges data in a tabular form.

Constructors in JTable:
1. JTable(): A table is created with empty cells.
2. JTable(int rows, int cols): Creates a table of size rows * cols.
3. JTable(Object[][] data, Object []Column): A table is created with the specified name
where []Column defines the column names.
Functions in JTable:
1. addColumn(TableColumn []column) : adds a column at the end of the JTable.
2. clearSelection() : Selects all the selected rows and columns.
3. editCellAt(int row, int col) : edits the intersecting cell of the column number col and row
number row programmatically, if the given indices are valid and the corresponding cell is
editable.
4. setValueAt(Object value, int row, int col) : Sets the cell value as ‘value’ for the position
row, col in the JTable.

Example Of JTable
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class JTableExamples {


JFrame f;
// Table
JTable j;

// Constructor
JTableExamples()
{
// Frame initialization
f = new JFrame();

// Frame Title
f.setTitle("JTable Example");

// Data to be displayed in the JTable


String[][] data = {
{ "Kundan Kumar Jha", "4031", "CSE" },
{ "Anand Jha", "6014", "IT" }
};

// Column Names
String[] columnNames = { "Name", "Roll Number", "Department" };

// Initializing the JTable


j = new JTable(data, columnNames);
j.setBounds(30, 40, 200, 300);

// adding it to JScrollPane
JScrollPane sp = new JScrollPane(j);
f.add(sp);
// Frame Size
f.setSize(500, 200);
// Frame Visible = true
f.setVisible(true);
}

// Driver method
public static void main(String[] args)
{
new JTableExamples();
}

Output:

JProgressBar

JProgressBar is a part of Java Swing package. JProgressBar visually displays the progress of
some specified task. JProgressBar shows the percentage of completion of specified task.The
progress bar fills up as the task reaches it completion. In addition to show the percentage of
completion of task, it can also display some text.

Constructors of JProgressBar :

1. JProgressBar() : creates an progress bar with no text on it;


2. JProgressBar(int orientation) : creates an progress bar with a specified orientation. if
SwingConstants.VERTICAL is passed as argument a vertical progress bar is created, if
SwingConstants.HORIZONTAL is passed as argument a horizontal progress bar is created.
3. JProgressBar(int min, int max) : creates an progress bar with specified minimum and
maximum value.
4. JProgressBar(int orientation, int min, int max) : creates an progress bar with specified
minimum and maximum value and a specified orientation.if SwingConstants.VERTICAL
is passed as argument a vertical progress bar is created, if SwingConstants.HORIZONTAL
is passed as argument a horizontal progress bar is created.
Commonly used methods of JProgressBar are :

1. int getMaximum() : returns the progress bar’s maximum value.


2. int getMinimum() : returns the progress bar’s minimum value.
3. String getString() : get the progress bar’s string representation of current value.
4. void setMaximum(int n) : sets the progress bar’s maximum value to the value n.
5. void setMinimum(int n) : sets the progress bar’s minimum value to the value n.
6. void setValue(int n) : set Progress bar’s current value to the value n.
7. void setString(String s) : set the value of the progress String to the String s.
1. Program to create a simple progress bar

// Java Program to create a


// simple progress bar
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class progress extends JFrame {

// create a frame
static JFrame f;

static JProgressBar b;

public static void main()


{

// create a frame
f = new JFrame("ProgressBar demo");

// create a panel
JPanel p = new JPanel();

// create a progressbar
b = new JProgressBar();

// set initial value


b.setValue(0);

b.setStringPainted(true);

// add progressbar
p.add(b);

// add panel
f.add(p);
// set the size of the frame
f.setSize(500, 500);
f.setVisible(true);

fill();
}

// function to increase progress


public static void fill()
{
int i = 0;
try {
while (i <= 100) {
// fill the menu bar
b.setValue(i + 10);

// delay the thread


Thread.sleep(1000);
i += 20;
}
}
catch (Exception e) {
}
}
}
OUTPUT :
JToolTip
We can add tooltip text to almost all the components of Java Swing by using the following
method setToolTipText(String s). This method sets the tooltip of the component to the
specified string s. When the cursor enters the boundary of that component a popup appears and
text is displayed.
Methods used:
1. getToolTipText() : returns the tooltip text for that component .
2. setToolTipText(String s) : sets the tooltip text for the component .
3. getToolTipText(MouseEvent e): returns the same value returned by getToolTipText().
Multi-part components such as JTabbedPane, JTable, and JTree override this method to
return a string associated with the mouse event location.
4. getToolTipLocation(MouseEvent e) : Returns the location (in the receiving component’s
coordinate system) where the upper left corner of the component’s tool tip appears.
// java Program to create a textarea and single line tool tip text to it
import javax.swing.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame {
// frame
static JFrame f;
// text areas
static JTextArea t1;
// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("frame");
// create a object
solve s = new solve();
// create a panel
JPanel p = new JPanel();
// create a text area
t1 = new JTextArea(20, 20);
// set tooltip text
t1.setToolTipText("this is a text Area");
// add text area
p.add(t1);
// add panel
f.add(p);
// set the size of frame
f.setSize(300, 300);
f.show();
}
}

You might also like