Chapter 9 The Java Foundation Classes (Swings)

snottybugbearSoftware and s/w Development

Nov 3, 2013 (3 years and 7 months ago)

161 views


Mastering Java 7 By Neeraj Sharma 9893017496

Chapter 9 The Java Foundation Classes (Swings)


Mastering Java 7 By Neeraj Sharma 9893017496

9.1 Introduction to

JFC and Swing


JFC is short for Java Foundation Classes, which include a group of features for building
gr
aphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java
applications. It is defined as containing the features shown in the table below.


Features of the Java Foundation Classes

Feature

Description

Swing GUI
Compon
ents

Includes everything from buttons to split panes to tables. Many
components are capable of sorting, printing, and drag and drop, to name a
few of the supported features.

Pluggable Look
-
and
-
Feel Support

The look and feel of Swing applications is plugg
able, allowing a choice
of look and feel. For example, the same program can use either the Java
or the Windows look and feel. Additionally, the Java platform supports
the GTK+ look and feel, which makes hundreds of existing look and
feels available to Swin
g programs. Many more look
-
and
-
feel packages
are available from various sources.

Accessibility API

Enables assistive technologies, such as screen readers and Braille
displays, to get information from the user interface.

Java 2D API

Enables developers to

easily incorporate high
-
quality 2D graphics, text,
and images in applications and applets. Java 2D includes extensive APIs
for generating and sending high
-
quality output to printing devices.

Internationalization

Allows developers to build applications th
at can interact with users
worldwide in their own languages and cultural conventions. With the
input method framework developers can build applications that accept
text in languages that use thousands of different characters, such as
Japanese, Chinese, or
Korean.

Table 9.1.1 Features of JFC

The Swing API is powerful, flexible


and immense. The Swing API has 18 public packages:


javax.accessibility

javax.swing.plaf

javax.swing.text

javax.swing

javax.swing.plaf.basic

javax.swing.text.html

javax.swing.bor
der

javax.swing.plaf.metal

javax.swing.text.html.parser

javax.swing.colorchooser

javax.swing.plaf.multi

javax.swing.text.rtf

javax.swing.event

javax.swing.plaf.synth

javax.swing.tree

javax.swing.filechooser

javax.swing.table

javax.swing.undo

Table 9.1.
2 Packages in Swing API

Fortunately, most programs use only a small subset of the API.


Mastering Java 7 By Neeraj Sharma 9893017496

9.2 Introduction to NetBeans IDE

Now before we get started learning the java swings I will first introduced you the NetBeans IDE.
Download and install the latest NetBea
ns IDE from
http://netbeans.org/index.html


Open the NetBeans IDE from programs Menu or by Double clicking on the NetBeans Icon.

9.2.1
Setting Up the Project

To create an IDE project:

1.

Start NetBeans IDE.

2.

In t
he IDE, choose File > New Project (Ctrl
-
Shift
-
N), as shown in the figure below
.


Figure 9.2.1 Creating New Project

3.

In the New
Project

wizard, e
xpand the Java category and select Java Application as
shown in the figure below. Then click Next.


Figure 9.2.2

Selecting Project Type

4.

In
t
he

Name and Location page of the wizard, do the following (as shown in the figure
below):

a.

In the Project Name field, type
HelloWorldApp
.

b.

In the Create Main Class field, type
helloworldapp.HelloWorldApp
.

c.

Leave the Set as Main Project checkbox selected.


Mastering Java 7 By Neeraj Sharma 9893017496


Figure 9.2.3 Filling Details for Project

5.

Click Finish.

6.

The project is created and opened in the IDE. You should see the following
components

as shown in figure 9.2.4
:

a.

The Projects window, which contains a tree view of the components of the
project, inc
luding source files, libraries that your code depends on, and so on.

b.

The Source Editor window with a file called
HelloWorldApp

open.

c.

The Navigator window, which you can use to quickly navigate between elements
within the selected class.

d.

The Tasks window
, which lists compilation errors as well other tasks that are
marked with keywords such as XXX and TODO.

7.

Adding Code
to

the Generated Source File

a.

Because you have left the Create Main Class checkbox selected in the New
Project wizard, the IDE has created
a skeleton class for you. You can add the
"Hello World!" message to the skeleton code by replacing the line:


// TODO code application logic here

with the line:


System.out.println("Hello World!");

b.

Save the change by choosing File >

Save.

c.

The file should look something

like the following code sample after the figure.



Mastering Java 7 By Neeraj Sharma 9893017496


Figure 9.2.4 Project Opened in NetBeans IDE

/*


* T
o change this template, choose Tools | Templates


* and open the template in the editor.


*/

package helloworldapp;

/**


* @author <your name>


*/

public class HelloWorldApp {


/**


* @param args the command line arguments


*/


public static
void main(String[] args) {


System.out.println("Hello World!");


}

}

Listing 9.2.1 Default Template


Mastering Java 7 By Neeraj Sharma 9893017496


8.

Compiling
and

Running the Program

a.

Because of the IDE's Compile on Save feature, you do not have to manually
compile your project in order to
run it in the IDE. When you save a Java source
file, the IDE automatically compiles it
.

b.

To run the program
Choose

Run > Run Main Project (F6).

c.

The next figure shows
what

you should now see.


Figure 9.2.5 Output Window

Congratulations! Your program works!

If there are compilation errors, they are marked with red
glyphs in the left and right margins of the Source Editor. The glyphs in the left margin indicate
errors for the corresponding lines. The glyphs in the right margin show all of the areas of the fil
e
that have errors, including errors in lines that are not visible. You can mouse over an error mark
to get a description of the error. You can click a glyph in the right margin to jump to the line with
the error.

9.

Building and Deploying the Application

a.

Onc
e you have
written

and test run your application, you can use the Clean and
Build command to build your application for deployment. When you use the
Clean and Build command, the IDE runs a build script that performs the
following tasks:

1.

Deletes any previou
sly compiled files and other build outputs.

2.

Recompiles the application and builds a JAR file containing the compiled
files.

b.

To build your application: Choose Run > Clean and Build Main Project (Shift
-
F11).

c.

You can view the build outputs by opening the F
iles window and expanding the
HelloWorldApp node. The compiled bytecode file HelloWorldApp.class is
within the build/classes/helloworldapp subnode. A deployable JAR file that
contains the HelloWorldAp
p.class is within the dist node as shown in following
fi
gure.




Mastering Java 7 By Neeraj Sharma 9893017496


Figure

9.2.6

Files Window

Now we will learn how to create and design a swing application for this we create a small
application that is a Celsius to Fahrenheit converter.

9.2.2
Setting up the CelsiusConverter Project

1.

To create a new project, lau
nch the NetBeans IDE and choose New Project from the File
menu

2.

Next, select General from the Categories column, and Java Application from the Projects
column

3.

Press the button labeled "Next" to proceed.

4.

Now enter "CelsiusConverterProject" as the project nam
e. You can leave the Project
Location and Project Folder fields set to their default values, or click the Browse button to
choose an alternate location on your system.

5.

Make sure to deselect the "Create Main Class" checkbox; leaving this option selected
gen
erates a new class as the main entry point for the application, but our main GUI window
(created in the next step) will serve that purpose, so checking this box is not necessary. Click
the "Finish" button when you are done.

6.

When the IDE finishes loading, y
ou will see a screen similar to the given in figure 9.2.7. All
panes will be empty except for the Projects pane in the upper left hand corner, which shows
the newly created project.


Mastering Java 7 By Neeraj Sharma 9893017496


Figure 9.2.7 Initial NetBeans Screen For the Project

7.

Now Add A JFrame F
orm as shown in figure 9.2.8.


Figure 9.2.8 Adding JFrame

8.

Next, type
CelsiusConverterGUI

as the class name, and
learn

as the package name. You
can actually name this package anything you want but here we used
learn
.


Mastering Java 7 By Neeraj Sharma 9893017496


Figure 9.2.9 Defining Name and Locati
on

9.

The remainder of the fields should automatically be filled in, as shown above. Click the
Finish button when you are done

10.

When the IDE finishes loading, the right pane will display a design
-
time, graphical view of
the
CelsiusConverterGUI
. It is on this s
creen that you will visually drag, drop, and
manipulate the various Swing components.

9.2.3
NetBeans IDE Basics

It is not necessary to learn every feature of the NetBeans IDE before exploring its GUI creation
capabilities. In fact, the only features that y
ou really need to understand are the
Palette
, the
Design Area
, the
Property Editor
, and the
Inspector
. We will discuss these features below.

9.2.3.1
The Palette


The Palette contains all of the components offered by the Swing API. You can probably already

guess what many of these components are for, even if this is your first time using them (
JLabel

is a text label,
JList

is a drop
-
down list, etc.)


Figure 9.2.3.1.1 The Palette Window


Mastering Java 7 By Neeraj Sharma 9893017496

From this list, our application will use only
JLabel

(a basic text lab
el),
JTextField

(for the user
to enter the temperature), and
JButton

(to convert the temperature from Celsius to Fahrenheit.)

9.2.3.2
The Design Area

The Design Area is where you will visually construct your GUI. It has two views:
source view
,
and
design v
iew
. Design view is the default, as shown below. You can toggle between views at
any time by clicking their respective tabs.


Figure 9.2.3.2 Design Area

The figure above shows a single
JFrame

object, as represented by the large shaded rectangle with
blue
border. Commonly expected behavior (such as quitting when the user clicks the "close"
button) is auto
-
generated by the IDE and appears in the source view between uneditable blue
sections of code known as
guarded blocks
.








Mastering Java 7 By Neeraj Sharma 9893017496


Figure 9.2.3.3 Source Window

9.2.3.3
The Property Editor


The Property Editor does what its name implies: it allows you to edit the properties of each
component. The Property Editor is intuitive to use; in it you will see a series of rows


one row
per property


that you can click a
nd edit without entering the source code directly. The
following figure shows the Property Editor for the newly added
JFrame

object
.



Mastering Java 7 By Neeraj Sharma 9893017496


F
igure 9.2.3.3.1 The Property Window

The screenshot above shows the various properties of this object, such as background color,
foreground color, font, and cursor.

9.2.3.4
The Inspector

The last component of the NetBeans IDE that we will use in this lesso
n is the Inspector:


Figure 9.2.3.3.5 The Inspector Window

The Inspector provides a graphical representation of your application's compo
nents. We will use
the Inspector only once, to change a few variable names to something other than their defaults.


Mastering Java 7 By Neeraj Sharma 9893017496

9.2.3.5
Creating the CelsiusConverter GUI

First, set the title of the application's
JFrame

to "Celsius Converter", by single
-
clicking the
JFr
ame

in the Inspector then, set its title with the Property Editor. You can set the title by either
double
-
clicking the title property and entering the new text directly, or by clicking the
button
and entering the title in the provided field. Or, as a shortcut, you could single
-
click the
JFrame

of
the inspector and enter its new text directly without using the property editor.

9.2.3.6
Add a

JTextField


Next, drag a
JTextField

from the Palette to the upper left corner of the Design Area. As you
approach the upper left corner, the GUI builder provides visual cues (dashed lines) that suggest
the appropriate spacing. Using these cues as a guide,

drop a
JTextField

into the upper left hand
corner of the window as shown below:




Figure 9.2.3.6.1 Adding JTextField

9.2.3.7
Add a JL
ab
el

Next, drag a
JLabel

onto the Design Area. Place it to the right of the
JTextField
, again
watching for visual cues that suggest an appropriate amount of spacing. Make sure that text base
for this component is aligned with that of the
JTextField
. The visu
al cues provided by the IDE
should make this easy to determine.


Figure 9.2.3.7.1

Adding JLabel

9.2.3.8
Add a JButton

Next, drag a
JButto
n

from the Palette and position it to the left and underneath the
JTextField
.
Again, the visual cues help guide it into place.



Figure 9
.2.3.8.1 Adding JButton


Mastering Java 7 By Neeraj Sharma 9893017496

9.2.3.9
Add a Second JLabel


Figure 9.2.3.9.1 Adding Second JLabel

Finally, add a second
JLabel
, repeating the pr
ocess in step 2. Place this second label to the right
of the
JButton
, as shown above.

9.2.3.10
Adjusting the CelsiusConverter GUI

With the GUI components now in place, it is time to make the final adjustments. There are a few
different ways to do this; the

order suggested here is just one possible approach.


Step 1: Set the Component Text

First, double
-
click the
JTextField

and
JButton

to change the default text that was inserted by
the IDE. When you erase the text from the
JTextField
, it will shrink in size

as shown below.
Change the text of the
JButton

from "JButton1" to "Convert." Also change the top
JLabel

text
to "Celsius" and the bottom to "Fahrenheit."

Step 2: Set the Component Size

Next, shift
-
click the
JTextField

and
JButton

components. This will hig
hlight each showing
that they are selected. Right
-
click (control
-
click for mac users) Same Size
-
> Same Width. The
components will now be the same width, as shown below. When you perform this step, make
sure that
JFrame

itself is not also selected. If it i
s, the Same Size menu will not be active.

Step 3: Remove Extra Space

Finally, grab the lower right
-
hand corner of the
JFrame

and adjust its size to eliminate any extra
whitespace. Note that if you eliminate all of the extra space (as shown below) the titl
e (which
only appears at runtime) may not show completely. The end
-
user is free to resize the application
as desired, but you may want to leave some extra space on the right side to make sure that
everything fits correctly. Experiment, and use the screensh
ot of the finished GUI as a guide.


Figure 9.2.3.10.1 Complete GUI


Mastering Java 7 By Neeraj Sharma 9893017496

The GUI portion of this application is now complete! If the NetBeans I
DE has done its job, you
should feel that creating this GUI was a simple, if not trivial, task. But take a minute to click on
the source tab; you might be surprised at the amount of code that has been generated. To see the
code in its entirety, scroll up a
nd down within the IDE as necessary. You can expand or collapse
certain blocks of code (such as method bodies) by clicking the + or
-

symbol on the left
-
hand
side of the source editor.

9.2.3.11
Adding the Application Logic

The figure below shows the defaul
t variable names as they currently appear within the Inspector.
For each component, the variable name appears first, followed by the object's type in square
brackets. For example,
jTextField1 [JTextField]

means that "jTextField1" is the variable
name and "
JTextField" is its type.


Figure 9.2.3.11.1 Inspector Window


The default names are not very relevant in the context of this application,

so it makes sense to
change them from their defaults to something that is more meaningful. Right
-
click each variable
name and choose "Change variable name." When you are finished, the variable names should
appear as follows:


Fig
ure 9.2.3.11.2 Change Variable Names

The new variable names are "tempTextField", "celsiusLabel", "convertButton", and
"fahrenheitLabel." Each change that you make
in the Inspector will automatically propagate its
way back into the source code. You can rest assured that compilation will not fail due to typos or
mistakes of that nature


mistakes that are common when editing by hand.


Step 2: Register the Event Listen
ers


When an end
-
user interacts with a Swing GUI component (such as clicking the Convert button),
that component will generate a special kind of object


called an
event object



which it will

Mastering Java 7 By Neeraj Sharma 9893017496

then broadcast to any other objects that have previously regist
ered themselves as
listeners

for
that event. The NetBeans IDE makes event listener registration extremely simple:



Figure 9.2.3.11.3 Registering Event Listener

In the Design Area, click on the Convert button to select it. Make sure that
only

the Convert
button is selected (if the JFrame itself is also selected, this step will not work.) Right
-
click the
Convert button and choose Events
-
> Action
-
> ActionPerformed. This will generate the required
event
-
handling code, leaving you with empty method bodies in

which to add your own
functionality:


Step 3: Add the Temperature Conversion Code

//Parse degrees Celsius as a double and convert to Fahrenheit.

int tempFahr = (int)((Double.parseDouble(tempTextField.getText()))


* 1.8 + 32);


fahrenheitLa
bel.setText(tempFahr + " Fahrenheit");


With the conversion code in place, the application is now complete.

Step 4: Run the Application

Running the application is simply a matter of choosing Run
-
> Run Main Project within the
NetBeans IDE. The first time
you run this application, you will be prompted with a dialog asking
to set
CelsiusConverterGUI

as the main class for this project. Click the OK button, and when
the program finishes compiling, you should see the application running in its own window.

Cong
ratulations! You have completed your first Swing application!


Mastering Java 7 By Neeraj Sharma 9893017496

9.3 Using Swing Components

9.3.1
Using JFrame


A Frame is a top
-
level window with a title and a border. The size of the frame includes any area
designated for the border.
A frame, implemented
as an instance of the JFrame class, is a window
that has decorations such as a border, a title, and supports button components that close or
iconify the window. Applications with a GUI usually include at least one frame. Applets
sometimes use frames, as we
ll.


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;


public class FrameDemo {



public
static void main(String[] args)


{



//Create and set up the window.


JFrame frame = new JFrame("FrameDemo");


frame.setDefaultCl
oseOperation(JFrame.EXIT_ON_CLOSE);



//Display the window.


frame.pack();


frame.setVisible(true);



}

}

Listing 9.3.1.1 Using JFrame

9.3.2
Using JLabel

With the JLabel class, you can display unselectable text and images. If you ne
ed to create a
component that displays a string, an image, or both, you can do so by using JLabel.

By
specifying HTML code in a label's text, you can give the label various characteristics such as
multiple lines, multiple fonts or multiple colors. If the l
abel uses just a single color or font, you
can avoid the overhead of HTML processing by using the setForeground or setFont method
instead.

import javax.swing.*;

public class HelloLabel extends JFrame {



public HelloLabel() {


super("JLabel Demo"
);


JLabel label1 = new JLabel("Neeraj Sharma Welcomes you");


setSize(200, 100);


add(label1);


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


setVisible(true);


}


public static void main(String args[]) {



HelloLabel hl = new HelloLabel(); }}

Listing 9.3.2.1 Using JLabel


Mastering Java 7 By Neeraj Sharma 9893017496

Creating a JLabel


There are six constructors for JLabel:


1.

public JLabel()

a.

JLabel label = new JLabel();

2.

public JLabel(Icon image)

a.

Icon icon = new ImageIcon("dog.jpg");

b.

JLabel label = n
ew JLabel(icon);

3.

public JLabel(Icon image, int horizontalAlignment)

a.

Icon icon = new ImageIcon("dog.jpg");

b.

JLabel label = new JLabel(icon, JLabel.RIGHT);

4.

public JLabel(String text)

a.

JLabel label = new JLabel("Dog");

5.

public JLabel(String text, int horizontalA
lignment)

a.

JLabel label = new JLabel("Dog", JLabel.RIGHT);

b.

public JLabel(String text, Icon icon, int horizontalAlignment)

6.

Icon icon = new ImageIcon("dog.jpg");

a.

JLabel label = new JLabel("Dog", icon, JLabel.RIGHT);

With the constructors for JLabel, you can c
ustomize any of three properties of the JLabel: text,
icon, or horizontalAlignment. By default, the text and icon properties are empty, whereas the
initial horizontalAlignment property setting depends on the constructor arguments. These
settings can be any

of JLabel.LEFT, JLabel.CENTER, or JLabel.RIGHT. In most cases not
specifying the horizontalAlignment setting results in a left
-
aligned label. However, if only the
initial icon is specified, then the default alignment is centered.

9.3.3
Using JButton

JButt
on is a replacement of AWT Button but it adds more functionality than Button. The JButton
class has five constructors:


1.

public JButton()

a.

JButton button = new JButton();

2.

public JButton(Icon image)

a.

Icon icon = new ImageIcon("dog.jpg");

b.

JButton button = new J
Button(icon);

3.

public JButton(String text)

a.

JButton button = new JButton("Dog");

4.

public JButton(String text, Icon icon)

a.

Icon icon = new ImageIcon("dog.jpg");

b.

JButton button = new JButton("Dog", icon);

5.

public JButton(Action action)

a.

Action action = ...;

b.

JButto
n button = new JButton(action);


Mastering Java 7 By Neeraj Sharma 9893017496

import java.awt.Color;

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.*;

public class ColorChange extends JFrame implements ActionListener {



JButt
on b1, b2, b3;


public ColorChange() {


super("JButton Demo");


b1 = new JButton("Red");


b2 = new JButton("Green");


b3 = new JButton("Blue");


b1.setMnemonic('R'); //alt+r


b2.setMnemonic('G');//alt+g



b3.setMnemonic('B');//alt+b


b1.setToolTipText("Red");


b2.setToolTipText("Green");


b3.setToolTipText("Blue");


b1.addActionListener(this);


b2.addActionListener(this);


b3.addActionListener(this);


setL
ayout(new FlowLayout(FlowLayout.LEFT));


setSize(300, 200);


add(b1);


add(b2);


add(b3);


b1.requestFocus();


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


setVisible(true);


}


public void actionP
erformed(ActionEvent e) {


Object source = e.getSource();


if (source == b1) {


this.getContentPane().setBackground(Color.RED);


}


if (source == b2) {


this.getContentPane().setBackground(Color.GREEN);



}


if (source == b3) {


this.getContentPane().setBackground(Color.BLUE);


}


}


public static void main(String args[]) {


ColorChange cc = new ColorChange();


}

}

Listing 9.3.3.1 Using JButton



Mastering Java 7 By Neeraj Sharma 9893017496

9.3.4
Using JTe
xtField

A text field is a basic text control that enables the user to type a small amount of text. When the
user indicates that text entry is complete (usually by pressing Enter), the text field fires an
ActionEvent. It has following four constructors:


1.

pu
blic JTextField()

2.

public JTextField(int columns)

3.

public JTextField(String text)

4.

public JTextField(String text,int columns)


import java.awt.FlowLayout;

import javax.swing.*;

import java.awt.event.*;


public class TextFieldDemo extends JFrame implements Act
ionListener {


JTextField t;


public TextFieldDemo() {


super("JTextField Demo");


setSize(300, 300);


setVisible(true);


t = new JTextField("Type Here and press enter");


setLayout(new FlowLayout());


add(t)
;


t.addActionListener(this);


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


}


public void actionPerformed(ActionEvent e) {


JOptionPane.showMessageDialog(this, t.getText());


}


public static void main(String args[]) {


TextFieldDemo tfd = new TextFieldDemo();


}

}

Listing 9.3.4.1 Using JTextField

9.3.5
Using JPasswordField

The JPasswordField class has the same five constructors as the JTextField
.


import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.*;


public class PasswordFieldDemo extends JFrame implements ActionListener {


JPasswordField pf;


JButton b;



public PasswordFieldDemo() {


super("JPasswordField Demo");


se
tVisible(true);


setLayout(new FlowLayout());


Mastering Java 7 By Neeraj Sharma 9893017496


b = new JButton("Login");


pf = new JPasswordField();


pf.setColumns(15);


b.addActionListener(this);


pf.addActionListener(this);


b.requestFocus();


ad
d(pf);


add(b);


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


pack();


}


public void actionPerformed(ActionEvent e) {


JOptionPane.showMessageDialog(this, "Encrypted Password is " +
pf.getPassword());


char[] c

= pf.getPassword();


String str = new String(c);


JOptionPane.showMessageDialog(this, "Orignal Text = " + str);


}


public static void main(String args[]) {


PasswordFieldDemo pfd = new PasswordFieldDemo();


}

}

Listing 9.3.5
.1 Using JPasswordField

9.3.6
Using
JTextArea

The JTextArea is used to input multiline text input. The java.awt.TextArea internally handles
scrolling. JTextArea is different in the sense that it doesn’t manage scrolling but implements the
swing Scrollable
interface. This allows it to be placed inside a JScrollPane if scrolling behavior
is desired and used directly if scrolling is not required.

It has following constructors.


JTextArea()

Constructs a new TextArea.

JTextArea(Document doc)

Constructs a new JT
extArea with the given
document model, and defaults for all of the
other arguments (null, 0, 0).

JTextArea(Document doc, String text,int
rows, int columns)

Constructs a new JTextArea with the
specified number of rows and columns, and
the given model.

JTe
xtArea(int rows,int columns)

Constructs a new empty TextArea with the
specified number of rows and columns.

JTextArea(String text)

Constructs a new TextArea with the specified
text displayed.

JTextArea(String text, int rows,int columns)

Constructs a new
TextArea with the specified
text and number of rows and columns

Table 9.3.6.1 Constructers of JTextArea





The JTextArea Cla
ss has the following properties


Mastering Java 7 By Neeraj Sharma 9893017496



void

append(String str)


Appends the given text to the end of the document.

protected

Document

createDefaultModel()


Creates the default implementation of the model to be used at
construction if one isn't explicitly given.


AccessibleCon
text

getAccessibleContext()


Gets the AccessibleContext associated with this JText
Area.


int

getColumns()


Returns the number of columns in the TextArea.

protected

int

getColumnWidth()


Gets column width.


int

getLineCount()


Determines the number of lines contained in the area.


int

getLineEndOffset(i
nt line)


Determines the offset of the end of the given line.


int

getLineOfOffset(int offset)


Translates an offset into the components text to a line number.


int

getLineStartOffset(int line)


Determines the offset of the
start of the given line.


boolean

getLineWrap()



Gets the line
-
wrapping policy of the text area.

Dimension

getPreferredScrollableViewportSize()


Returns the preferred size of the viewport if this component is
embedded in a JScrollPan
e.

Dimension

getPreferredSize()


Returns the preferred size of the TextArea.

protected

int

getRowHeight()


Defines the meaning of the height of a row.


int

getRows()


Returns the number of rows in the TextArea.


boolean

g
etScrollableTracksViewportWidth()


Returns true if a viewport should always force the width of this
Scrollable to match the width of the viewport.


int

getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int
direction)


Components that display logical rows or columns should compute the
scroll increment that will completely expose one new row or column,
depending on the value of orientation.


int

getTabSize()


Gets the number of characters used to expand tabs.

String

getUIClassID()


Returns the class ID for the UI.


boolean

getWrapStyleWord()


Gets the style of wrapping used if the text area is
wrapping lines.


void

insert(String str, int pos)


Mastering Java 7 By Neeraj Sharma 9893017496


Inserts the specified text at the sp
ecified position.

protected

Str
ing

paramString()


Returns a string representation of this JTextArea.


void

replaceRange(String str, int start, int end)


Replaces text from the indicated start to end position with the new
text specifi
ed.


void

setColumns(int columns)


Sets the number of columns for this TextArea.


void

setFont(Font f)


Sets the current font.


void

setLineWrap(boolean wrap)


Sets the line
-
wrapping policy of the text area.


void

setRows(
int rows)


Sets the number of rows for this TextArea.


void

setTabSize(int size)


Sets the number of characters to expand tabs to.


void

setWrapStyleWord(boolean word)


Sets the style of wrapping used if the text area is wra
pping lines.

Table 9.3.6.2 Properties/Methods of JTextArea

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;


public class TextAreaDemo extends JFrame implements ActionListener {


String str = null;


JTextArea t1;


JButton copy, c
ut, paste;



public TextAreaDemo() {


setTitle("JTextArea Demo");


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


copy = new JButton("Copy");


cut = new JButton("Cut");


paste = new JButton("Paste");


t1 = new

JTextArea(10, 30);


JScrollPane jPane = new JScrollPane(t1); //this enables t1 to scroll text



t1.setLineWrap(true);


copy.addActionListener(this);


cut.addActionListener(this);


paste.addActionListener(this);


Conta
iner cPane = getContentPane();


JPanel p1 = new JPanel();


p1.add(cut);


p1.add(copy);


p1.add(paste);


cPane.add(p1, "South");


cPane.add(jPane, "Center");


setVisible(true);


pack();


}


Mastering Java 7 By Neeraj Sharma 9893017496


publi
c void actionPerformed(ActionEvent e) {



String cmd = e.getActionCommand();


if (cmd.equals("Cut")) {


str = t1.getSelectedText();


t1.replaceRange("", t1.getSelectionStart(), t1.getSelectionEnd());


} else if (cm
d.equals("Copy")) {


str = t1.getSelectedText();


} else if (cmd.equals("Paste")) {


t1.insert(str, t1.getSelectionStart());


}


}


public static void main(String args[]) {


TextAreaDemo tad = new TextAreaDe
mo();


}

}

Listing 9.3.6.1 Using JTextArea

9.3.7
Using JCheckBox

The JCheckBox class provides support for check box buttons. You can also put check boxes in
menus, using the JCheckBoxMenuItem class. Because JCheckBox and JCheckBoxMenuItem
inherit from A
bstractButton, Swing check boxes have all the usual button characteristics, as
discussed earlier in this section. For example, you can specify images to be used in check boxes.


Check boxes are similar to radio buttons but their selection model is differen
t, by convention.
Any number of check boxes in a group


none, some, or all


can be selected. A group of radio
buttons, on the other hand, can have only one button selected.

This class has following constructors:


JCheckBox()


Creates an initial
ly unselected check box button with no text, no icon.

JCheckBox(Action a)


Creates a check box where properties are taken from the Action supplied.

JCheckBox(Icon icon)


Creates an initially unselected check box with an icon.

JCheckB
ox(Icon icon, boolean selected)


Creates a check box with an icon and specifies whether or not it is initially selected.

JCheckBox(String text)


Creates an initially unselected check box with text.

JCheckBox(String text, boolean selec
ted)


Creates a check box with text and specifies whether or not it is initially selected.

JCheckBox(String text, Icon icon)


Creates an initially unselected check box with the specified text and icon.

JCheckBox(String text, Icon icon
, boolean selected)


Creates a check box with text and icon, and specifies whether or not it is initially
selected.

Table 9.3.7.1 Constructers of JCheckBox


Mastering Java 7 By Neeraj Sharma 9893017496

And has following methods


AccessibleContext

getAccessibleContext()


Gets the A
ccessibleContext associated with this JCheckBox.

String

getUIClassID()


Returns a string that specifies the name of the L&F class that renders
this component.


boolean

isBorderPaintedFlat()


Gets the value of the borderPaintedFlat pro
perty.

protected
String

paramString()


Returns a string representation of this JCheckBox.


void

setBorderPaintedFlat(boolean b)


Sets the borderPaintedFlat property, which gives a hint to the look
and feel as to the appearance of the
check box border.


void

updateUI()


Resets the UI property to a value from the current look and feel.

Table 9.3.7.2 Properties/Methods of JCheckBox

import java.awt.Font;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

i
mport javax.swing.JCheckBox;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

public class CheckBoxDemo extends JFrame implements ActionListener {


JLabel fontLabel = new JLabel("The quick brown fox jumps over the lazy dog")
;


JCheckBox bold = new JCheckBox("Bold");


JCheckBox italic = new JCheckBox("Italic");



public CheckBoxDemo() {


setTitle("CheckBoxDemo");


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JPanel p = new JPanel();


p.
add(bold);


p.add(italic);


bold.addActionListener(this);


italic.addActionListener(this);


add(p, "South");


add(fontLabel, "Center");


setVisible(true);


pack();


}


public void actionPerformed(Actio
nEvent evt) {

int m = (bold.isSelected() ? Font.BOLD : 0) + (italic.isSelected() ? Font.ITALIC : 0);


fontLabel.setFont(new Font("SansSerif", m, 12));


}


public static void main(String[] args) {


CheckBoxDemo cbd = new CheckBoxDemo();

}}

Listing 9.3.7.1 Using JCheckBox


Mastering Java 7 By Neeraj Sharma 9893017496

9.3.8
Using JRadioButton

Radio buttons are groups of buttons in which, by convention, only one button at a time can be
selected. The Swing release supports radio buttons with the JRadioButton and ButtonGroup
classes.

To put a radio button in a menu, use the JRadioButtonMenuItem class. Other ways of
displaying one
-
of
-
many choices are combo boxes and lists. Radio buttons look similar to check
boxes, but, by convention, check boxes place no limits on how many items can b
e selected at a
time. Because JRadioButton inherits from AbstractButton, Swing radio buttons have all the usual
button characteristics, as discussed earlier in this section. For example, you can specify the
image displayed in a radio button. JRadioButton c
lass has following constructor to create radio
button


JRadioButton()


Creates an initially unselected radio button with no set text.

JRadioButton(Action a)


Creates a radiobutton where properties are taken from the Action supplied.

J
RadioButton(Icon icon)


Creates an initially unselected radio button with the specified image but no text.

JRadioButton(Icon icon, boolean selected)


Creates a radio button with the specified image and selection state, but no text.


J
RadioButton(String text)


Creates an unselected radio button with the specified text.

JRadioButton(String text, boolean selected)


Creates a radio button with the specified text and selection state.

JRadioButton(String text, Icon icon
)


Creates a radio button that has the specified text and image, and that is initially
unselected.

JRadioButton(String text, Icon icon, boolean selected)


Creates a radio button that has the specified text, image, and selection state.

Table 9.3.8
.1

Constructers of JRadioButton

And has following methods:

Access
ibleContext

getAccessibleContext
()



Gets the AccessibleContext associated with this JRadioButton.


String

getUIClassID
()



Returns the name of the L&F class that renders this component.

pr
otected

String

paramString
()



Returns a string representation of this JRadioButton.


void

updateUI
()



Resets the UI property to a value from the current look and feel.

Table 9.3.8.2 Properties/Methods of JRadioButton


Mastering Java 7 By Neeraj Sharma 9893017496

import java.awt.Container;

import java.awt.GridLayout;

import javax.swing.But
tonGroup;

import javax.swing.JFrame;

import javax.swing.JRadioButton;


public class SwingRadioButtonTest{


public static void main(String args[]) {


JFrame frame = new JFrame();


Container contentPane = frame.getContentPane();


contentPane.setLay
out(new GridLayout(0, 1));


ButtonGroup group = new ButtonGroup();


JRadioButton option = new JRadioButton("French Fries", true);


group.add(option);


contentPane.add(option);


option = new JRadioButton("Onion Rings", false);


group.add(o
ption);


contentPane.add(option);


option = new JRadioButton("Ice Cream", false);


group.add(option);


contentPane.add(option);


frame.setSize(200, 200);


frame.setVisible(true);


}

}

Listing 9.3.8.1 Using

JRadioButton

9.4
Advanced Swing

Programming

9.4.1
Using JList


A JList presents the user with a group of items, displayed in one or more columns, to choose
from. Lists can have many items, so they are often put in scroll panes. In addition to lists, the
following Swing components presen
t multiple selectable items to the user: combo boxes, menus,
tables, and groups of check boxes or radio buttons. To display hierarchical data, use a tree.


The JList class has following constructors:


JList
()



Constructs a
JList

with an empty, read
-
only, model.

JList
(
ListModel

dataModel)




Constructs a
JList

that displays elements from the specified,
non
-
null
, model.

JList
(
Object
[]

listData)



Constructs a
JList

that displays the elements in the specified array.

JList
(
Vector
<?>

listData)



Constructs a
JList

that displays the elements in the specified
Vector
.

Table 9.4.1.1 JList Constructers




Mastering Java 7 By Neeraj Sharma 9893017496


Has following fields:


static

int

HORIZONTAL_WRAP



Indicates a "newspaper style" layout with cells flowing horizontally then
vertically.

static

int

VERTICAL



Indicates a vertical layout of cells, in a single column; the default layout.

static

int

VERTICAL_WRAP



Indicates a "newspaper style" layout with cells flowing vertically then
horizontally.

Table 9.4.1.2 JList Fields

And has
following methods:



void

addListSelectionListener
(
ListSelectionListener

listene
r)



Adds a listener to the list, to be no
tified each time a change to
the selection occurs; the preferred way of listening for selection
state changes.


void

addSelectionInterval
(int

anchor, int

lead)



Sets the selection to be the union of the specified interval
with current selection.


void

clearSelection
()



Clears the selection; after calling this method,
isSelectionEmpty

will return
true
.

protected

ListSele
ctionModel

createSelectionModel
()



Returns an instance of
DefaultListSelectionModel
; called
during construction to initialize the list's selection model property.


void

ensureIndexIsVisible
(int

index)



Scrolls the list within an enclosing viewport to make the
specified cell completely visible.

protected

void

fireSelectionValueChanged
(int

firstIndex,
int

lastIndex, boolean

isAdjusting)



Notifies

ListSelectionListener
s added directly to the list
of selection changes made to the selection model.


AccessibleContext

getAccessibleContext
()



Gets the
AccessibleCont
ext

associated with this
JList
.


int

getAnchorSelectionIndex
()



Returns the anchor selec
tion index.


Rectangle

getCellBounds
(int

index0, int

index1)



Returns the bounding rectangle, in the list's coordinate
system, for the range of cells specified by the two indices.


ListCellRenderer

getCellRenderer
()



Returns the object responsible for painting list items.


boolean

getDragEnabled
()



Returns whether or not automatic drag handling is enabled.


JList.DropLocation

getDropLocation
()



Returns the

location that this component should visually
indicate as the drop location during a DnD operation over the

Mastering Java 7 By Neeraj Sharma 9893017496

component, or
null

if no location is to currently be shown.


DropMode

getDropMode
()



Returns t
he drop mode for this component.


int

getFirstVisibleIndex
()



Returns the smallest list ind
ex that is currently visible.


int

getFixedCellHeight
()



Returns the value of the
fixedCellHe
ight

property.


int

getFixedCellWidth
()



Returns the value of the
fixedCellWidth

property.


i
nt

getLastVisibleIndex
()



Returns the largest list index that is currently visible.


int

getLayoutOrientation
()



Returns the layout orientation property for the list:
VERTICAL

if the l
ayout is a single column of cells,
VERTICAL_WRAP

if the
layout is "newspaper style" with the content flowing vertically then
horizontally, or
HORIZONTAL_WRAP

if the layout is "newspaper
style" with the content flowing horizontally then vertically.


int

getLeadSelectionIndex
()



Returns the lead selection index.


ListSelectionListener
[]

getListSelectionListeners
()



Returns an array of all the
ListSelectionListener
s added
to this
JList

by way of
addListSelectionListener
.


int

getMaxSelectionIndex
()



Returns the largest selected cell index, or
-
1

if the selection
is empty.


int

getMinSelectionIndex
()



Returns the smallest selected cell index, or
-
1

if the selection
is empty.


ListModel

getModel
()



Returns the data model that holds the list of items displayed
by the
JList

component.


int

getNextMatch
(
String

prefix, int

startIndex,
Position.Bias

bias)



Returns t
he next list element whose
toString

value starts
with the given prefix.


Dimension

getPreferredScrollableViewportSize
()



Computes the size of viewport needed to display
visibleRowCoun
t

rows.


Object

getPrototypeCellValue
()



Returns the "prototypical" cell value
--

a value used to
calculate a fixed width and height for cells.


int

getScrollableBlockIncrement
(
Rectangle

visibleRect,
int

orientation, int

direction)



Returns the distance to scroll to expose the next or previous
block.


boolean

getScrollableTracksViewportHeight
()



Returns
true

if this
JList

is displayed in a
JViewport

and
the viewport is taller than th
e list's preferred height, or if the layout
orientation is
VERTICAL_WRAP

and
visibleRowCount <= 0
;

Mastering Java 7 By Neeraj Sharma 9893017496

otherwise returns
false
.


boolean

getScrollableTracksViewportWidth
()



Returns
true

if this
JList

is displayed in a
JViewport

and
the viewport is wider than the list's preferred width, or if the layout
orientation is
HORIZONTAL_WRAP

and
visibleRowCount <= 0
;
otherwise returns
false
.


int

getScrollableUni
tIncrement
(
Rectangle

visibleRect,
int

orientation, int

direction)



Returns the distance to scro
ll to expose the next or previous
row (for vertical scrolling) or column (for horizontal scrolling).


int

getSelectedIndex
()



Returns the smallest selected cell index;
the selection

when
only a single item is selected in the list.


int[]

getSelectedIndices
()



Returns an array of all of the selected indices, in increasing
order.


Object

getSelectedValue
()



Returns the value for the smalle
st selected cell index;
the
selected value

when only a single item is selected in the list.


Object
[]

getSelectedValues
()



Returns an array of all the selected values, in increasing order
based on thei
r indices in the list.


Color

getSelectionBackground
()



Returns the color used to draw the background of selected
items.


Color

getSelectionForeground
()



Returns the color used to draw the foreground of selected
items.


int

getSelectionMode
()




Returns the current selection mode for the list.


ListSelectionModel

getSelectionModel
()



Returns the current selection model.


String

getToolTipText
(
MouseEvent

event)



Returns the tooltip t
ext to be used for the given event.


ListUI

getUI
()



Returns the
ListUI
, the look and feel object that renders this
component.


String

getUIClassID
()




Returns
"ListUI"
, the
UIDefaults

key used to look up the
name of the
javax.swing.plaf.ListUI

class that defines the look
and feel for this component.


boolean

getValueIsAdjusting
()



Returns the value of the selection model's
isAdjusting

property.


int

getVisibleRowCount
()



Returns the value of the
visibleRowCount

property.


Point

indexToLocation
(int

index)



Returns the origin of the
specified item in the list's coordinate
system.


Mastering Java 7 By Neeraj Sharma 9893017496


boolean

isSelectedIndex
(int

index)



Returns
true

if the specified index is selected, else
false
.


boolean

isSelectionEmpty
()



Returns
true

if nothing is selected, else
false
.


int

locationToIndex
(
Point

location)



Returns the cell index closest to the given location in the list's
coordinate system.

protected

String

paramString
()



Returns a
String

representation of this
JList
.


void

removeListSelectionListener
(
ListSelectionListener

list
ener)



Removes a selection listener from the list.


void

removeSelectionInterval
(int

index0, int

index1)



Sets the selection to be the set difference of the specified
interval and the current selection.


void

setCellRenderer
(
ListCellRenderer

cellRenderer)



Sets the delegate that is used to paint each cell in the list.


void

setDragEnabled
(boolean

b)



Turns on or off automatic drag handling.


void

setDropMode
(
DropMode

dropMode)



Sets the drop mode for this component
.


void

setFixedCellHeight
(int

height)



Sets a fixed value to be used for the height of ev
ery cell in
the list.


void

setFixedCellWidth
(int

width)



Sets a fixed value to be used for

the width of every cell in the
list.


void

setLayoutOrientation
(int

layoutOrientation)




Defines the way list cells are layed out.


void

setListData
(
Object
[]

listData)



Constructs a read
-
only
ListModel

from an array of objects,
and calls
setModel

with this model.


void

setListData
(
Vector
<?>

listData)



Constructs a read
-
only
ListModel

from a
Vector

and calls
setModel

with this model.


void

setModel
(
ListModel

model)



Sets the model that represents the contents or "value" of the
list, notifies property change listeners, and then clears the list's
selection.


void

setPrototypeCellValue
(
Object

prototypeCellValue)



Sets the
prototypeCellValue

property, and then (if the new
value is
non
-
null
), computes the
fixedCellWidth

and
fixedCellHeight

properties by requesting the cell renderer
component for the given value (and index

0) from the cell renderer,
and using that component's preferred size.


void

setSelectedIndex
(int

inde
x)



Selects a single cell.


void

setSelectedIndices
(int[]

indices)



Changes th
e selection to be the set of indices specified by the

Mastering Java 7 By Neeraj Sharma 9893017496

given array.


void

setSelec
tedValue
(
Object

anObject,
boolean

shouldScroll)



Selects the specified object from the list.


v
oid

setSelectionBackground
(
Color

selectionBackground)



Sets the color used to draw the background of selected items,
which cell renderers can use fill selected cells.


void

setSelectionForeground
(
Color

selectionForeground)



Sets the color used to draw the foreground of selected items,
which cell renderers can use to render text and graphics.


void

setSelectionInterval
(int

anchor, int

lead)



Selects the specified interval.


void

setSelectionMode
(int

selectionMode)



Sets the selection mode for the list.


void

setSelectionModel
(
ListSelectionModel

selectionModel)



Sets the
selectionModel

for the list to a non
-
null

ListSelectionModel

implementation.


void

setUI
(
ListUI

ui)



Sets the
ListUI
, the look and feel object that renders this
component.


void

setValueIsAdjusting
(boolean

b)



Sets the selection model's
valueIsAdjusting

property.


void

setVisibleRowCount
(int

visibleRowCount)



Sets the
visibleRowCount

property, which has different
meanings depending on the layout orientation: For a
VERTICAL

layout orientation, this sets the preferred n
umber of rows to display
without requiring scrolling; for other orientations, it affects the
wrapping of cells.


void

updateUI
()



Resets the
ListUI

property by setting it to the value provided
by the current look and feel.

Table 9.4.1.3 Properties/Methods of JList

import java.awt.BorderLayout;

import javax.swing.Box;

import javax.swing.BoxLayout;

import ja
vax.swing.JCheckBox;

import javax.swing.JFrame;

import javax.swing.JList;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.event.ListSelectionEvent;

import javax.swing.event.ListSelectionListener;


public class SelectionMonitor

extends JPanel {



String label[] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six",


"Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve"};


JCheckBox checks[] = new JCheckBox[label.length];


JList list;



Mastering Java 7 By Neeraj Sharma 9893017496


public SelectionMonitor(
) {


setLayout(new BorderLayout());


list = new JList(label);


JScrollPane pane = new JScrollPane(list);


// Format the list and the buttons in a vertical box


Box rightBox = new Box(BoxLayout.Y_AXIS);


Box leftBo
x = new Box(BoxLayout.Y_AXIS);


// Monitor all list selections


list.addListSelectionListener(new RadioUpdater());



for (int i = 0; i < label.length; i++) {


checks[i] = new JCheckBox("Selection " + i);


checks[
i].setEnabled(false);


rightBox.add(checks[i]);


}


leftBox.add(pane);


add(rightBox, BorderLayout.EAST);


add(leftBox, BorderLayout.WEST);


}


public static void main(String s[]) {


JFrame frame = new JF
rame("Selection Monitor");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


frame.setContentPane(new SelectionMonitor());


frame.pack();


frame.setVisible(true);


}


// Inner class that responds to selection events
to update the buttons


class RadioUpdater implements ListSelectionListener {



public void valueChanged(ListSelectionEvent e) {


// If either of these are true, the event can be ignored.


if ((!e.getValueIsAdjusting()) || (
e.getFirstIndex() ==
-
1)) {


return;


// Change the radio button to match the current selection state


// for each list item that reported a change.


}



for (int i = e.getFirstIndex(); i <= e.ge
tLastIndex(); i++)



checks[i].setSelected(((JList) e.getSource()).isSelectedIndex(i));





}

}

}

Listing 9.4.1 Using JList

9.4.2
Using JComboBox


A JComboBox, which lets the user choose one of several choices, can hav
e two very different
forms. The default form is the uneditable combo box, which features a button and a drop
-
down
list of values. The second form, called the editable combo box, features a text field with a small
button abutting it. The user can type a val
ue in the text field or click the button to display a drop
-
down list. Here's what the two forms of combo boxes look like in the Java look and feel:


Mastering Java 7 By Neeraj Sharma 9893017496


Figure 9.4.2.1 JComboBox

The JComboBox class has following fields:


protected

String

actionCommand



This protected field is implementation specific.

protected

ComboBoxModel

dataModel



This protected field is implementation specific.

protected


ComboBoxEditor

editor



This protected field is implementation specific.

protected

boolean

isEditable



This protected field is implementation specific.

protected
JComboBox.KeySelectionManager

keySelectionManager



This protected field is implementation specific.

protected

boolean

lightWeightPopupEn
abled



This protected field is implementation specific.

protected

int

maximumRowCount




This protected field is implementation specific.

protected

ListCellRenderer

renderer



This protected field is implementation specific.

protected

Object

selectedItemReminder



This protected field is implementation specific.

Table 9.4.2.1 JComboBox Fields

List of Constructors:


JComboBox
()



Creates a
JComboBox

with a default data model.

JComboBox
(
ComboBoxModel

aModel)



Creates a
JCombo
Box

that takes its items from an existing
ComboBoxModel
.

JComboBox
(
Object
[]

items)



Creates a
JComboBox

that contains the elements in the specified array.

JComboBox
(
Vector
<?>

items)



Creates a
JComboBox

that contains the elements in the specified Vector.


Mastering Java 7 By Neeraj Sharma 9893017496

Table 9.4.2.2 JComboBox Constructers

List of Methods:


void

actionPerformed
(
ActionEvent

e)



This method is public as an implementation side effect.

protected

void

actionPropertyChanged
(
Action

action,
String

propertyName)



Updates the combobox's state in response to property
cha
nges in associated action.


void

addActionListener
(
ActionListener

l)



Adds an
ActionListener
.


void

addItem
(
Object

anObject)



Adds an item to the item list.


void

addItemListener
(
ItemListener

aListener)



Adds an
ItemListener
.


void

addPopupMenuListener
(
PopupMenuListener

l)



Adds a
PopupMenu

listener which will listen to
notification messages from the popup po
rtion of the combo
box.


void

configureEditor
(
ComboBoxEditor

anEditor,
Object

anItem)



Initializes the editor with the specified item.

protected

void

configurePropertiesFromAction
(
Action

a)



Sets the properties on this combobox to match those in
the specified
Action
.


void

contentsChanged
(
ListDataEvent

e)



This method is public as an implementation side effect.

protected

Pro
pertyChang
eListener

createActionPropertyChangeListener
(
Action

a)



Creates and returns a
PropertyChangeListener

that is
responsible for listening for chang
es from the specified
Action

and updating the appropriate properties.

protected
JComboBox.KeySelectionMa
nager

createDefaultKeySelectionManager
()



Retur
ns an instance of the default key
-
selection
manager.

protected

void

fireActionEvent
()



Noti
fies all listeners that have registered interest for
notification on this event type.

protected

void

fireItemStateChanged
(
ItemEvent

e)



Notifies all listene
rs that have registered interest for
notification on this event type.


void

firePopupMenuCanceled
()



Notifies
PopupMenuListener
s that the popup portion of
the combo box has been canceled.


void

firePopupMenuWillBecomeInvisible
()



Notifies
PopupMenuListener
s that the popup portion of
the combo box has become invisible.


void

firePopupMenuWillBecomeVisible
()



Notifies
PopupMenuListener
s that the popup portion of
the combo box will become visible.


Mastering Java 7 By Neeraj Sharma 9893017496


AccessibleContext

getAccessibleContext
()



Gets the AccessibleContext associated with this
JComboBox.


Action

getAction
()



Returns the currently set
Action

for this
ActionEvent

source, or
null

if no
Action

is set.


String

getActionCommand
()



Returns the action command that is included in the event
sent to action listeners.


ActionListener
[]

getActionListeners
()



Returns an array of all the
ActionListener
s added to
this JComboBox with addActionListener().


ComboBoxEditor

getEditor
()



Returns the editor used to paint and edit the selected
item in the
JComboBox

field.


Object

getItemAt
(int

index)



Returns the list item at the specified index.


int

getItemCount
()



Returns the number of items in the list.


ItemListener
[]

getItemListeners
()



Returns an array of all the
ItemListener
s added to this
JComboBox with addItemListener().


JComboBox.KeySelectionM
anager

getKeySelectionManager
()



Returns the list's key
-
selection manager.


int

getMaximumRowCount
()



Returns the maximum number of items the combo box
can display without a scrollbar


ComboBoxModel

getModel
()



Returns the data model currently used by th
e
JComboBox
.


PopupMenuListener
[]

getPopupMenuListeners
()



Returns an array of all the
PopupMenuListener
s added
to this JComboBox with addPopupMenuListener().


Object

getPrototypeDisplayValue
()



Returns the "prototypical display" value
-

an Object used
for the calculation of the display height and width.


ListCellRenderer

getRenderer
()



Returns the renderer used to display the selected item in
the
JComboBox

field.


int

getSelectedIndex
()



Returns the first item in the list that matches the given
item.


Object

getSelectedItem
()



Returns the current selected item.


Object
[]

getSelectedObjects
()



Returns an array containing the selected item.


ComboBoxUI

getUI
()



Returns the L&F object that rende
rs this component.


String

getUIClassID
()



Mastering Java 7 By Neeraj Sharma 9893017496


Returns the name of the L&F class that renders this
component.


void

hidePopup
()



Causes the combo box to close its popup window.


void

insertItemAt
(
Object

anObject, int

index)



Inse
rts an item into the item list at a given index.

protected

void

installAncestorListener
()






void

intervalAdded
(
ListDataEvent

e)



This method is public as an implementation side effect.


void

intervalRemoved
(
ListDataEvent

e)



This method is public as an implementation side effect.


boolean

isEditable
()



Returns true if the
JComboBox

is editable.


boolean

isLightWeightPopupEnabled
()



Gets the value of the
lightWeightPopupEnabled

property.


boolean

isPopupVisible
()



Determines the visibility of the popup.

protected

String

paramString
()



Returns a string representation of this
JComboBox
.


void

processKeyEvent
(
KeyEvent

e)



Handles
KeyEvent
s, looking for the Tab key.


void

removeActionListener
(
ActionListener

l)



Removes an
ActionListener
.


void

removeAllItems
()



Removes all items from the item list.


void

removeItem
(
Object

anObject)



Removes an item from the item list.


void

removeItemAt
(int

anIndex)



Removes the item at
anIndex

This method works only if
the
JComboBox

uses a mutable data model.


void

removeItemListener
(
ItemListener

aListener)



Removes an
ItemListener
.


void

removePopupMenuListener
(
PopupMenuListener

l)



Removes a
PopupMenuListener
.

protected

void

selectedItemChanged
()



This protected method is implementation specific.


boolean

selectWithKeyChar
(char

keyChar)



Selects the list item that corresponds to the specified
keyboard character and returns true, if there is an item
corresponding to that character.


void

setAction
(
Action

a)



Sets the
Action

for the
ActionEvent

source.


void

setActionCommand
(
String

aCommand)



Sets the action com
mand that should be included in the
event sent to action listeners.


void

setEditable
(boolean

aFlag
)



Determines whether the
JComboBox

field is editable.


Mastering Java 7 By Neeraj Sharma 9893017496


void

setEditor
(
ComboBoxEditor

anEditor)



Sets the editor used to paint and edit the selected item

in
the
JComboBox

field.


void

setEnabled
(boolean

b)



Enables the combo box so that items
can be selected.


void

setKeySelectionManager
(
JComboBox.KeySelectionManag
er

aManager)



Sets the object that translates a

keyboard character into a
list selection.


void

setLightWeightPopupEnabled
(boolean

aFlag)



Sets the
lightWeightPopupEnabled

property, which
provides a hint as to whether or not a lightweight
Component

should be used to contain the
JComboBox
, versus a
heavyweight
Component

such as a
Panel

or a
Window
.


void

setMaximumRowCount
(int

count)



Sets the maximum number of rows the
JComboBox

displays.


void

setModel
(
ComboBoxModel

aModel)



Sets the data model that the
JComboBox

uses to obtain
the list of items.


void

setPopupVisible
(boolean

v)



Sets the visibility of the popup.


void

setPrototypeDisplayValue
(
Object

prototypeDisplayVa
lue)



Sets the prototype display value used to calculate the
size of the display for the UI portion.


void

setRenderer
(
Lis
tCellRenderer

aRenderer)



Sets the renderer that paints the list items and the item
selected from the list in the JComboBox field.


void

setSelectedIndex
(int

anIndex)



Selects the item at index
anIndex
.


void

setSelectedItem
(
Object

anObject)



Sets the selected

item in the combo box display area to
the object in the argument.


void

setUI
(
ComboBoxUI

ui)



Sets the L&F object that renders this component.


void

showPopup
()



Causes the combo box to display its popup window.


void

updateUI
()



Resets the UI property to a value from the current look
and feel.

Table 9.4.2.3 JComboBox Methods

import java.awt.BorderLayout;

i
mport java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.JScrollPane;


Mastering Java 7 By Neeraj Sharma 9893017496

import javax.swing.JTextArea;


public class EditComboBox {


public
static void main(String args[]) {


String labels[] = { "A", "B", "C", "D","E", "F", "G", "H","I", "J" };


JFrame frame = new JFrame("Editable JComboBox");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


Container contentPane = frame.get
ContentPane();



final JComboBox comboBox = new JComboBox(labels);


comboBox.setMaximumRowCount(5);


comboBox.setEditable(true);


contentPane.add(comboBox, BorderLayout.NORTH);



final JTextArea textArea = new JTextArea();


JScrollPane sc
rollPane = new JScrollPane(textArea);


contentPane.add(scrollPane, BorderLayout.CENTER);



ActionListener actionListener = new ActionListener() {


public void actionPerformed(ActionEvent actionEvent) {


textArea.append("Selected: " + comb
oBox.getSelectedItem());


textArea.append(", Position: " + comboBox.getSelectedIndex());


textArea.append(System.getProperty("line.separator"));