Вы находитесь на странице: 1из 79

Java Swing

After learning AWT, lets now see what's Swing? Well, Swing is important to develop Java programs with a graphical user interface
(GUI). There are many components which are used for the building of GUI in Swing. The Swing Toolkit consists of many
components for the building of GUI. These components are also helpful in providing interactivity to Java applications.Following
are components which are included in Swing toolkit:
list controls
buttons
labels
tree controls
table controls
All AWT flexible components can be handled by the Java Swing. Swing toolkit contains far more components than the simple
component toolkit. It is unique to any other toolkit in the way that it supports integrated internationalization, a highly
customizable text package, rich undo support etc. Not only this you can also create your own look and feel using Swing other
than the ones that are supported by it. The customized look and feel can be created usingSynth which is specially designed. Not to
forget that Swing also contains the basic user interface such as customizable painting, event handling, drag and drop etc.
The Java Foundation Classes (JFC) which supports many more features important to a GUI program comprises ofSwing as well.
The features which are supported by Java Foundation Classes (JFC)are the ability to create a program that can work in
different languages,the ability to add rich graphics functionality etc.
The features which are provided by Swing and the Java Foundation Classes are as follows:

Swing GUI Components
There are several components contained in Swing toolkit such as check boxes, buttons, tables, text etc. Some very simple
components also provide sophisticated functionality. For instance, text fields provide formatted text input or password field
behavior. Furthermore, the file browsers and dialogs can be used according to one's need and can even be customized.


Java 2D API
Programming has become more interactive with Java 2D API. You can add images, figures, animation to your GUI and even pass
visual information with the help of Java 2D API. You can easily use 2D within Swing components such as drop shadows since
Swing is built on 2D package.

Pluggable Look and Feel
The Java Swing supports the plugging between the look and feel features. The look and feel that means the dramatically
changing in the component like JFrame, JWindow, JDialog etc. for viewing it into the several types of window. You can create your
own look and feel using Synth package. There are many of existing look and feels which are available to Swing programs provided
byGTK+ look and feel. Moreover, the look and feel of the platform can be specified by the program while running and also to use
Java look and feel can be specified by it.
The pluggable look and feel indicates that the whole look of the GUI element can be changed i.e. both the visual
representation andbehavior of a GUI can be changed at the time of display of the component. The new object which is created by
the Swing application i.e. a new button by instantiating the JButton class already knows that how to react to mouse movements and
mouse clicks. Some tasks are only performed by certain specialized classes like mouse handlingthat is why there is no need to
change the code to modify the look. However, if the code is contained by the button itself that creates its visual representation
then this code would be required to be changed to modify the look and feel of the GUI. Due to this reason only Swing provides
custom look and feel.
Lets tweak the example below that shows how pluggable look and feel affects programming.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class SwingDemo extends JFrame{
JLabel msgLabel;

public SwingDemo(){
super("Swing");
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent ae){
msgLabel.setText(((JButton)ae.getSource()).getText());
}
};

JButton button;
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(new TitledBorder("Click a button"));
for (int i = 0; i < 3; i++){
button = new JButton("Button " + (i + 1));
button.addActionListener(al);
buttonPanel.add(button);
}

JPanel p = new JPanel(new BorderLayout());
p.setBorder(new EmptyBorder(8, 8, 8, 8));
msgLabel = new JLabel("No button pressed!");
p.add(msgLabel, BorderLayout.NORTH);
p.add(buttonPanel, BorderLayout.CENTER);
setContentPane(p);
pack();
setVisible(true);
}

public static void main(String[] args){
new SwingDemo();
}
}
Output of the program:
C:\newprgrm>javac
SwingDemo.java

C:\newprgrm>java SwingDemo




Data Transfer

Swing supports data transfer through drag and drop, copy-paste, cut-paste etc.Data transfer works between Swing
components within an application and between Java and native applications. The ability of data transfer is beneficial to programs
between Java applications, between components etc.
There are two ways to transfer data. These are:

1. The diagram below displays the Drag and drop (DnD) functionality of Swing.

2. The diagram below displays the cut/copy and pastefunctionality of Swing. That is the clipboard transfer via cut/copy and paste.
The path of the data is shown by the arrows.


To be more precise, first of all the bundling of data takes place into a package known as Transferable to beginData Transfer.
Then the data gets extracted by an object i.e. TransferHandler from the Transferable which is provided by the component.


Internationalization

Swing in Java also supports the feature of Internationalization.The developers can build applications by which the users can
interact worldwide in different languages. They can also create applications that can accept input in languages having different
characters such as French, Spanish, Japanese, etc.
An automatic support is provided by the Swing's layout managers required by the UI. That is Swing's layout manager let the UI
to appear from right to left in a locale. Hence to let the UI work for left to right and right to left and also to take care of the size of
components that change on localization, you need to code the UI only once.
Lets see how to internationalize the program given below.
import java.util.*;
public class InternationalizationDemo {
public static void main(String[] args) {
System.out.println("The text displayed is specific to locale"+"
("+Locale.getDefault().getDisplayLanguage() +", "+
Locale.getDefault()
.getDisplayCountry () + ").\n");
System.out.println("Hello, how are you?");
System.out.println("Thanks to visit."); }
}
Now you want this program to get internationalized so that it may response according to the specific region and country i.e. locale
(Remember no code changes are required for different locale). Just follow these steps:

1. Create Properties Files:

Create ?. properties? file containing a set of key and value pair. Remember to keep the keys same in all the files and provide
values according to the locale in different files.

Properties Files Naming Convention:

Creating a default properties file is a good practice, which is available to the program by default. You can give any name to this file
but remember to use the same name that your ResourceBundle uses (MessageBundle.properties file in our example). While
naming other properties files follow the syntax:
PropertiesFileNameUsedInResourceBundle_languageCode_countryCode.properties
Let?s create these files.

Default file:
Write down the following lines in a plain-text file (Default version) and save it asMessagesBundle.properties:
localeInfo = The text displayed is specific to locale
welcome = Hello, how are you?
sayThanks = Thanks to visit.

Other properties files:
Write down the following lines in a plain-text file (for the French version) and save it as MessagesBundle_fr_FR.properties:

localeInfo = Le texte affich est spcifique la scne
welcome = Bonjour, comment allez-vous ?
sayThanks = Merci pour visiter.
Write down the following lines in a plain-text file (for the Spanish version) and save it asMessagesBundle_es_ES.properties:

localeInfo = El texto mostrado es especfico al lugar
welcome = Hola, Cmo est usted?.
sayThanks = Gracias a visita.

Notice that ?localeInfo?, ?welcome?, ?sayThanks? keys are same in English, French, Spanish files and values are replaced with
the converted value of the particular language.
2. Remove hard coded text from the source file:
Our next step is to remove the hard coded text from our source file and use the keys of properties file. These values are picked up
at the run time from the properties file according to the locale provided to the program. So this source file doesn?t require to be
compiled while dealing with the different locales. You can be sure of this fact viewing the code modified below:
import java.util.*;

public class InternationalizationDemo {
public static void main(String[] args) {
String language;
String country;
Locale locale;
ResourceBundle rb;

if (args.length != 2) {
language = new String("en");
country = new String("US");
}
else {
language = new String(args[0]);
country = new String(args[1]);
}
locale = new Locale(language, country);
rb = ResourceBundle.getBundle("MessagesBundle", locale);
System.out.println(rb.getString("localeInfo") + " ( " +
locale.getDisplayLanguage() + "," + locale.getDisplayCountry() + ").\n");
System.out.println(rb.getString("welcome"));
System.out.println(rb.getString("sayThanks"));
}
}
When the set of language code and country code is provided at run time, the output is shown according to that particular locale. For
example, in the output below, for ?es? and ?ES? the output is displayed in Spanish language. The text displayed is fetched from
MessageBundle_es_ES.properties file. If ?fr? and ?FR? codes are provided at run time then values are displayed in French
language. Now this text is fetched from MessageBundle_fr_FR.properties file. Here we are not changing and compiling the
source code to work for different locale because the program references the keys, not the values.
Output of the Program:
C:\Program Files\Java\jdk1.6.0_01\bin>javac
InternationalizationDemo.java

C:\Program Files\Java\jdk1.6.0_01\bin>java
InternationalizationDemo
The text displayed is specific to locale (English,United States).

Hello, how are you?
Thanks to visit.

C:\Program Files\Java\jdk1.6.0_01\bin>java
InternationalizationDemo fr FR
Le texte affich est spcifique la scne (French,France).

Bonjour, comment allez-vous ?
Merci pour visiter.

C:\Program Files\Java\jdk1.6.0_01\bin>java
InternationalizationDemo es ES
El texto mostrado es especfico al lugar. (Spanish,Spain).

Hola, Cmo est usted?.
Gracias a visita.


Localization

To translate a text in to a particular language is know as Localization. It is a process by which we can change a text to a different
language and also we can add some locale-specific components. Swing supports localization in the way that when we localize an
application to a particular language and run it in that specific locale then Swing pulls up the localized strings from the resource
bundle. After this, the component gets resized by the layout manager. The previous example demonstrates how to localize an
application.
Undo Framework API
To perform undo and redo, the developers can use Swing's undo framework.There are number of actions related to undo and
redo which are supported by Swing. Moreover, it can easily be used with any other application such as if you want to undo the add
and remove elements from a table, you can easily do that.

Flexible Deployment Support
Swing also supports the Flexible Deployment of the program. For instance, you can create an applet to run your program within a
browser window using Java Plug-in. Several browsers are supported by it like Firefox, Internet Explorer etc. Moreover, a program
can also be launched from a browser itself with Java Web Start and can also be run outside of browser as a standard desktop
application.
Integrating with the Desktop
Now the Java applications can be integrated seamlessly with the desktop. This has become possible with the introduction of the
Desktop API in version 6 of the Java Platform, Standard Edition (Java SE). There are three types of integration which are
supported. These are:
The host system's default email client can be launched.
Various functionality of applications like edit, print, open can be launched.
The host system's default browser can be launched with a specific Uniform Resource Identifier (URI).


What is Java Swing?

Here, you will know about the Java swing. The Java Swing provides the multiple platform independent APIs interfaces for interacting
between the users and GUIs components. All Java Swing classes imports form the import javax.swing.*; package. Java provides an
interactive features for design the GUIs toolkit or components like: labels, buttons, text boxes, checkboxes, combo boxes, panels
and sliders etc. All AWT flexible components can be handled by the Java Swing. The Java Swing supports the plugging between the
look and feel features. The look and feel that means the dramatically changing in the component like JFrame, JWindow, JDialog etc.
for viewing it into the several types of window.
Here the following APIs interfaces and classes are available:
The following interfaces and it's descriptions to be used by the Java swing.
Interfaces Descriptions
Action
This interface performed the action with the ActionListener where the multiple
controls are used for same purposes.
BoundedRangeModel This interface defines the data model of components like: sliders and
progressBars.
ButtonModel It defines the state model for the buttons like: radio buttons, check boxes etc.
CellEditor This interface used by the developer for creating the new editor and it has the
new components implement interfaces. The CellEditor implements the
wrapper based approach.
ComboBoxEditor In this interface, the editor component used to JComboBox components.
ComboBoxModel This interface represents the data model in a list model with the selected items.
DesktopManager This interface has JDesktopPane object. The JInternalFrame implements in
the JDesktopPane with the help of DesktopManager.
Icon This interface used to graphical representation of the components. It has fixed
size picture.
JComboBox.KeySelectionManager This interface has KeySelectionManager and used for the combo box data
model.
ListCellRenderer This interface used for paint the cell in the list with the help of "rubber stamps" .
ListModel This interface used for JList components method. It gets the value of each cell
of list.
ListSelectionModel This interface indicates the components, which are stable or not.
MenuElement This interface used where the any components are implements in the menu.
MutableComboBoxModel This interface extends from the ComboBoxModel. It is a mutable version of
ComboBoxModel.
Renderer It defines the requirements of an object for displaying the values.
RootPaneContainer This interface uses the RootPane properties and it has the components like:
JFrame, JInternalFrame and JWindow etc.
Scrollable This interface provides the scrolling to show the large amount of data with the
help of JScrollPane.
ScrollPaneConstants This interface used for JScrollPane components.
SingleSelectionModel This interface used to select the one index in a model.
SwingConstants You can set the components on the screen to own requirements.
UIDefaults.ActiveValue It constructs the DefaultListCellRenderer.
UIDefaults.LazyValue This enables one to store an entry in the default table. The entered value is not
constructed until first time is a real value is created through it using
LazyValue.createValue() method.
WindowConstants This interface has two methods setDefaultCloseOperation and
getDefaultCloseOperation and provides the window close opration.
The following classes and it's descriptions to be used by the Java swing.
Classes Descriptions
AbstractAction This class handles the any types of action and provides JFC Action interface.
AbstractButton This class defines the nature of buttons and menu items.
AbstractCellEditor It provides a list and contents of the data model.
AbstractListModel This class defines the data model which provides the list with its contents.
ActionMap This class works with InputMap and performs any action when the key is
pressed.
BorderFactory This class extends from Object and creates the Border instance in the factory.
Box
It provides the fixed spaces between two components and uses the
BoxLayout object of the layout manager.
Box.Filler This class participates in the Layout and uses the lightweight components.
BoxLayout
This class uses the arranging the multiple components either horizontally or
vertically. The Box container uses this class.
ButtonGroup This class used to create the multiple buttons in a ButtonGroup object.
CellRandererPane This class used to insert the components like: JList, JTable and JTree.
ComponentInputMap This class has ComponentInputMap constructor and creates the
components with the help of InpuMap.
DebugGraphics It extends from the Graphics and used to debug the graphics
DefaultBoundedRangeModel This class provides the implementation of default BoundedRangeModel.
DefaultButtonModel This class implements the generic ButtonModel.
DefaultCellEditor It implements the TableCellEditor and TreeCellEditor for the table and tree
cells.
DefaultComboBoxModel It provides the default model for combo boxes.
DefaultDesktopManager
It implements the DesktopManager. The DesktopManager has the
JInternalFrame for creating the internal fame in a frame.
DefaultFocusManager It provides the implementing the FocusManager.
DefaultListCellRanderer It implements the default ListCellRanderer.
DefaultListCellRanderer.UIResource This extends the DefaultListCellRanderer and implementing in the
UIResource.
DefaultListModel It extends the AbstractListModel and implementing the java.util.Vector.
DefaultListSelectionModel This class used for select the list in a data model.
DefaultSingleSelectionModel This class provides the default SingleSelectionModel.
FocusManager It handles all focus like: gainedFocus and lostFocus.
GrayFilter It extends the RGBImageFilter and used for disabling the image through the
button.
ImageIcon This class implements the Icon and paints the icons from the images.
InputMap
This class uses the ActionMap to performed the action when you press any
key of keyboard. It bounds data between the input event and an object.
InputVerifier This class helps you when you works with the text fields through the focus.
JApplet This class extends the Applet and implements the Accessible and
RootPaneContainer.
JButton This class extends the AbstractButton and you can create the new button.
JCheckBox This class extends the JToggleButton and implements the check box in
which buttons are selected or deselected.
JCheckBoxMenuItem It extends the JMenuItem and determines the items which is selected or
deselected.
JColorChooser It extends the JComponent and implementing the Accessable. Here, you
choose and manipulate the colors.
JComboBox This class extends the JComboBox. It provides the drop-down list where user
select only one item or value at a time. But combo box is a combination of
multiple text or buttons etc.
JComponent
In java swing, All components are used the JComponent except the top-level
containers like: JFrame, JDialog etc.
JDesktopPane This class extends the JLayeredPane and when you create the object of
JInternalFrame to be maintained in the JDesktopPane. The JDesktopPane
has DesktopManager.
JDialog It extends the Dialog. This class used to create the dialog window and when
you want to create the custom dialog window with the help of JOptionPane
method.
JEditorPane This class extends the JTextComponent. It edits the component by the
EditorKit.
JFileChooser This class provides the facility to choosing the file.
JFrame It extends the Frame and supports the swing components architecture.
JInternalFrame This class extends from the JComponent and provides the facility to
dragging, closing, resizing and menu bar of the internal frame. The
JInternalFrame added into the JDesktopPane.
JInternalFrame.JDesktopIcon It displays the desktop icon and create the instance of JInternalFrame and
iconify.
JLabel This class used to show the small text and image.
JLayeredPane It has JFC/Swing container that can be used to overlap the components to
each other.
JList This class used to create a list where you select the one or more than objects.
JMenu
This class used to create a new menu where you add the JMenuItems. When
you select the item then shows the popup menu items in the JMenuBar.
JMenuBar It used to create a new menu bar where the JMenu objects are added.
JMenuItem This class used to create new menu items in the mebus.
JOptionPane It used to create some different types of dialog box like: message dialog box,
error dialog box etc.
JPanel It extends the JComponent and used to create a new panel.
JPassworkField
It provides the single line text editing. Here, don't available the original
characters but view type indication characters are available.
JPopupMenu
This class used to create a popup menu. It provides small window where the
various types of choices are available.
JPopupMenu.Separator Here the popup menu and the separator are available.
JProgressBar It shows the integer types values in percent within a bounded range to
determine the working process.
JRadioButton It implements the radio button and shows the state of an item selected or
deselected.
JRadioButtonMenuItem It extends the JMenuItem and implements the radio button menu item
JRootPane This class provides the component behind the scenes by JFrame, JWindow,
JDialog etc. for providing the task-orientation and functionality.
JScrollBar
This class used to create a scroll bar. It provides the view content area where
you show the content to scroll this.
JScrollPane It provides the scrollable view components.
JSeparator This class use the separator among the components.
JSlider This class provides a control to represent a numeric value by dragging the
slider.
JSplitPane This class used to divides the two components graphically like: top and
button, left and right.
JTabbedPane This class provides the tab component through which you can switch from
one component to another component regarding to the specific tab button by
clicking on that.
JTable It provides the user interface component and represents the two dimensional
data.
JTextArea It provides the multi line plain text area.
JTextField It provides the facility to editing the text in a single line.
JTextPane This class provides the component like JTexArea for multiple lines text with
more capabalities.
JToggleButton It implements two state button that means selected or deselected.
JToggleButton.ToggleButtonModel It extends the DefaultButtonModel and provides the ToggleButton model.
JToolBar It provides set of command buttons icons that performs the different actions or
controls.
JToolBar.Separator It provides the tool bar separator.
JToolTip It shows the tool tips related to it's components.
JTree It shows the data in a hierarchical way.
JTree.DynamicUtilTreeNode This extends the DefaultMutableTreeNode and create children nodes.
JTree.EmptySelectionModel It does not allows the any selection.
JViewPort It gives you about the underlying information.
JWindow It extends window and shows the any location or area on the desktop. It
couldn't any title bar and window management buttons.
KeyStroke This class controls the key events on the keyboard for the equivalent device.
LayoutFocusTraversalPolicy This class conducts the sorting objects according to their size, type, position
or orientation.
LookAndFeel It provides the dramatically changes in the component like frame related to
the graphics for the application. Through this the application can be done very
efficient and easier.
MenuSelectionManager It has menu selection hierarchy.
OverlayLayout The layout manager arrange the components.
ProgressMonitor This class is used to monitoring the progress of any operation to be done.
ProgressMonitorInputStream This class creates a progress monitor to monitor the progress of reading input
from the input stream. It cleanups all the rights when the stream is closed.
RepaintManager This class manage and override the repaint requests.
ScrollPaneLayout
It implements the LayoutManager and manage the components like: scroll
bar, row header, column header etc.
ScrollPaneLayout.UIResource It extends the ScrollPaneLayout and implements the UIResource.
SizeRequirements It calculates the size and positions of components.
SizeSequence It represents the order list of size and it's positions.
SwingUtilities This class has utilities methods for swing.
Timer Actions perform the predefined rate.
ToolTipManager It manages the all tool tips.
UIDefaults It extends the Hashtable and you set/get the value with the help of
UIManager.
UIDefaults.LazyInputMap This class creates a Input Map through it's createValue() method. The array of
key after binding is passed to the constructor of this. Example of binding of
key is array of pressing key information (e.g. ctrl + c or alt + f).
UIDefaults.ProxyLazyValue This class is used to create a lazy value which is used to delay loading of the
class to create instance for that.
UIManager This class has track of the current look and feel details.
UIManager.LookAndFeelInfo This is the nested class of UIManager class i.e. used for getting information
about all the look and feels installed with the software development kit.
ViewportLayout It implements the LayoutManager and defines the policy for the layout.
The following Exceptions and it's description to be used by the Java swing.
Exception Descriptions
UnsupportedLookAndFeelException
This exception occurred when the look and feel classes are not supported to
user's system.

Creating a Frame : Swing Tutorials

This program shows you how to create a frame in Java Swing Application. The frame in java works like the main window where your
components (controls) are added to develop an application. In the Java Swing, top-level windows are represented by the JFrame
class. Java supports the look and feel and decoration for the frame.
For creating java standalone application you must provide GUI for a user. The most common way of creating a frame is, using single
argument constructor of the JFrame class. The argument of the constructor is the title of the window or frame. Other user interface
are added by constructing and adding it to the container one by one. The frame initially are not visible and to make it visible the
setVisible(true) function is called passing the boolean value true. The close button of the frame by default performs the hide
operation for the JFrame. In this example we have changed this behavior to window close operation by setting the
setDefaultCloseOperation() to EXIT_ON_CLOSE value.
setSize (400, 400):
Above method sets the size of the frame or window to width (400) and height (400) pixels.
setVisible(true):
Above method makes the window visible.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE):
Above code sets the operation of close operation to Exit the application using the System exit method.
Here is the code of the program :
import javax.swing.*;

public class Swing_Create_Frame{
public static void main(String[] args){
JFrame frame = new JFrame("Frame in Java Swing");
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


Setting an Icon for a Frame in Java
In this section, you will learn how to set an icon for the frame in Java Swing.
This program helps us to set the icon (image) on the title bar of the frame. When you open frame or window the icon situated on the
title bar is seen on the taskbar also. For this purposes, various methods as follows has been used:
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("icon_confused.gif"));
Above method sets the icon for the frame or window after getting the image using the Image class method named getImage().
frame.getDefaultToolkit():
This is the method of the Toolkit class which gets the default toolkit.
Here is the code of program:
import javax.swing.*;
import java.awt.*;

public class SettingIconFrame{
public static void main(String[] args){
JFrame frame = new JFrame("Setting an Icon for a frame");
frame.setIconImage(Toolkit.getDefaultToolkit()
.getImage("icon_confused.gif"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}


Show Dialog Box in Java - Swing
Dialogs

Message dialog box is used to display informative messages to the user. In this section we will use JOptionPane class to display the
message Dialog box. Our program display "Click Me" button on the window and when user clicks on it program displays Message
box with "OK" button and message "Roseindia.net".
When you run the program following window will be displayed:

When you click on "Click Me" button, following Message is displayed:

Program description:
JOptionPane Class:
In non-swing application we were using System.inclass for input or output some text or numeric values but now in the swing
application we can use JOptionPane to show the output or show the message. This way of inputting or outputting works very
efficiently in the Swing Applications. The window for showing message for input or output makes your application very innovative.
JOptionPane class is available in the javax.swing.*; package. This class provide various types of message dialog box as follows:
A simple message dialog box which has only one button i.e. "Ok". This type of message dialog box is used only for
showing the appropriate message and user can finish the message dialog box by clicking the "Ok" button.
A message dialog box which has two or three buttons. You can set several values for viewing several message dialog box
as follows:
1.) "Yes" and "No"
2.) "Yes", "No" and "Cancel"
3.) "Ok", and "Cancel"
A input dialog box which contains two buttons "Ok" and "Cancel".
The JOptionPane class has three methods as follows:
showMessageDialog(): First is the showMessageDialog() method which is used to display a simple message.
showInputDialog(): Second is the showInputDialog() method which is used to display a prompt for inputting. This
method returns a String value which is entered by you.
showConfirmDialog(): And the last or third method is the showConfirmDialog() which asks the user for confirmation
(Yes/No) by displaying message. This method return a numeric value either 0 or 1. If you click on the "Yes" button then
the method returns 1 otherwise 0.
How program Works:
This program illustrates you how to show a message dialog box when you click on the button.
showMessageDialog():
This method is used to show a message dialog box which contains some text messages. This is being used with two arguments in
the program where the first argument is the parent object in which the dialog box opens and another is the message which has to be
shown.
Here is the code of the program:
import javax.swing.*;
import java.awt.event.*;

public class ShowDialogBox{
JFrame frame;
public static void main(String[] args){
ShowDialogBox db = new ShowDialogBox();
}

public ShowDialogBox(){
frame = new JFrame("Show Message Dialog");
JButton button = new JButton("Click Me");
button.addActionListener(new MyAction());
frame.add(button);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(frame,"Roseindia.net");
}
}
}
Show Message and Confirm Dialog Box -
Swing Dialogs
This section show you how to display several types of message box. There are three types of message dialog box that you can use
in your swing applications, example of each type of dialog boxes are provided here. When your run the program, it will display a
frame with three buttons. Once you click on the first button then the simple message box will open which holds only "Ok" button as
shown below:

If you click on the second button then the confirm dialog box will open which asks for "Ok" and "Cancel".

If you click on the "Ok" button then a message dialog box will open with message "You clicked on "Ok" button" like this

otherwise message dialog box will open with text "You clicked on "Cancel" button like this

If you click on the third button from the main window or frame then a confirm message dialog box will open with three button i.e. the
"Yes", "No" and "Cancel" like the following image:

For this purposes two methods have been used:
showMessageDialog():
Above method shows a simple message dialog box which holds only one button i.e. "Ok" button. This method takes four
arguments in which, first is the parent object name, second is the message as string, third is the title of the message
dialog box as string and the last is the type of the message dialog box.
showConfirmDialog():
Above method asks from the user by displaying a message dialog box which contains more than one button. Depending
on the parameter passed it can be "Ok" and "Cancel" or "Yes", "No" and "Cancel". This method returns the integer
value.
Here is the code of the program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ShowMessageDialog{
JButton button;
public static void main(String[] args){
ShowMessageDialog md = new ShowMessageDialog();
}

public ShowMessageDialog(){
JFrame frame = new JFrame("Message Dialog Box");
button = new JButton("Show simple message dialog box");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(button);
button = new JButton("Show \"Ok/Cancel\" message
dialog box");
button.addActionListener(new MyAction());
panel.add(button);
button = new JButton("Show \"Yes/No/Cancel\" dialog box");
button.addActionListener(new MyAction());
panel.add(button);
frame.add(panel);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent ae){
String str = ae.getActionCommand();
if(str.equals("Show simple message dialog box")){
JOptionPane.showMessageDialog(null, "This is the simple message
dialog box.", "Roseindia.net", 1);
}
else if(str.equals("Show \"Ok/Cancel\" message dialog box")){
if(JOptionPane.showConfirmDialog(null, "This is the \"Ok/Cancel\"
message dialog box.", "Roseindia.net", JOptionPane.OK_CANCEL_OPTION) == 0)
JOptionPane.showMessageDialog(null, "You clicked on \"Ok\" button",
"Roseindia.net", 1);
else
JOptionPane.showMessageDialog(null, "You clicked on \"Cancel\" button",
"Roseindia.net", 1);
}
else if(str.equals("Show \"Yes/No/Cancel\" dialog box")){
JOptionPane.showConfirmDialog(null, "This is the \"Yes/No/Cancel\"
message dialog box.");
}
}
}
}


Swing Input Dialog Box Example - Swing
Dialogs



Input dialog box is very important and interactive feature of Java Swing. You have been using the System.in for inputting anything
from user. Java Swing provides the facility to input any thing (whether the text or the numeric values) in a normal window i.e. the
Input Dialog Box. The input dialog box contains two buttons, first is the "Ok" button and another is the "Cancel" button like this:

When you run the given program, this shows a button labeled by "Show Input Dialog Box" on the frame. If you click on the button
then a input dialog box will open. If you click on the "Ok" button of the input dialog button then a message dialog box is seen which
has the message "You entered the text : entered_text" otherwise it will display a message dialog box that has the message "You
pressed cancel button.".
Here is the code of the program:
import javax.swing.*;
import java.awt.event.*;

public class ShowInputDialog{
public static void main(String[] args){
JFrame frame = new JFrame("Input Dialog Box Frame");
JButton button = new JButton("Show Input Dialog Box");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String str = JOptionPane.showInputDialog(null, "Enter some text : ",
"Roseindia.net", 1);
if(str != null)
JOptionPane.showMessageDialog(null, "You entered the text : " + str,
"Roseindia.net", 1);
else
JOptionPane.showMessageDialog(null, "You pressed cancel button.",
"Roseindia.net", 1);
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}




Changing the Label of a JButton
Component in Java



This section illustrates you how to change the label of a button in java swing. JButton is the component of javax.swing.*;package.
The following program helps you to change the label of the button. In this program, the label of the button is changed from "Click
Me" to "Roseindia.net"and vice versa whenever you click on the button as shown below:
Before:

After:

In this program, addActionListener() method has been added to the button to register the action listener and then if you click on the
button, the generated action event is captured in the actionPerformed(ActionEvent e) method. In theactionPerformed(ActionEvent
e){ we check the label of the button. If the label of the button is "Roseindia.net", it will change the button label to "Click Me"
otherwise it will change the label to "Roseindia.net".
setText(String):
Above method sets the label of the button.
Here is the code of the program:
import javax.swing.*;
import java.awt.event.*;

public class ChangeButtonLabel{
JButton button;
public static void main(String[] args){
ChangeButtonLabel cl = new ChangeButtonLabel();
}

public ChangeButtonLabel(){
JFrame frame = new JFrame("Change JButton Lebel");
button = new JButton("Click Me");
button.addActionListener(new MyAction());
frame.add(button);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e){
String text = (String)e.getActionCommand();
if (text.equals("Click Me")){
button.setText("Roseindia.net");
}
else{
button.setText("Click Me");
}
}
}
}


Setting Multi-Line label on the Button

This section shows you how to set the multi line label on the button in Java Swing Applications.
This program uses html class from javax.swing.text.html*; package and then breaks the text label of the button into two lines. If you
run the program it will look like following image:

HTML:
This is the class from the javax.swing.text.html.*;package of Java. This class provides the facility to use the html tags in java
application for texts. There are <html></html> tag and <br> tag have been used in this program. Tags of html are used with the
string which is the label of the button.
Here is the code of the program:
import javax.swing.*;
import javax.swing.text.html.*;
import java.awt.*;

public class MultilineLabelButton{
public static void main(String[] args){
JFrame frame = new JFrame("Multiline Label for
Button");
String lbl = "<html>" + "This label" + "<br>" + "is in
two lines"
+ "</html>";
Panel panel = new Panel();
JButton button = new JButton(lbl);
panel.add(button);
// frame.add(button);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Setting icon on the button in Java

This section illustrates you how to show the icon on the button in Java Swing.
This program sets the icon on the button in Java Swing.
Following is the output of the program:

Code description:
setIcon(Icon):
Above method sets the specified Icon on the button.
ImagIcon(String image_name):
Above code creates an object of image.
Here is the code of the program:
import javax.swing.*;
import java.awt.*;

public class IconButton{
public static void main(String[] args){
JFrame frame = new JFrame("Icon on button");
JButton button = new JButton("Roseindia.net");
Icon imgicon = new ImageIcon("icon_confused.gif");
JPanel panel = new JPanel();
button.setIcon(imgicon);
panel.add(button);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


Making a Frame Non Resizable in Java

This program illustrates you how to make a frame non resizable. It means, disabling the maximize button of the frame.
The setResizable() method has been used to make the frame resizable or not. If you pass the boolean value false to
thesetResizable() method then the frame will be non-resizable otherwise frame will be resizable. The setResizable() is the method
of the JFrame class which takes a boolean valued argument (true or false).
Screen shot for the result of the program:

Here is the code of the program :
import javax.swing.*;

public class SwingFrameNonResizable{
public static void main(String[] args){
JFrame frame = new JFrame("Non Resizable Frame");
frame.setResizable(false);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


Remove Minimize and Maximize Button
of Frame in Java
In this section we are going to learn the coding methods to remove the minimize and maximize button from the title bar of a frame.
We know that the title bar contains icon, minimize, maximize and close buttons. The following program provides the facility for doing
it. That means, the frame or window displays on the screen without minimize and maximize button but it has only the icon and close
button on the title bar that helps us at the time of closing the frame or window. See more information below.
Description of program:
This program displays a frame under the dialog box that hasn't the minimize and maximize button. It contains only a close button
that performs only closing operation that means our window closes when you click on it. So follow the program for better
understanding and you will find that the title bar has only close botton.
Here is the code of program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RemoveMaxAndMinButton extends JDialog{
public RemoveMaxAndMinButton(JFrame frame, String str){
super(frame,str);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent evt){
System.exit(0);
}
});
}
public static void main(String[] args){
try{
RemoveMaxAndMinButton frame = new RemoveMaxAndMinButton(new JFrame(),
"Remove the Minimize and Maximize button from the Title Bar");
JPanel panel = new JPanel();
panel.setSize(200,200);
JLabel lbl = new JLabel("RoseIndia.Net");
panel.add(lbl);
frame.add(panel);
frame.setSize(400, 400);
frame.setVisible(true);
}
catch(IllegalArgumentException e){
System.exit(0);
}
}
}
Output of program:


Removing the Title Bar of a Frame

In this section, you will learn how to remove the title bar of a frame or window in java. That means show the frame or window without
title bar. The title bar of the frame or window which holds the icon, minimize button, maximize button and close button with the title of
the frame. Following is the image of the frame without title bar:

Code Description:
setUndecorated(boolean):
This is the method of the JFrame class that sets the frame decoration. It takes a boolean typed value either true or false.If you
passes the true then the frame will undecorated means the frame will not show the title bar and if you passes the false then the
frame will show the title bar.
Here is the code of the program:
import javax.swing.*;

public class RemoveTitleFrame{
public static void main(String[] args) {
JFrame frame = new JFrame("Removing the Title Bar of a Frame");
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}

Setting Bounds for a maximized frame
In this section, you will learn how to set the bounds for a maximized frame. This means to fix the size for the frame after maximizing
it.
This program sets the bounds for the maximized frame using setMaximizedBounds()method of the JFrame class. There has been
shown the images below for the illustration:




Restored Frame:

Maximized Frame:

Code description:
setMaximizedBounds():
This is the method of the JFrame class sets the bounds for a maximized frame. The method takes the object of Rectangle class to
set the size of frame. Constructor of the Ractangle class takes four argument in sequence: row of the screen, column of the screen,
width of the frame and last is the height of the frame.
Here is the code of the program:
import java.awt.*;
import javax.swing.*;

public class SwingSetBounds{
public static void main(String[] args){
JFrame frame = new JFrame();
Rectangle bounds = new Rectangle(0, 0, 500, 500);
frame.setMaximizedBounds(bounds);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


Iconifying and Maximizing a frame in
Java

In this section, you will learn about the Iconifying and maximizing a frame in java. Iconifying means to show a frame in minimized
form. This program displays a frame in both forms. By default the frame will be in the minimized form. Following is the image of the
frame which has to be minimized or maximized:

Code Description:
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG):
The setWindowDecorationStyle() is the method of the JRootPane class which sets the window decoration type using the constant
property PLAIN_DIALOG of the JRootPane class.
setExtendedState():
It sets the state of window to minimize and maximize. It uses the constant field of the JFrame class.
MAXIMIZED_BOTH
This state is used to maximize the frame horizontal and vertical.
ICONIFIED
This state checks whether the frame is minimized or not.
Here is the code of program:
import javax.swing.*;

public class IconifyAndMaximizeFrm{
public static void main(String[] args){
JFrame frame = new JFrame("Iconifying and Maximizing a Frame");
frame.setUndecorated(false);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH); //Maximizing the frame
frame.setExtendedState(JFrame.ICONIFIED | frame.getExtendedState());
//Minimizing or Iconifing the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}


Making a Component Draggable in Java
In this section, you will learn how to make a component draggable in java. This program provides the drag and drop feature from
one component to another. This program shows a text box and a label on the frame. When you drag the label and drop to the text
box then the text of the label is copied to the text box. For the pictorial representation of the application result is given as follows:

Code Description:
There are several APIs has been used to make the component draggable in the program. These are explained as follows:
TransferHandler:
This is the class of the javax.swing.*; package. This is used to transfer the transferable swing component from on the another. Both
components should be the swing component. This class is helpful to copy from one component to another via clipboard.
setTransferHandler():
This is the method of the TransferHandler class which makes the component able to transfer the specified part of the component in
the TransferHandler() as parameter which specifies the the property of the component which has to be dragged and dropped. This
program specifies the text of the label to be dragged and drop to the text box using the string "text".
MouseListener:
This is the interface which receives the different mouse events. Mouse events can be like: pressing or releasing the mouse, click,
enter or exit the mouse etc. are handled through the MouseEvent generated by the MouseListener interface. This program uses the
instance of the MouseListener.
exportAsDrag():
This is the method of the TransferHandler class which initiates the component to drag and drop from one to another swing
component. This method takes three arguments like: JComponent, Active event, and another is the Action which has to be done.
Here, the constant property COPY of the TransferHandlerclass has been used to copy the text from the label to the text box.
Here is the code of the program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingDragDrop{
JTextField txtField;
JLabel lbl;
public static void main(String[] args){
SwingDragDrop sdd = new SwingDragDrop();
}

public SwingDragDrop(){
JFrame frame = new JFrame("Drag Drop Demo");
txtField = new JTextField(20);
lbl = new JLabel("This is the text for drag and drop.");
lbl.setTransferHandler(new TransferHandler("text"));
MouseListener ml = new MouseAdapter(){
public void mousePressed(MouseEvent e){
JComponent jc = (JComponent)e.getSource();
TransferHandler th = jc.getTransferHandler();
th.exportAsDrag(jc, e, TransferHandler.COPY);
}
};
lbl.addMouseListener(ml);
JPanel panel = new JPanel();
panel.add(txtField);
frame.add(lbl, BorderLayout.CENTER);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}
}

Create a ToolBar in Java

In this section, you will learn how to create toolbar in java. Swing provides a most important feature for creating an interactive
component. Toolbar is a area which is situated inside the main window of any applications on top. Tool Bar contains multiple
command buttons for shortcuts. The toolbar has been arranged horizontal in this program but, if you want to make it vertically, you
can do so. Pictorial representation is given below:


Here, you will see a simple toolbar, Which have three command buttons like: cut, copy and paste with small images. For showing
these three buttons on the toolbar of the frame various APIs as follows have been used:
JToolBar():
This is the constructor of the JTooBar class which has been used to create a new toolbar.
JToolBar.HORIZONTAL
This is the constant field of the JToolBarclass which support to situating the Tool Bar horizontal on the frame.
Here is the code of program:
import javax.swing.*;
import java.awt.*;

public class CreateToolbar{
public static void main(String[] args) {
JFrame frame = new JFrame("Create a toolbar Which have three
buttons Such as: Cut, Copy, Paste");
JToolBar toolbar = new JToolBar("Toolbar", JToolBar.HORIZONTAL);
JButton cutbutton = new JButton(new ImageIcon("cut.gif"));
toolbar.add(cutbutton);
JButton copybutton = new JButton(new ImageIcon("copy.gif"));
toolbar.add(copybutton);
JButton pastebutton = new JButton(new ImageIcon("paste.gif"));
toolbar.add(pastebutton);
frame.getContentPane().add(toolbar,BorderLayout.NORTH);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,400);
frame.setVisible(true);
}
}


Convert Image Formats

In this example we are converting image of any format into jpg format.
Import java.io.* package and class javax.imageio.ImageIO and java.awt.BufferedImage. The package java.io.* is used for input
and output operations through data streams, serialization and the file system. Classes ImageReader and ImagrWriter inherit the
static methods from the class javax.imageio..ImageIO for reading and writing the images respectively. The class
java.awt.BufferedImage extends Image class and implements WritableRenderedImage interface. The class BufferedImage is
used to access an image.
The methods used in this example are:
write(RenderedImage im, String formatName, File output): This method is used to write an image. This method takes three
parameters first one is Renderedimage, second is format in which the image is to be converted and last is name of the file on which
the image is to be writen. The format name may be gif, jpg, png etc.

read(File input) : This is used to read an image.

Code Description:
This example reads the image name passed at the command prompt for converting the image into the jpg format. In this example
we are reading the image from system by using read() method of ImageIO class. We are using write() method for conversion of an
image of any format into the jpg format.

Here is the code of the program :
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class GIFToJPG
{
public static void main(String a[]){
try{
System.out.println("Enter image name\n");
BufferedReader bf=new BufferedReader(new
InputStreamReader(System.in));
String imageName=bf.readLine();
File input = new File(imageName);
BufferedImage image = ImageIO.read(input);
System.out.println("Enter the output image
name(.jpg):\n");
String imageName1=bf.readLine();
File output = new File(imageName1);
ImageIO.write(image, "jpg", output);
System.out.println("Your image has been
converted successfully");
}catch(FileNotFoundException e){
System.out.println("Error:"+e.getMessage());
}catch(IOException e)
{
System.out.println("Error:"+e.getMessage());
}
catch(Exception e){
System.out.println(e.getMessage());
}

}
}
Input on DOS Prompts :
C:\image>javac GIFToJPG.java
C:\image>java GIFToJPG
Enter image name
rajeshxml2.gif
Enter the output image name(.jpg):
raju.jpg
Your image has been converted
successfully
Input image:rajeshxml2.gif

Output of The Example:raju.jpg



Display Image in Java

This example takes an image from the system and displays it on a frame using ImageIO class. User enters the name of the image
using the command prompt and then the program displays the same image on the frame. The image is read from the system by
using ImageIO.read(File file) method.
The methods used in this example are:.
drawImage(Image img,int x,int y,ImageObserver observer): This method is used to draw an image. The image is drawn at the
top-left corner at (x, y) coordinates in this graphics context's coordinate space
setSize(int height , int width): Use this method to set the size of the frame.
setVisible(boolean b): Pass the boolean value as true to display the image or Vice-Versa. Here we are passing the boolean value
as true to display the image on the frame.
getContentPane(): This method gets the content pane in which our GUI component will be added.
Code deacription:
In this example first we imports the required packages. Then create a class named ShowImage that extends the Panel class. Now
declare a variable of BufferedImage class. Constructor ShowImage() recieves the name of the image passed at the command
prompt in the BufferedReader object and reads the image from the system. Use paint() method to draw the image. Create a frame
and an object of ShowImage in the main method. Add this object into content pane, set the size of the frame and define the visibility
mode as true to display the image on the frame.
Here is the code of the program :
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class ShowImage extends Panel {
BufferedImage image;
public ShowImage() {
try {
System.out.println("Enter image name\n");
BufferedReader bf=new BufferedReader(new
InputStreamReader(System.in));
String imageName=bf.readLine();
File input = new File(imageName);
image = ImageIO.read(input);
} catch (IOException ie) {
System.out.println("Error:"+ie.getMessage());
}
}

public void paint(Graphics g) {
g.drawImage( image, 0, 0, null);
}

static public void main(String args[]) throws
Exception {
JFrame frame = new JFrame("Display image");
Panel panel = new ShowImage();
frame.getContentPane().add(panel);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
Input on dos Prompts :
C:\image>javac ShowImage.java
C:\image>java ShowImage
Enter image name
rajeshxml2.gif

Input image:rajeshxml2.gif


Output of The Example:


Animating Images in Java Application
This section shows you how to create an animation with multiple images. You can see how animation has been implemented in the
following program or example. The given program implements the animation using more than one images. Image are given below:


In this program, images are displayed one by one from the list of the images. Images are added to the label on the frame or window.
This program shows the image one by one after 1000 milliseconds or 1 second. The time delaying is maintained by thread.
Code Description:
One method has been used to show images on the frame one by one during the 1000 milliseconds. This collection of images makes
the application as an animation.
sleep(int time):
This is the method of the Thread class which is used to sleep the program for the specified time. The time to sleep is passed
through the sleep() method of the Thread class as parameter.
Here is the code of the program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingAnimation{
Thread th;
ImageIcon images;
JFrame frame;
JLabel lbl;
int i = 0;
int j;

public static void main(String[] args){
SwingAnimation sa = new SwingAnimation();
}

public SwingAnimation(){
frame = new JFrame("Animation Frame");
th = new Thread();
lbl = new JLabel();
Panel panel = new Panel();
panel.add(lbl);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for(j = 1; j <= 2; j++){
SwingAnimator();
if (j == 2)
j = 0;
}
}

public void SwingAnimator(){
try{
for(i = 1; i <= 5; i++){
images = new ImageIcon("images/img" + i + ".gif");
lbl.setIcon(images);
th.sleep(1000);
}
}
catch(InterruptedException e){}
}
}

Drawing with Color in Java
In this section, you will see how to draw colorful shapes in java swing. There are various colorful shapes have been drawn in the
given program. This program has used various types of methods to draw shapes and fill these with the appropriate color. Following
are some methods are using in the given program to complete the required result. Pictorial representation for the result is given
below:

drawRect():
This is the method of the Graphics class (The Graphics class is used to drawing different-different type of shapes). This method
draws the rectangle. It takes some integer value as parameter. This method is written like : Graphics.drawRect(x, y, height, width);.
x - This is the variable represents the row no. or the x - coordinate.
y - This is also a variable represents the column no. or the y - coordinate.
drawOval():
This is the method of the Graphics class which draws the oval on the frame. This method takes argument same as the drawRect()
method. In this method first come the width and then height is specified.
fillRect():
This is the method of the Graphics class which is used to fill rectangle with the specified color which is set before using the
setColor() method of the Graphics class. It also takes argument same as the drawRect() method.
fillOval():
This is also the method of the Graphicsclass which is used to fill the oval with color specified in the setColor() method before. This
method also takes argument same as the drawOval() method.
Here is the code of program:
import javax.swing.*;
import java.awt.*;

public class DrawingColor{
public static void main(String[] args) {
DrawingColor d = new DrawingColor();
}

public DrawingColor(){
JFrame frame = new JFrame("Drawing with Alpha");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyComponent());
frame.setSize(400,400);
frame.setVisible(true);
}

public class MyComponent extends JComponent{
public void paint(Graphics g){
int height = 200;
int width = 120;
g.setColor(Color.red);
g.drawRect(10,10,height,width);
g.setColor(Color.gray);
g.fillRect(11,11,height,width);
g.setColor(Color.red);
g.drawOval(250,20, height,width);
g.setColor(Color.magenta);
g.fillOval(249,19,height,width);
}
}
}

Drawing with Gradient Color in Java
In this section, you will learn how to draw the colorful gradient shapes. First of all you will know
about the gradient color. The gradient color is combination of more than one colors to design
graphics. Object with the gradient color looks like a 3-D component. The object colored with
gradient color makes it more attractive. The screen shot is given below:

Here you will see the gradient colors have been used in the Rectangle with the help of this
program. Program draws a rectangle using Graphics2D and GradientPaint().
Code Description:
The Gradient color uses the following methods:
Graphics2D:
This is the class which extends from the Graphicsclass i.e. used to control the geometry
according to the coordinate. It is also used to manage texts.
Gradient():
This is a constructor of Gradient class. It is used to create a gradient color with the help of
getGradient() method.
GradientPaint():
This is a constructor of Gradient class. It used to fill the gradient color in the shapes.
Syntax for GradientPaint:
GradientPaint(startX, startY, startColor, endX, endY, endColor, true)
startX - It represents the X-coordinate of the starting point.
startY - It represents the Y-coordinate of thestarting point.
startColor - It is used to set the starting color of the shape.
endX - It represents the X-coordinate of the ending point.
endY - It represents the Y- coordinate of the ending point.
endColor - It is used to set the ending color of the shape.
true - It is a boolean value mentioned for the cyclic presentation of color in the shape mean the
starting color and the ending color are repeated up to the size of the shape.
Here is the code of program:
import javax.swing.*;
import java.awt.*;

public class GradientColor{
public static void main(String[] args) {
GradientColor gd = new GradientColor();
}

public GradientColor(){
JFrame frame = new JFrame("Drawing with a Gradient Color");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyComponent());
frame.setSize(400,400);
frame.setVisible(true);
}

public class MyComponent extends JComponent {
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
Color s1 = Color.red;
Color e = Color.green;
GradientPaint gradient = new GradientPaint(10,10,s1,30,30,e,true);
g2d.setPaint(gradient);
g2d.drawRect(100,100,200,120);
Color s2 = Color.yellow;
Color e1 = Color.pink;
GradientPaint gradient1 = new GradientPaint(10,10,s2,30,30,e1,true);
g2d.setPaint(gradient1);
g2d.fillRect(99,99,199,119);
}
}
}


Adding a Rollover and Pressed Icon to a
JButton Component in Java

Here, you will learn about adding event i.e. the rollover and click icon to a JButton component of swing in java. Rollover means
moving mouse pointer above the icon on the button. This program shows an icon or image on the button if the mouse pointer moves
above the Button then your icon or image should be changed. When you click on the button then another image or icon should be
shown on the button.
This program displays a button on a frame. Button shows different icons like: cut, copy and paste on different events. At first, the
button shows the "cut" icon and when the mouse pointer moves above the button then the button shows the "copy" icon and when
you click on the button then the "paste" icon is seen. Following are the screenshot of the application:
This the "cut" image which occurs by default when the program is rum from the command prompt.

This is the "copy" image which occurs by default when user will rollover the image or button.

And this is the "paste" image which occurs by default when user clicks on the button.

Code Description:
These events are managed by the program using some APIs or methods as follows:
button.setRolloverIcon(Icon icon_name):
This is the method of the JButton class which is used to set the icon or image to a button for display when the mouse pointer rolls
over the icon or the button. The icon or image is passed through the method as a parameter.
button.setPressIcon(Icon press):
This is the method of the JButton class which is used to set the icon or image to a object for displaying when the button is clicked.
The icon or image is specified in the method argument as a parameter.
Here is the code of program:
import javax.swing.*;
import java.awt.*;

public class RolloverComponent{
public static void main(String[] args) {
JFrame frame = new JFrame("Adding a Rollover and Pressed Icon
to a JButton Component");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel,BorderLayout.CENTER);
JButton cutbutton = new JButton(new ImageIcon("cut.gif"));
panel.add(cutbutton);
ImageIcon rollover = new ImageIcon("copy.gif");
cutbutton.setRolloverIcon(rollover);
ImageIcon press = new ImageIcon("paste.gif");
cutbutton.setPressedIcon(press);
frame.setSize(400,400);
frame.setVisible(true);
}
}

Creating Check Box in Java Swing

This section illustrates you how to create a Check Box component in Java Swing.
In this section, you can learn simply creating the Check Box in Java Swing. Check Boxes are created in swing by creating the
instance of the JCheckBox class using it's constructor which contains the string which has to be shown beside the check box on
the frame or window like this:

This is written like:
JCheckBox chk = new JCheckBox("This is the Check Box");
This component of the javax.swing.*; is added to the frame using the add(component) method of the JFrame class.
Here is the code of the program:
import javax.swing.*;

public class CreateCheckBox{
public static void main(String[] args){
JFrame frame = new JFrame("Check Box Frame");
JCheckBox chk = new JCheckBox("This is the Check Box");
frame.add(chk);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Customize the Icon in a JCheckBox
Component of Java Swing

This section shows you how to customize the icon in a check box component. That means any icon can be shown where the
checked or unchecked box of the check box is situated. The specified icon is looked with the given text for the check box. Image for
the pictorial representation is as follows:

Following is the method used in this program:
setIcon(Icon):
This is the method of the JCheckBox class which sets the icon in the check box component of swing. The icon is passed to the
setIcon() method as a parameter. The image for icon is specified in the ImageIcon() constructor of theImageIcon class. This
constructor has been used in this program to create the instance of the Icon class for specifying the image name.
Here is the code of the program:
import javax.swing.*;

public class CustomizedCheckBox{
public static void main(String[] args){
JFrame frame = new JFrame("Customized Check Box");
Icon im = new ImageIcon("cut.gif");
JCheckBox chk = new JCheckBox("This is the Customized Check Box");
chk.setIcon(im);
frame.add(chk);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Create a JComboBox Component in
Java

In this section, you will learn about the JComboBox Component of swing in java. The JComboBox is used to display drop-down list.
It provides you options to select an item from the item list. You can never select more than one items from a combo box. Combo
Box can be whether editable or only non-editable means only readable.
This program displays a simple combo box on the frame which contains multiple items like: BCA, MCA, PPC etc. The background
color of this combo box is gray and foreground color is red. Here, the background color of the combo box and the foreground color is
set using the setBackground(Color) and setForeground(Color) method of the JComboBox class. When you select the item from the
combo box then the selected item is displayed in the text box. Image of the result for the given program is as follows in the pictorial
form:

And

APIs used in the program:
JComboBox:
This is the class which is used to create a combo box in swing using it's constructor.
itemStateChanged():
This is the method which receives the ItemEvent generated by the addItemListener() method of the JComboBox class. The event is
generated when you select item from the combo box.
Here is the code of program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ComboBox{
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
ComboBox b = new ComboBox();
}

public ComboBox(){
String course[] = {"BCA","MCA","PPC","CIC"};
JFrame frame = new JFrame("Creating a JComboBox Component");
JPanel panel = new JPanel();
combo = new JComboBox(course);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
txt = new JTextField(10);
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
String str = (String)combo.getSelectedItem();
txt.setText(str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}

Combo Box operation in Java Swing

In this section, you can learn how to operate the Combo Box component, you will learn how to add items to the combo box, remove
items from the combo box.
This program shows a text field, a combo box and two command buttons, first is for the adding items to the combo box and another
is for the removing items from the combo. When you click on the add command button then the text of the text box is added to the
combo box if the text box is not blank otherwise a message box will display with the message "Please enter text in Text Box". But
when you click on the remove button the item at the 0th (zero) position of the combo box will be remove from the combo box if the
combo box has one item at least otherwise a message box will display with the message "Item not available.". Following is the
image for the result of the given program:

This program has used various java APIs for doing required are explained as follows:
JComboBox combo = new JComboBox(items);
The above code has been used to create a combo box in this program. The JComboBox instance combo is created using the
constructor of the JComboBoxclass of the javax.swing.*; package. This constructor holds the string array in which items for the
combo box are kept.
getItemCount():
This is the method of the JComboBox class which return the number of the items present is the combo box.
getItemAt(index):
this is the method of the JComboBox class which returns the name of the item of the combo box at the specified position. This
specification of position the item in the combo box is held by the getItemAt() method as a parameter.
showMessageDialog():
This the method of the JOptionPane class of javax.swing.*;package. This method displays some messages in the special dialog
box. This method holds two argument in this program in which first is the parent object name and another is the message text which
has to be displayed.
addItem(String):
This is the method of the JComboBox class which adds items to the combo box. This method takes a string argument which is to
be used to add to the combo box.
removeItemAt(index):
This is the method of the JComboBox class which remove the item at the specified position of the combo box. This method holds
the integer value for the position number of the item in combo box to remove it.
Here is the code of the program:
import javax.swing.*;
import java.awt.event.*;

public class AddRemoveItemFromCombo{
JComboBox combo;
JTextField txtBox;
public static void main(String[] args){
AddRemoveItemFromCombo ar = new AddRemoveItemFromCombo();
}

public AddRemoveItemFromCombo(){
JFrame frame = new JFrame("Add-Remove Item of a Combo Box");
String items[] = {"Java", "JSP", "PHP", "C", "C++"};
combo = new JComboBox(items);
JButton button1 = new JButton("Add");
txtBox = new JTextField(20);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (!txtBox.getText().equals("")){
int a = 0;
for(int i = 0; i < combo.getItemCount(); i++){
if(combo.getItemAt(i).equals(txtBox.getText())){
a = 1;
break;
}
}
if (a == 1)
JOptionPane.showMessageDialog(null,"Combo has already this item.");
else
combo.addItem(txtBox.getText());
}
else{
JOptionPane.showMessageDialog(null,"Please enter text in Text Box");
}
}
});
JButton button2 = new JButton("Remove");
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (combo.getItemCount() > 0)
combo.removeItemAt(0);
else
JOptionPane.showMessageDialog(null,"Item not available");
}
});
JPanel panel = new JPanel();
JPanel panel1 = new JPanel();
panel.add(txtBox);
panel.add(combo);
panel.add(button1);
panel.add(button2);
frame.add(panel);
// frame.add(panel1);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
}

Create a JRadioButton Component in
Java

In this section, you will learn how to create a radio button in java swing. Radio Button is like check box. Differences between check
box and radio button are as follows:
1. Check Boxes are separated from one to another where Radio Buttons are the different-different button like check box
from a same ButtonGroup.
2. You can checks multiple check boxes at once but this can never done in the case of radio button. You can select only one
radio button at once from a group of the radio button.
3. You can check or uncheck the check box but you can on check the radio button by clicking it once.
Here, you will see the JRadioButton component creation procedure in java with the help of this program. This example provides two
radio buttons same ButtonGroup. These radio buttons represent the option for choosing male or female. Following is the image for
the result of the given program:

The creation of JRadioButton are completed by the following methods:
ButtonGroup:
This is the class of the javax.swing.*;package, which is used to create a group of radio buttons from which you can select only one
option from that group of the radio buttons. This is class is used by creating a instance of if using it's constructor. Radio Buttons are
added to the specified group using the add(JRadioButton) method of the ButtonGroupclass.
JRadioButton:
This is the class has been used to create a single radio button for the application.
setSelected():
This method sets the value of the radio button. This method takes a boolean value either true or false. If you pass true value then
the radio button will be selected otherwise the radio button is not selected.
Here is the code of program:
import javax.swing.*;
import java.awt.*;

public class CreateRadioButton{
public static void main(String[] args) {
CreateRadioButton r = new CreateRadioButton();
}

public CreateRadioButton(){
JRadioButton Male,Female;
JFrame frame = new JFrame("Creating a JRadioButton Component");
JPanel panel = new JPanel();
ButtonGroup buttonGroup = new ButtonGroup();
Male = new JRadioButton("Male");
buttonGroup.add(Male);
panel.add(Male);
Female = new JRadioButton("Female");
buttonGroup.add(Female);
panel.add(Female);
Male.setSelected(true);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}


Selecting a Radio Button component in
Java
In this section, you will learn how to set the radio buttons in a group so that only one can be selected at a time.
This program shows five radio buttons with labeled by "First", "Second", "Third", "Fourth" and "Fifth". This program also show a label
which contains the text "Roseindia.net" but when you click on any radio button from a ButtonGroup the text of the selected radio
button is shown on the label and a message box will be shown with message holds the selected radio button label. This is done
through the generating event for the different-different radio buttons. Following are the screen shots for the result of the given
program:


For this purposes, there are some APIs or methods have been used as follows:
getActionCommand():
This is the method of the ActionEvent class which returns the source title in string of the generated event.
Here is the code of the program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SelectRadioButton{
JLabel label;
public static void main(String[] args){
SelectRadioButton sr = new SelectRadioButton();
}

public SelectRadioButton(){
JFrame frame = new JFrame("Radio button selection");
JRadioButton first = new JRadioButton("First");
JRadioButton second = new JRadioButton("Second");
JRadioButton third = new JRadioButton("Third");
JRadioButton fourth = new JRadioButton("Fourth");
JRadioButton fifth = new JRadioButton("Fifth");
JPanel panel = new JPanel();
panel.add(first);
panel.add(second);
panel.add(third);
panel.add(fourth);
panel.add(fifth);
ButtonGroup bg = new ButtonGroup();
bg.add(first);
bg.add(second);
bg.add(third);
bg.add(fourth);
bg.add(fifth);
first.addActionListener(new MyAction());
second.addActionListener(new MyAction());
third.addActionListener(new MyAction());
fourth.addActionListener(new MyAction());
fifth.addActionListener(new MyAction());
label = new JLabel("Roseindia.net");
frame.add(panel, BorderLayout.NORTH);
frame.add(label, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e){
label.setText(e.getActionCommand());
JOptionPane.showMessageDialog(null,"This is the " + e.getActionCommand() +
" radio button.");
}
}
}


Create a JList Component in Java

In this section, you will learn how to create a JList component of swing. JList is a component of GUI. It provides the multiple items in
a list and some times it shows the data in multiple columns in a list. Lists are used to select item from the item's group like combo
box but the major difference between list and the combo box is that you can select only one item from the combo box since you can
select more than one item at once from the list. You can easily add or remove items from or to the JList component of swing. The
JList component has been shown in this article below:

This program provides a List. The given List has multiple subjects as items like: Math, Computer, Physics and Chemistry.
JList:
This is the class which is used to create a list which contains items. This class extends the JComponentclass in java swing. There
has been using string array values in this program.
Here is the code of program:
import javax.swing.*;

public class CreateJList{
public static void main(String[] args) {
String subject[] = {"Math", "Computer", "Phisics", "Chemestry"};
JFrame frame = new JFrame("Creating a JList Component");
JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JList list = new JList(subject);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
panel.add(list);
frame.add(panel);
frame.setSize(400,400);
frame.setVisible(true);
}
}

Setting Tool Tip Text for items in a JList
Component

In this section, you will learn how to set the tool tip text for items present in the JList component of the Java Swing. Tool Tip text is
the help text of any component for user. When you rest the mouse cursor on the component then at that point a message which
small font and yellow background stay there for few seconds. This text show the information about that component.
This program has used the tool tip text for items present in the JList component in Java Swing. In this program, you can add more
and more items. You can enter the item name in the text box and click on the "Add" button. When you move the mouse pointer
around the items in the list, it shows the specific item name as a tool tip text like the following image:

Following are some methods and APIs are explained as follows:
JScrollPane:
This is the class of javax.swing.*; package of Java Swing. This class is used to create scroll bar (Horizontal or Vertical) for any
component. This program has used this for creating scroll bar for the text area. It creates scroll bar using it's constructor which holds
the component name for which the scroll bar has to be created.
DefaultListModel:
This is the class of javax.swing.*; package of Java. This class is used to create a list model which is helpful for adding items for the
list. This class has used own method to add items in the list.
locationToIndex():
This is the method of the MultiListUI class which is imported from the javax.swing.plaf.multi.*;package of Java. This method locate
the item to the index where the mouse pointer points. This method takes a integer value for locating item from the list according to
the given point.
getModel():
This is the method of JList class which holds the list of item which are shown in the JList component of Java Swing. It returns the
list model.
getElementAt(index):
This is the method of DefaultListModel class which gets the item from the returned list model by getModel() method according to
the given integer index no. as parameter.
addElement(String):
This is the method of DefaultListModel class which adds the item into the list.
Here is the code of the program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TooltipTextOfList{
private JScrollPane scrollpane = null;
JList list;
JTextField txtItem;
DefaultListModel model;
public static void main(String[] args){
TooltipTextOfList tt = new TooltipTextOfList();
}

public TooltipTextOfList(){
JFrame frame = new JFrame("Tooltip Text for List Item");
String[] str_list = {"One", "Two", "Three", "Four"};
model = new DefaultListModel();
for(int i = 0; i < str_list.length; i++)
model.addElement(str_list[i]);
list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
txtItem = new JTextField(10);
JButton button = new JButton("Add");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(txtItem);
panel.add(button);
panel.add(list);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public class MyAction extends MouseAdapter implements ActionListener{
public void actionPerformed(ActionEvent ae){
String data = txtItem.getText();
if (data.equals(""))
JOptionPane.showMessageDialog(null,"Please enter text in the Text Box.");
else{
model.addElement(data);
JOptionPane.showMessageDialog(null,"Item added successfully.");
txtItem.setText("");
}
}
}
}

Setting the Dimensions of an Item in a
JList Component in Java

In this section, you will learn about setting the dimensions of the List component in java. A list can have multiple data or items. Here,
you will know how to set data or items in a List Component. This provides setting the dimension of items present in the list. You can
specify the dimension of items present in the list.
Here, the dimension for the items of the list have been mentioned according to the length of the specified text "Roseindia.net". The
These are shown in the following figure:

Following are the explanation of the used method which is helpful for setting the dimension of various items of the list:
setPrototypeCellValue(String):
This method sets the dimension of the list items. This method takes a string as a parameter. According to the length of the
mentioned string, all the list width is arranged properly.
Here is the code of program:
import javax.swing.*;
import java.awt.event.*;

public class DimensionItemList{
public static void main(String[] args) {
DimensionItemList di = new DimensionItemList();
}

public DimensionItemList(){
String name[] = {"Deepak", "Chandan Kumar Verma",
"Sushil","Raju",
"Santosh", "Amar", "Vinod"};
JFrame frame = new JFrame("Setting the Dimensions of
an Item in
a JList Component");
JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultListModel model = new DefaultListModel();
for(int i = 0; i < name.length; i++)
model.addElement(name[i]);
JList list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
list.setPrototypeCellValue("RoseIndia.net");
panel.add(list);
frame.add(panel);
frame.setSize(400,400);
frame.setVisible(true);
}
}

Create a JSpinner Component in Java

In this section, you will learn how to create a JSpinner component of swing. The JSpinner provides the up-down arrow buttons which
are used to increase or decrease the numeric value.
This program provides an appropriate JSpinner component on the frame. The following figure shows that:

This program have used the following methods or API's components for appropriate:
JSpinnerComp():
This is the constructor of JSpinnerCompclass. This constructor used for displaying the JSpinner component on the frame.
JSpinner():
This is the constructor of JSpinnerclass. It extends form the JComponentclass. This is used to create a spinner. It takes the initial
value "0" by default.
Here is the code of program:
import javax.swing.*;
import java.awt.*;
import java.util.*;

public class JSpinnerComp{
public static void main(String[] args) {
JSpinnerComp h = new JSpinnerComp();
}

public JSpinnerComp(){
JFrame frame = new JFrame("Creating a JSpinner Component");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSpinner spinner = new JSpinner();
frame.add(spinner,BorderLayout.NORTH);
frame.setSize(100,100);
frame.setVisible(true);
}
}

Show Time in JSpinner Component

In this section, you will learn about the creation of a JSpinner Component with time. Here, you will see time is increased or
decreased with the help of JSpinner button. This program increases or decreases the time and change hour from 1 to 12. Following
image shows you a JSpinner component with time:

If you want to increase or decrease the minute then you have to put the cursor in the minute section of the JSpinner. Following are
some methods and APIs:
Date():
This is the constructor of Date class. Dateclass is used by importing from java.util.*; package of java. This class is used to represent
date and time according to Greenwich Mean Time (GMT) by default.
SpinnerDateModel():
It is a constructor of SpinnerDateModelclass. It creates a SpinnerDateModel and takes date and Calendar.HOUR_OF_DAYfrom a
calendar.
Calendar.HOUR_OF_DAY
This is the Calendar class field which returns the hour of the specified time.
JSpinner.DateEditor(spinner, "hh:mm"):
This is the constructor of JSpinner.DateEditorclass. It is used to formatting the date given in the JSpinner component. This
constructor takes two argument in which, first is the JSpinner specification and second one is the format in "hh:mm" means first
come hour and then the minute.
setEditor():
This is the method of the JSpinner class i.e. used to change that component which is helpful to show the current value of the
SpinnerModel.
Here is the code of program:
import javax.swing.*;
import java.awt.*;
import java.util.*;

public class ShowTimeJSpinner{
public static void main(String[] args) {
ShowTimeJSpinner h = new ShowTimeJSpinner();
}

public ShowTimeJSpinner(){
JFrame frame = new JFrame("Creating JSpinner Component with time");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Date date = new Date();
SpinnerDateModel sm =
new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
JSpinner spinner = new JSpinner(sm);
JSpinner.DateEditor de = new JSpinner.DateEditor(spinner, "hh:mm");
spinner.setEditor(de);
frame.add(spinner,BorderLayout.NORTH);
frame.setSize(100,100);
frame.setVisible(true);
}
}

Disabling Keyboard Editing in a
JSpinner Component
In this section, you will see how to create a non editable Spinner component of Java Swing. You can increase it's value by clicking
up and down button. Through the given program you can only increase and decrease the value nor write the value directly in the
Spinner component of java. The JSpinner component, which is disable for the keyboard editing looks like the following image:

In this program, a Spinner component has been created and set for editing mode of the Spinner. The Spinner has been disabled for
editing using setEditable() method. Some following methods and APIs are explained as follows:
JFormattedTextField:
This is the class of javax.swing.*;package which creates formatted text field for edit text in the specified format. For creating a
JFormattedTextField, the syntax is written like:
JFormattedTextField tf = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField();
getTextField():
This method creates a JFormattedTextField for edit in the specified format. This is defined in the JSpinner.DefaultEditorclass.
getEditor():
This is the method of JSpinner class. This method is used to get the editor which has been using for the JSpinner component.
Here is the code of the program:
import javax.swing.*;
import java.awt.*;

public class DesableEditingSpinner{
public static void main(String[] args){
JFrame frame = new JFrame("Desabling editing Spinner");
JSpinner spinner = new JSpinner();
JFormattedTextField tf = ((JSpinner.DefaultEditor)spinner.getEditor())
.getTextField();
tf.setEditable(false);
spinner.setValue(new Integer(100));
JPanel panel = new JPanel();
panel.add(spinner);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


Limiting the Values in a Number
JSpinner Component

In this section you will learn how to create a Number JSpinner that can take values up to certain maximum limit. You can even set
the minimum value of the JSpinner component.
In this program, you will see the code for JSpinner component that holds the numeric value up to certain maximum limit. Following
program has used some methods and APIs are explained as follows:
SpinnerModel:
This is the Interface of the javax.swing.*; package which is implemented by the SpinnerNumberModel class i.e. used to sequence
of numbers it's constructor specifies the lower and upper bound for JSpinner contained values.
SpinnerNumberModel():
This is the constructor of the SpinnerNumberModel class which sets the lower and upper bound for the JSpinner contained values.
The constructor takes four argument as follows:
First is the default value of JSpinner component.
Second is the lower bound of JSpinner component.
Third is the upper bound of JSpinner component.
Fourth is the steps to increase and decrease the JSpinner contained value by the specified number.
Here is the code of the program:
import javax.swing.*;
import java.awt.*;

public class LimitValueSpinner{
public static void main(String[] args){
JFrame frame = new JFrame("Limiting value for a JSpinner");
SpinnerModel sm = new SpinnerNumberModel(0, -50, 100, 2);
JSpinner spinner = new JSpinner(sm);
JPanel panel = new JPanel();
panel.add(spinner);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
JSlider Component of Java Swing

In this section, you will learn how to create a JSlider component of Java Swing. A Slider is a Swing tool which you can use for
selecting a range. There is minimum chances of being mistake to illegal input values.
In this program, events on the JSlider component have also been shown. If you increase or decrease the slider by selecting then the
actual position of the slider will be displayed on a label. The figure for the result of the given program is followed below:
Before touch the JSlider Component:

After drag the JSlider Component:

For these purposes, some methods and APIs have been used to create a JSlider component and performs various tasks related to
the slider. Methods and APIs are as follows:
JSlider:
This is the class which creates the slider for the swing application. For creating the slider this class creates a instance using it's
constructor JSlider().
ChangeListener:
This is the interface of which is used to call stateChanged() method which receives the event generated by the slider using
addChangeListener() method of the JSlider class.
ChangeEvent:
This is the class which handle the event generated by the JSlider component on change the state.
addChangeListener(object):
This is the method of the JSlider class which is used to handle event on change the selected state of the JSlider component.
Here is the code of the program:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class CreateSlider{
JSlider slider;
JLabel label;
public static void main(String[] args){
CreateSlider cs = new CreateSlider();
}

public CreateSlider(){
JFrame frame = new JFrame("Slider Frame");
slider = new JSlider();
slider.setValue(70);
slider.addChangeListener(new MyChangeAction());
label = new JLabel("Roseindia.net");
JPanel panel = new JPanel();
panel.add(slider);
panel.add(label);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public class MyChangeAction implements ChangeListener{
public void stateChanged(ChangeEvent ce){
int value = slider.getValue();
String str = Integer.toString(value);
label.setText(str);
}
}
}

Progress Bar in Java Swing


In this section, you can learn how to handle progress bar in java swing. This section shows you how the progress bar starts and
stops with the timer. Through the given example you can understand how the progress bar is created for showing your work is in
progress.
This program shows you a frame in which a button labeled by the string "Start", a progress bar and another is the label which has
been used to display some messages. When you click on the "Start" button progress bar is started to progress the completed
process in percent and the label which holds the text "Roseindia.net" is change to with the label text "Downloading is in process......"
in green color and the button is disabled. When the value of the progress bar is become 100% then the label text of the label is
changed with the text "Downloading completed." in red color and "Start" button is enabled.
The label display the information about the Downloading process whether completed or not. But here, nothing is downloading
through the program. This message on the label has been used only for showing in output of the program. For completion the
process, there are some methods and APIs are used in the program has been explained as follows:
JProgressBar:
This is the class which creates the progress bar using it's constructor JProgressBar()to show the status of your process completion.
The constructor JProgressBar()takes two argument as parameter in which, first is the initial value of the progress bar which is
shown in the starting and another argument is the counter value by which the value of the progress bar is incremented. Here, the
value of the progress bar is incremented by 20.
setStringPainted(boolean):
This is the method of the JProgressBar class which shows the complete process in percent on the progress bar. It takes a boolean
value as a parameter. If you pass the true then the value will be seen on the progress bar otherwise not seen.
setValue():
This is the method of the JProgressBar class which sets the value to the progress bar.
Timer():
This the constructor of the Timer class which starts the timer for timing. This constructor takes two argument as parameter first is
the interval (in milliseconds) of the timer and second one is the listener object. Time is started using the start() method of the Timer
class.
Here is the code of the program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.html.*;

public class SwingProgressBar{
final static int interval = 1000;
int i;
JLabel label;
JProgressBar pb;
Timer timer;
JButton button;

public SwingProgressBar() {
JFrame frame = new JFrame("Swing Progress Bar");
button = new JButton("Start");
button.addActionListener(new ButtonListener());

pb = new JProgressBar(0, 20);
pb.setValue(0);
pb.setStringPainted(true);

label = new JLabel("Roseindia.net");

JPanel panel = new JPanel();
panel.add(button);
panel.add(pb);

JPanel panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
panel1.add(panel, BorderLayout.NORTH);
panel1.add(label, BorderLayout.CENTER);
panel1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
frame.setContentPane(panel1);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create a timer.
timer = new Timer(interval, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (i == 20){
Toolkit.getDefaultToolkit().beep();
timer.stop();
button.setEnabled(true);
pb.setValue(0);
String str = "<html>" + "<font color=\"#FF0000\">" + "<b>" +
"Downloading completed." + "</b>" + "</font>" + "</html>";
label.setText(str);
}
i = i + 1;
pb.setValue(i);
}
});
}

class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
button.setEnabled(false);
i = 0;
String str = "<html>" + "<font color=\"#008000\">" + "<b>" +
"Downloading is in process......." + "</b>" + "</font>" + "</html>";
label.setText(str);
timer.start();
}
}

public static void main(String[] args) {
SwingProgressBar spb = new SwingProgressBar();
}
}

Create menus and submenus in Java

In this section, you will learn about creation of menus, submenus and Separators in Java Swing. Menu bar contains a collection of
menus. Each menu can have multiple menu items these are called submenu. Similarly, all menus have multiples menu items. The
Separator divides the menu items in a separate groups like same types of menu Items are divided into a individual parts. For
pictorial representation, the image for the result of the given program is given below:



This program shows how to create menu bar, menus, submenus and Separators. Here, all items shows on a frame with the help of
following methods and APIs:
JMenuBar:
This is the class which constructs a menu bar that contains several menus.
JMenu(String):
This is the constructor of JMenu class. This constructor constructs the new menu. It takes the string type value which is the name
label for the menu.
JMenuItem(String):
This is the constructor of JMenuItem class which constructs new menu items for the specific menu. It takes string types value which
is the label for the menu item.
JSeparator():
This is the constructor of JSeparator class which adds an extra line between menu items. This line, only separates the menu items.
setJMenuBar():
This method is used to set the menu bar to the specified frame. It takes the object of the JMenuBar class.
Here is the code of program:
import javax.swing.*;

public class SwingMenu{
public static void main(String[] args) {
SwingMenu s = new SwingMenu();
}

public SwingMenu(){
JFrame frame = new JFrame("Creating a JMenuBar, JMenu, JMenuItem and
seprator Component");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menubar = new JMenuBar();
JMenu filemenu = new JMenu("File");
filemenu.add(new JSeparator());
JMenu editmenu = new JMenu("Edit");
editmenu.add(new JSeparator());
JMenuItem fileItem1 = new JMenuItem("New");
JMenuItem fileItem2 = new JMenuItem("Open");
JMenuItem fileItem3 = new JMenuItem("Close");
fileItem3.add(new JSeparator());
JMenuItem fileItem4 = new JMenuItem("Save");
JMenuItem editItem1 = new JMenuItem("Cut");
JMenuItem editItem2 = new JMenuItem("Copy");
editItem2.add(new JSeparator());
JMenuItem editItem3 = new JMenuItem("Paste");
JMenuItem editItem4 = new JMenuItem("Insert");
filemenu.add(fileItem1);
filemenu.add(fileItem2);
filemenu.add(fileItem3);
filemenu.add(fileItem4);
editmenu.add(editItem1);
editmenu.add(editItem2);
editmenu.add(editItem3);
editmenu.add(editItem4);
menubar.add(filemenu);
menubar.add(editmenu);
frame.setJMenuBar(menubar);
frame.setSize(400,400);
frame.setVisible(true);
}
}

Вам также может понравиться