Java Notes (3) in PDF Form
Java Notes (3) in PDF Form
Example:
import [Link];
public class JavaRandomExample1 {
public static void main(String[] args) {
//create random object
Random random= new Random();
//returns unlimited stream of pseudorandom long values
[Link]("Longs value : "+[Link]());
// Returns the next pseudorandom boolean value
boolean val = [Link]();
[Link]("Random boolean value : "+val);
byte[] bytes = new byte[10];
//generates random bytes and put them in an array
[Link](bytes);
[Link]("Random bytes = ( ");
for(int i = 0; i< [Link]; i++)
{
[Link]("%d ", bytes[i]);
}
[Link](")");
}
}
209
Output:
Formatter
Constructors
The Formatter class defines many constructors, which enable you to construct
a Formatter in a variety of ways. Here is a sampling:
Formatter( )
Formatter(Appendable buf)
Formatter(Appendable buf, Locale loc)
Formatter(String filename)
throws FileNotFoundException
Formatter(String filename, String charset)
throws FileNotFoundException, UnsupportedEncodingException
Formatter(File outF)
throws FileNotFoundException
Formatter(OutputStream outStrm)
210
Formatting Numbers
[Link]+/–yy
Example:
// Demonstrate the %g format specifier.
import [Link].*;
class FormatDemo2 {
public static void main(String args[]) {
Formatter fmt = new Formatter();
for(double i=1000; i < 1.0e+10; i *= 100) {
[Link]("%g ", i);
[Link](fmt);
}
}
}
Scanner
211
whether it comes from a disk file, the keyboard, or another source.
Scanner can be used to read input from the console, a file, a string, or
any source that implements the Readable interface or
ReadableByteChannel.
Examples
import [Link].*;
class AvgNums {
public static void main(String args[]) {
Scanner conin = new Scanner([Link]);
int count = 0;
double sum = 0.0;
[Link]("Enter numbers to average.");
// Read and sum numbers.
while([Link]()) {
if([Link]()) {
sum += [Link]();
count++;
}
else {
String str = [Link]();
if([Link]("done")) break;
else {
[Link]("Data format error.");
return;
}
}
}
[Link]("Average is " + sum / count);
}
}
OUTUT
212
UNIT-V
AWT
Limitations of AWT:
The AWT defines a basic set of controls, windows, and dialog boxes that
support a usable, but limited graphical interface. One reason for the
limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents or
peers.
This means that the look and feel of a component is defined by the
platform, not by java. Because the AWT components use native code
resources, they are referred to as heavy weight.
The use of native peers led to several problems.
First, because of variations between operating systems, a component
might look, or even act, differently on different platforms.
This variability threatened java’s philosophy: write once, run anywhere.
Second, the look and feel of each component was fixed and could not be
changed.
Third, the use of heavyweight components caused some frustrating
restrictions.
Due to these limitations Swing came and was integrated to java.
Swing is built on the AWT.
Two key Swing features are:
Swing components are light weight,
Swing supports a pluggable look and feel.
MVC architecture:
MVC
The model corresponds to the state information associated with the
component. For example, in the case of a check box, the model contains
a field that indicates if the box is checked or unchecked.
213
The view determines how the component is displayed on the screen,
including any aspects of the view that are affected by the current state of
the model.
The controller determines how the component reacts to the user.
For example, when the user clicks a check box, the controller reacts by
changing the model to reflect the user’s choice (checked or unchecked). This
then results in the view being updated. By separating a component into a
model, a view, and a controller, the specific implementation of each can be
changed without affecting the other two. For instance, different view
implementations can render the same component in different ways without
affecting the model or the controller.
214
Components & Containers of AWT:
215
The AWT defines windows according to a class hierarchy that adds
functionality and specificity with each level.
Container
Component
At the top of the AWT hierarchy is the Component class. Component is an
abstract class that encapsulates all of the attributes of a visual component. All
user interface elements that are displayed on the screen and that interact with
the user are subclasses of Component.
It defines over a hundred public methods that are responsible for managing
events, such as mouse and keyboard input, positioning and sizing the window,
and repainting.
216
height) component.
public void defines the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean changes the visibility of the component, by
status) default false.
Window
The window is the container that have no borders and menu bars. You must
use frame, dialog or another window for creating a window.
Frame
The Frame is the container that contain title bar and can have menu
bars. It can have other components like button, textfield etc.
The Panel is the container that doesn't contain title bar and menu bars.
It can have other components like button, textfield etc.
A Panel is a window that does not contain a title bar, menu bar, or
border. This is why you don’t see these items when an applet is run
inside a browser. When you run an applet using an applet viewer, the
applet viewer provides the title and border.
217
Frame Windows in awt:
Frame’s constructors:
To create simple awt example, you need a frame. There are two ways to create a
frame in AWT.
218
AWT Panel Example:
import [Link].*;
class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
[Link]([Link]);
[Link](b1); [Link](b2);
[Link](panel);
[Link](400,400);
[Link](null);//when we use setBounds() only layout must null
[Link](true);
}
}
Output:
219
Swing
The AWT defines a basic set of controls, windows, and dialog boxes that
support a usable, but limited graphical [Link] reason for the
limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents, or
peers.
This means that the look and feel of a component is defined by the
platform, not by Java. Because the AWT components use native code
resources, they are referred to as heavyweight.
Swing was initially available for use with Java 1.1 as a separate
library.
However, beginning with Java 1.2, Swing (and the rest of the JFC) was
fully integrated into Java.
220
Components and Containers of swings :
Swing Components:
In general, Swing components are derived from the JComponent class.
The following table shows the class names for Swing components (including
those used as containers).
221
JComponent provides the functionality that is common to all components. For
example, JComponent supports the pluggable look and feel. JComponent
inherits the AWT classes Container and Component.
Thus, a Swing component is built on and compatible with an AWT component.
Swing Containers:
222
Swing defines two types of containers. The one most commonly used for
applications is JFrame. The one used for applets is JApplet.
Unlike Frame, JFrame has the option to hide or close the window with the help
of setDefaultCloseOperation(int) method.
Constructors
Constructor Description
It constructs a new frame that is initially
JFrame()
invisible.
It creates a Frame in the specified
JFrame(GraphicsConfiguration gc) GraphicsConfiguration of a screen device
and a blank title.
It creates a new, initially invisible Frame
JFrame(String title)
with the specified title.
It creates a JFrame with the specified title
JFrame(String title,
and the specified GraphicsConfiguration of
GraphicsConfiguration gc)
a screen device.
223
Java Swing Example Swing by Association inside
import [Link].*; constructor
public class FirstSwingExample { import [Link].*;
public static void main(String[] args) {
public class Simple {
JFrame f=new JFrame();//creating JFrame f;
instance of JFrame Simple(){
f=new JFrame();//creating instance
JButton b=new of JFrame
JButton("click");//creating instance
of JButton JButton b=new
[Link](130,100,100, 40);//x JButton("click");//creating instance
axis, y axis, width, height of JButton
[Link](130,100,100, 40); );//x
[Link](b);//adding button in JFrame axis, y axis, width, height
Swing by inheritance
import [Link].*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click"); //create button
[Link](130,100,100, 40); );//x axis, y axis, width, height
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) { new Simple2(); }}
224
Output for all above 3 Programs:
Whenever a container is resized (or sized for the first time), the layout manager
is used to position each of the components within it.
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
225
[Link]
The FlowLayout is used to arrange the components in a line, one after another
(in a flow). It is the default layout of applet or panel.
The first form creates the default layout, which centers components and leaves
five pixels of
space between each component. The second form lets you specify how each line
is aligned.
Valid values for how are as follows:
[Link]
[Link]
[Link]
[Link]
[Link]
import [Link].*;
import [Link].*;
[Link](b1);[Link](b2);[Link](b3);[Link](b4);[Link](b5);
[Link](new FlowLayout([Link]));
226
//setting flow layout of right alignment
[Link](300,300);
[Link](true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
Output:
[Link]
227
Constructors of BorderLayout class:
add(new TextArea(msg),
[Link]);
}}
228
Output: Output:
[Link]
229
JButton b2=new JButton("2"); Applet {
JButton b3=new JButton("3"); static final int n = 4;
JButton b4=new JButton("4"); public void init() {
JButton b5=new JButton("5"); setLayout(new GridLayout(n, n));
JButton b6=new JButton("6"); setFont(new Font("SansSerif",
JButton b7=new JButton("7"); [Link], 24));
JButton b8=new JButton("8"); for(int i = 0; i < n; i++) {
JButton b9=new JButton("9"); for(int j = 0; j < n; j++) {
int k = i * n + j;
[Link](b1);[Link](b2);[Link](b3); if(k > 0)
[Link](b4);[Link](b5); add(new Button("" + k));
[Link](b6);[Link](b7);[Link](b8);[Link](b9); }
}
[Link](new GridLayout(3,3)); }
//setting grid layout of 3 rows and 3
columns }
[Link](300,300); Output:
[Link](true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Output:
230
[Link]
import [Link];
import [Link];
import [Link];
import [Link].*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
[Link](layout);
[Link] = [Link];
[Link] = 0;
[Link] = 0;
[Link](new Button("Button One"), gbc);
[Link] = 1;
[Link] = 0;
231
[Link](new Button("Button two"), gbc);
[Link] = [Link];
[Link] = 20;
[Link] = 0;
[Link] = 1;
[Link](new Button("Button Three"), gbc);
[Link] = 1;
[Link] = 1;
[Link](new Button("Button Four"), gbc);
[Link] = 0;
[Link] = 2;
[Link] = [Link];
[Link] = 2;
[Link](new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Output:
232
[Link]
The CardLayout class is unique among the other layout managers in
that it stores severaldifferent layouts.
Each layout can be thought of as being on a separate index card in a
deck that can be shuffled so that any card is on top at a given time.
This can be useful for user interfaces with optional components that can
be dynamically enabled and disabled upon user input.
You can prepare the other layouts and have them hidden, ready to be
activated when needed.
The CardLayout class manages the components in such a manner that
only one component is visible at a time. It treats each component as a
card that is why it is known as CardLayout.
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.
import [Link].*;
import [Link].*;
import [Link].*;
233
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
[Link](card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
[Link](this);
[Link](this);
[Link](this);
[Link]("a",b1);[Link]("b",b2);[Link]("c",b3);
}
public void actionPerformed(ActionEvent e) {
[Link](c);
}
Output:
234
Event Handling:
Event Handling is the mechanism that controls the event and decides
what should happen if an event occurs. This mechanism have the code
which is known as event handler that is executed when an event occurs.
The event handling mechanism used by Swing is the same as that used
by the [Link] approach is called the delegation event model.
Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.
The Delegation Event Model has the following key participants namely:
235
Adapter Classes
236
The adapter classes are found in [Link], [Link] and
[Link] packages. The Adapter classes with their corresponding
listener interfaces are
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
237
KeyListener{ Label l;
TextArea area;
public void keyPressed(KeyEvent ke) Frame f;
{ KeyAdapterExample(){
[Link]("Key Pressed f=new Frame("Key Adapter");
["+[Link]()+"]"); l=new Label();
} [Link](20,50,200,20);
public void keyReleased(KeyEvent ke) area=new TextArea();
{ [Link](20,80,300, 300);
[Link]("Key Released [Link](this);
["+[Link]()+"]");
} [Link](l);[Link](area);
public void keyTyped(KeyEvent ke) [Link](400,400);
{ [Link](null);
[Link]("Key Entered [Link](true);
["+[Link]()+"]"); }
} public void keyReleased(KeyEvent
e) {
} String text=[Link]();
class Myframe2 extends JFrame String words[]=[Link]("\\s");
{ [Link]("Words: "+[Link]+"
Myframe2() Characters:"+[Link]());
{ }
[Link](710,500);
[Link](true); public static void main(String[]
[Link]("MouseEvents"); args) {
//[Link](new FlowLayout()); new KeyAdapterExample();
getContentPane().setBackground(Colo }
[Link]); }
[Link](new KeyEventEx());
[Link](JFrame Output:
.EXIT_ON_CLOSE);
}
}
class KeyboardEvents
{
public static void main(String arg[])
{
Myframe2 f=new Myframe2();
238
}
}
Inner Classes
Recall that an inner class is a class defined within another class, or even within
an expression.
239
Here, InnerClassDemo is a top-level class that extends Applet.
MyMouseAdapter is an inner class that extends MouseAdapter. Because
MyMouseAdapter is defined within the scope of InnerClassDemo, it has
access to all of the variables and methods within the scope of that class.
Applet
240
viewer, called appletviewer, provided by the JDK. But we can use any
applet viewer or browser we like.
you can test the compiled applet by starting the applet viewer with your
Java source code file specified as the target.
Here is an example of such a comment:
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
This comment contains an APPLET tag that will run an applet called
MyApplet in a window that is 200 pixels wide and 60 pixels high.
As displayed in the above diagram, Applet class extends Panel. Panel class
extends Container which is the subclass of Component.
241
The first are those based directly on the Applet class These applets use
the Abstract Window Toolkit (AWT) to provide the graphic user interface
(or use no GUI at all). This style of applet has been available since Java
was first created.
The second type of applets are those based on the Swing class JApplet.
Swing applets use the Swing classes to provide the GUI. Swing offers a
richer and often easier-to-use user interface than does the AWT. Thus,
Swing-based applets are now the most popular. However, traditional
AWT-based applets are still used, especially when only a very simple user
interface is required.
Thus, both AWT- and Swing-based applets are valid.
[Link] class
[Link] class
run an Applet?
242
1. By html file.
2. By appletViewer tool (for testing purpose).
To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html
file.
//[Link]
import [Link];
import [Link];
public class First extends Applet{
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
//[Link]
import [Link];
import [Link];
public class First extends Applet{
}
/*
243
<applet code="[Link]" width="300" height="300">
</applet>
*/
c:\>javac [Link]
c:\>appletviewer [Link]
the APPLET tag in HTML allows you to pass parameters to your applet.
To retrieve a parameter, use the getParameter( ) method. It returns the value
of the specified parameter in the form of a String object. Thus, for numeric and
boolean values, you will need to convert their string representations into their
internal formats. Here is an example that demonstrates passing parameters:
Example 1:
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
import [Link].*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
[Link]("Name is: " + n, 20, 20);
[Link]("Age is: " + a, 20, 40);
}
}
244
Creating a Swing Applet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of
swing. The JApplet class extends the Applet class.
Example:
/* <applet code="[Link]" width="300" height="300"> */
import [Link].*;
import [Link].*;
import [Link].*;
tf=new JTextField();
[Link](30,40,150,20);
b=new JButton("Click");
[Link](80,150,70,40);
add(b);add(tf);
245
[Link](this);
setLayout(null);
}
}
Output:
In the above example, we have created all the controls in init() method because
it is invoked only once.
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
Painting in Swing
246
There are three customized callbacks for Swing components, which factor out a
single paint method into three subparts. These are
paintComponent()
paintBorder()
paintChildren()
o paintComponent()
You use the paintComponent method to call the UI delegate object's
paint method. The paintComponent method passes a copy of the
Graphics object to the UI delegate object's paint method. This protects
the rest of the paint code from irrevocable changes.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
public class paintSwing extends Applet implements MouseMotionListener{
}
Output:
247
Exploring Swing and Controls
JLabel :
Constructors:
Constructor Description
Creates a JLabel instance with no image and
JLabel()
with an empty string for the title.
Creates a JLabel instance with the specified
JLabel(String s)
text.
Creates a JLabel instance with the specified
JLabel(Icon i)
image.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified
horizontalAlignment) text, image, and horizontal alignment.
Examople
In Swing In awt
import [Link].*; import [Link].*;
class LabelExample class LabelExample{
{ public static void main(String args[]){
public static void main(String args[]) Frame f= new Frame("Label
{ Example");
JFrame f= new JFrame("Label Label l1,l2;
Example"); l1=new Label("First Label.");
JLabel l1,l2; [Link](50,100, 100,30);
248
l1=new JLabel("First Label."); l2=new Label("Second Label.");
[Link](50,50, 100,30); [Link](50,150, 100,30);
l2=new JLabel("Second Label."); [Link](l1); [Link](l2);
[Link](50,100, 100,30); [Link](400,400);
[Link](l1); [Link](l2); [Link](null);
[Link](300,300); [Link](true);
[Link](null); }
[Link](true); }
}
}
Output:
ImageIcon
ImageIcon(String filename)
The icon and text associated with the label can be obtained by the following
methods:
Icon getIcon( )
String getText( )
The icon and text associated with a label can be set by these methods:
249
void setIcon(Icon icon)
void setText(String str)
Here, icon and str are the icon and text, respectively. Therefore, using setText(
) it is possible to change the text inside a label during program execution.
The following applet illustrates how to create and display a label containing
both an icon and a string. It begins by creating an ImageIcon object for the file
[Link], which depicts the flag for France. This is used as the second
argument to the JLabel constructor.
The first and last arguments for the JLabel constructor are the label text and
the alignment. Finally, the label is added to the content pane.
Output:
250
JTextField
JTextField is the simplest Swing text component. It is also probably its most
widely used text
component. JTextField allows you to edit one line of text. It is derived from
JTextComponent,
which provides the basic functionality common to Swing text components.
JTextField uses
the Document interface for its model.
Three of JTextField’s constructors are shown here:
Constructor Description
JTextField() Creates a new TextField
Creates a new TextField initialized with the
JTextField(String text)
specified text.
JTextField(String text, int Creates a new TextField initialized with the
columns) specified text and columns.
Creates a new empty TextField with the specified
JTextField(int columns)
number of columns.
Methods:
Methods Description
It is used to add the specified action
void addActionListener(ActionListener
listener to receive action events from
l)
this textfield.
It returns the currently set Action for
Action getAction() this ActionEvent source, or null if no
Action is set.
void setFont(Font f) It is used to set the current font.
It is used to remove the specified action
void
listener so that it no longer receives
removeActionListener(ActionListener l)
action events from this textfield.
251
Example:
import [Link].*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Java.");
[Link](50,100, 200,30);
t2=new JTextField("AWT ");
[Link](50,150, 200,30);
[Link](t1); [Link](t2);
[Link](400,400);
[Link](null);
[Link](true);
}
}
Output:
252
JTextField Example with ActionListener
(calculator)
import [Link].*;
import [Link].*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
[Link](50,50,150,20);
tf2=new JTextField();
[Link](50,100,150,20);
tf3=new JTextField();
[Link](50,150,150,20);
[Link](false);
b1=new JButton("+");
[Link](50,200,50,50);
b2=new JButton("-");
[Link](120,200,50,50);
[Link](this);
[Link](this);
[Link](tf1);[Link](tf2);[Link](tf3);[Link](b1);[Link](b2);
[Link](300,300);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e) {
String s1=[Link]();
String s2=[Link]();
int a=[Link](s1);
int b=[Link](s2);
int c=0;
if([Link]()==b1){
c=a+b;
}else if([Link]()==b2){
c=a-b;
}
253
String result=[Link](c);
[Link](result);
}
public static void main(String[] args) {
new TextFieldExample();
}}
Output:
The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action when the
button is pushed. It inherits AbstractButton class.
Constructors:
Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.
Methods:
Methods Description
254
button.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
class button extends JFrame implements ActionListener
{
JButton b1,b2,b3;
button()
{
[Link]("Swing window close operation");
[Link](400,400);
[Link](null);
[Link](true);
b1=new JButton("red");
b2=new JButton("blue");
b3=new JButton("green");
[Link]().setBackground([Link]);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](b1);
[Link](50,50,100,50);
[Link](b2);
[Link](200,50,100,50);
[Link](b3);
255
[Link](350,50,100,50);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
if([Link]()==b1)
{
getContentPane().setBackground([Link]);
}
if([Link]()==b2)
{
getContentPane().setBackground([Link]);
}
if([Link]()==b3)
{
getContentPane().setBackground([Link]);
}
}
}
class buttonEx
{
public static void main(String[] args) {
new button();
}
} OUTPUT:
JToggleButton
256
A toggle button looks just like a push button, but it acts differently because it
has two states: pushed and released. That is, when you press a toggle button,
it stays pressed rather than popping back up as a regular push button does.
When you press the toggle button a second time, it releases (pops up).
Therefore, each time a toggle button is pushed, it toggles between its two
states.
Constructors
Constructor Description
It creates an initially unselected toggle
JToggleButton()
button without setting the text or image.
It creates a toggle button where properties
JToggleButton(Action a)
are taken from the Action supplied.
It creates an initially unselected toggle
JToggleButton(Icon icon)
button with the specified image but no text.
JToggleButton(Icon icon, boolean It creates a toggle button with the specified
selected) image and selection state, but no text.
It creates an unselected toggle button with
JToggleButton(String text)
the specified text.
JToggleButton(String text, It creates a toggle button with the specified
boolean selected) text and selection state.
It creates a toggle button that has the
JToggleButton(String text, Icon
specified text and image, and that is initially
icon)
unselected.
JToggleButton(String text, Icon It creates a toggle button with the specified
icon, boolean selected) text, image, and selection state.
Example:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
257
setTitle("JToggleButton with ItemListener Example");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setJToggleButton() {
button = new JToggleButton("ON");
add(button);
}
private void setAction() {
[Link](this);
}
public void itemStateChanged(ItemEvent eve) {
if ([Link]())
[Link]("OFF");
else
[Link]("ON");
}
}.
Output:
Check Boxes
The JCheckBox class provides the functionality of a check box. Its immediate
superclass is JToggleButton, which provides support for two-state buttons, as
just described. JCheckBox defines several constructors.
Constructor Description
Creates an initially unselected check box button
JJCheckBox()
with no text, no icon.
258
Creates an initially unselected check box with
JChechBox(String s)
text.
JCheckBox(String text, Creates a check box with text and specifies
boolean selected) whether or not it is initially selected.
Creates a check box where properties are taken
JCheckBox(Action a)
from the Action supplied.
Example:
import [Link].*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
[Link](100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
[Link](100,150, 50,50);
[Link](checkBox1);
[Link](checkBox2);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:
259
JCheckBox Example with ItemListener
import [Link].*;
import [Link].*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
final JLabel label = new JLabel();
[Link]([Link]);
[Link](400,100);
JCheckBox checkbox1 = new JCheckBox("C++");
[Link](150,100, 50,50);
JCheckBox checkbox2 = new JCheckBox("Java");
[Link](150,150, 50,50);
[Link](checkbox1); [Link](checkbox2); [Link](label);
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("C++ Checkbox: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("Java Checkbox: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
260
JRadioButton
Constructor Description
Creates an unselected radio button with no
JRadioButton()
text.
Creates an unselected radio button with
JRadioButton(String s)
specified text.
JRadioButton(String s, boolean Creates a radio button with the specified text
selected) and selected status.
import [Link].*;
import [Link].*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
261
rb1=new JRadioButton("Male");
[Link](100,50,100,30);
rb2=new JRadioButton("Female");
[Link](100,100,100,30);
ButtonGroup bg=new ButtonGroup();
[Link](rb1);[Link](rb2);
b=new JButton("click");
[Link](100,150,80,30);
[Link](this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if([Link]()){
[Link](this,"You are Male.");
}
if([Link]()){
[Link](this,"You are Female.");
}
}
public static void main(String args[]){
new RadioButtonExample();
}}
JTabbedPane
JTabbedPane encapsulates a tabbed pane. It manages a set of components by
linking them with tabs. Selecting a tab causes the component associated with
262
that tab to come to the forefront. Tabbed panes are very common in the
modern GUI, and you have no doubt used them many times. Given the
complex nature of a tabbed pane, they are surprisingly easy to
create and use.
Constructor Description
Creates an empty TabbedPane with a default
JTabbedPane()
tab placement of [Link].
Creates an empty TabbedPane with a specified
JTabbedPane(int tabPlacement)
tab placement.
JTabbedPane(int tabPlacement, Creates an empty TabbedPane with a specified
int tabLayoutPolicy) tab placement and tab layout policy.
Example:
import [Link].*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
[Link](ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
[Link](50,50,200,200);
[Link]("main",p1);
[Link]("visit",p2);
[Link]("help",p3);
[Link](tp);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String[] args) {
new TabbedPaneExample();
263
}}
Output:
JScrollPane
JScrollPane is a lightweight container that automatically handles the scrolling
of another component. The component being scrolled can either be an
individual component, such as a table, or a group of components contained
within another lightweight container, such as a JPanel. In either case, if the
object being scrolled is larger than the viewable area, horizontal and/or vertical
scroll bars are automatically provided, and the component can be scrolled
through the pane. Because JScrollPane automates scrolling, it usually
eliminates the need to manage individual scroll bars.
Constructor Purpose
JScrollPane()
JScrollPane(Component) It creates a scroll pane. The Component parameter,
when present, sets the scroll pane's client. The two
JScrollPane(int, int) int parameters, when present, set the vertical and
JScrollPane(Component, horizontal scroll bar policies (respectively).
int, int)
264
Modifier Method Description
It sets the column header for
void setColumnHeaderView(Component)
the scroll pane.
It sets the row header for the
void setRowHeaderView(Component)
scroll pane.
void setCorner(String, Component) It sets or gets the specified
corner. The int parameter
specifies which corner and
must be one of the following
constants defined in
ScrollPaneConstants:
UPPER_LEFT_CORNER,
Component getCorner(String) UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
void setViewportView(Component) Set the scroll pane's client.
Example:
import [Link];
import [Link];
import [Link];
import [Link];
265
[Link](JFrame.EXIT_ON_CLOSE);
[Link](JScrollPane.HORIZONTAL_SCR
OLLBAR_ALWAYS);
[Link](JScrollPane.VERTICAL_SCROLLB
AR_ALWAYS);
[Link]().add(scrollableTextArea);
}
public static void main(String[] args) {
[Link](new Runnable() {
JList
266
The object of JList class represents a list of text items. The list of text items can
be set up so that the user can choose either one item or multiple items. It
inherits JComponent class.
Swing, the basic list class is called JList. It supports the selection of one or
more items from a list. Although the list often consists of strings, it is possible
to create a list of just about any object that can be displayed. JList is so widely
used in Java that it is highly unlikely that you have not seen one before.
Constructor Description
JList() Creates a JList with an empty, read-only, model.
Creates a JList that displays the elements in the
JList(ary[] listData)
specified array.
JList(ListModel<ary> Creates a JList that displays elements from the
dataModel) specified, non-null, model.
Methods Description
It is used to add a listener to
Void
the list, to be notified each
addListSelectionListener(ListSelectionListener
time a change to the selection
listener)
occurs.
It is used to return the
int getSelectedIndex()
smallest selected cell index.
It is used to return the data
model that holds a list of
ListModel getModel()
items displayed by the JList
component.
It is used to create a read-
void setListData(Object[] listData) only ListModel from an array
of objects.
import [Link].*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
[Link]("Item1");
[Link]("Item2");
[Link]("Item3");
267
[Link]("Item4");
JList<String> list = new JList<>(l1);
[Link](100,100, 75,75);
[Link](list);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new ListExample();
}}
JComboBox
Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class. A combo box normally displays one entry, but
it will also display a drop-down list that allows a user to select a different entry.
You can also create a combo box that lets the user enter a selection into the
text field.
Constructor Description
268
JComboBox(Object[] Creates a JComboBox that contains the elements in
items) the specified array.
Example:
import [Link].*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
[Link](50, 50,90,20);
[Link](cb);
[Link](null);
[Link](400,500);
[Link](true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
269
JMenuBar, JMenu and JMenuItem
The object of JMenu class is a pull down menu component which is displayed
from the menu bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items
used in a menu must belong to the JMenuItem or any of its subclass.
Example:
import [Link].*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
[Link](i1); [Link](i2); [Link](i3);
[Link](i4); [Link](i5);
[Link](submenu);
[Link](menu);
[Link](mb);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new MenuExample();
}}
Output:
270
JDialog
The JDialog control represents a top level window with a border and a title
used to take some form of input from the user. It inherits the Dialog class.
Constructor Description
It is used to create a modeless dialog without a
JDialog()
title and without a specified Frame owner.
It is used to create a modeless dialog with
JDialog(Frame owner)
specified Frame as its owner and an empty title.
JDialog(Frame owner, String It is used to create a dialog with the specified
title, boolean modal) title, owner Frame and modality.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
[Link]( new FlowLayout() );
JButton b = new JButton ("OK");
[Link] ( new ActionListener()
{
271
public void actionPerformed( ActionEvent e )
{
[Link](false);
}
});
[Link]( new JLabel ("Click button to continue."));
[Link](b);
[Link](300,300);
[Link](true);
}
public static void main(String args[])
{
new DialogExample();
}
}
---------------------------------------------Best of Luck-------------------------------------
272
public void actionPerformed( ActionEvent e )
{
[Link](false);
}
});
[Link]( new JLabel ("Click button to continue."));
[Link](b);
[Link](300,300);
[Link](true);
}
public static void main(String args[])
{
new DialogExample();
}
}
---------------------------------------------Best of Luck-------------------------------------
272