Title: Title Slid
1Title Slid
CSS 444
Java Programming JFC Swing
By Ralph B. Bisland, Jr.
2Swing Package
- Swing is an alternative to the Java AWT.
- It is part of the Java Foundation Classes.
- The AWT is tied to the local environment. The
displays may look different when run under
different platforms. - Swing components will look the same no matter
which environment the program is run under. - The Swing package is written in Java.
3Swing Package (ctd)
- Swing is part of the javax.swing package. (x
extension to basic Java.) - To use the Swing class you must import
javax.swing. - All Swing items names are preceded with the
letter J. Examples JPane, JButton, etc. - Swing and AWT components may be mixed in the same
program.
4How Swing Works
- Very similar to the Java AWT.
- Swing classes allow the definition of containers.
- Containers are made up of components (buttons,
lists, textboxes, etc.) which must be added to
the container. - Each component must have a listener attached.
- Each listener has an action performed method
which is used to program what happens when you
use the component.
5Sample Swing Classes
- JButton Creates buttons.
- JComboList Creates pull-down menus.
- JList Creates a list of options to choose from.
- JLabel Displays static text or an image.
- JTextField Creates an editable one line text
box. - JTextArea Creates an editable multi-line text
box. - JPanel Used to group components together.
6Sample Swing Classes (ctd)
- JScrollPane Allows the scrolling of a
component. - JApplet The Applet class associated with Swing
components.
7Swing Applets vs Applications
- Applications using Swing components must extend
the Frame (JFrame) class. - Applets using Swing components must extend the
Applet (JApplet) class. - Since you can not add components directly to
either JFrame or JApplet, you must create a
container to hold the components. - Use the method getContentPane() to get a
reference to the container.
8Application Containers
- To create an application container, you must do
the following things - Create a new instance of JFrame.
- Create a container of JFrame.
- Create components.
- Add the components to the container.
- You may optionally pack the components into the
smallest possible space if you wish. - You must then make the component visible or not.
- Optionally resize the window.
9Applet Containers
- To create an applet container, you must do the
following things - Create a container.
- Create components.
- Add the components to the container.
- You may optionally pack the components into the
smallest possible space if you wish. - You must then make the component visible or not.
- Optionally resize the window.
10JButton Class
- To create a Button pass a string with the button
text to the button class constructor. - The button must be added to the container.
- A listener must be added to determine if the
button has been pressed. - An action performed method must be over written
to tell the program what to do when the button is
pressed.
11Example
import java,awt. import javax.swing. class
FirstButton public static void main
(String args) JFrame frame new
JFrame (First Button) Container pane
frame.getContentPane() JButton hello new
JButton (Hello) pane.add(hello)
frame.pack() frame.show() frame.setSize
(300,200) // Hor vert // Other class
methods are placed here
12Listening To Events
- Any program that uses Swing components to create
a window, implicitly creates a thread that enters
into an infinite loop looking for the component
to do something (like push a button.) - Swing methods called listeners are issued to
monitor these events. - The listeners are all named addXXXListener()
- Where XXX is the component type.
13The Delegation Model
- A component that waits for user interaction is
called event-driven. - The implementation of event-driven programming
that Swing uses is called the delegation model
because objects are delegated the responsibility
of handling certain events that may occur.
14Implementation
- Objects that receive events are called listeners.
- Different types of objects have different types
of listeners. - Objects that generate ActionEvents contain the
method addActionListener() that indicates which
object(s) should receive the event. - The ActionEvent listener must implement the
java.awt.event.ActionEventListener interface.
15Implementation (ctd)
- To implement an interface, a class must define
all the methods specified in the interface. - Therefore, a class that implements the
ActionEventListener interface must contain an
actionPerformed() method. - Whenever you generate an ActionEvent (by clicking
on a button) the ActionPerformed() method for
each ActionEventListener that was added to the
button is called with the ActionEvent object as a
parameter.
16Example
import java,awt. import javax.swing. class
FirstButton public static void main
(String args) JFrame frame new JFrame
(First Button) Container pane
frame.getContentPane() JButton hello new
JButton (Hello) CheckIt listener new
CheckIt() hello.addActionListener(listener)
pane.add(hello) frame.pack()
frame.show() frame.setSize (300,200)
17Example (ctd)
import java.awt.event. class CheckIt implements
ActionListener public void actionPerformed
(ActionEvent e) System.out.print
(\0007)
18Summary Listening For An Event
- Create a button with new Jbutton (Some text).
- Get the Container for the JFrame using
getContentPane(). - Add the button to the content pane of the JPane
with add(). - Create an ActionEventListener class by
- Adding implements ActionEventListener to the
class declaration. - Defining the actionPerformed method.
19Summary Listening For An Event (ctd)
- Add a listener object to the list of listeners
for the button by calling button.addActionListener
(), where button is a reference to the button
previously created and listener is a reference to
an instance of the class created previously.
20The JComboBox Class
- Used to create pull-down menus.
- You create an empty JComponent object then add
items to it. - The items are usually strings.
- The item currently selected is displayed when the
list is not pulled down. - To have an action performed when an item is
selected, add an ItemListener to the JComponent
object.
21Example
import javax.swing. import java.awt. class
JComboBoxTest public static void main (String
args) JFrame frame new JFrame (JCombo
Test) Container display frame.getContainerP
ane() JComboBox list new JComboBox()
list.addItem(Baseball) //default selection
list.addItem(Football) list.addItem(Golf)
list.addItem(Bowling) display.add(list,
BorderLayout.NORTH) frame.pack()
frame.show()
22The JList Class
- Similar to JComboBox class except that the entire
list is always displayed. - The currently selected item is highlighted.
- More than one item can be selected.
- The list of items can be things other than
strings (i.e., images, etc.) - To have an action performed when an item is
selected, add an ItemListener to the JComponent
object.
23Example
import javax.swing. import java.awt. class
JListTest public static void main (String
args) JFrame frame new JFrame (JList
Test) Container display frame.getContainerP
ane() String items (Baseball,
Football, Golf,
Bowling) JList list new JList (items)
display.add(list) // Use default layout
frame.pack() frame.show()
24The JLabel Class
- Displays static text or an image.
- You, but not the user, can change the text by
calling the setText() method. - The Jlabel constructor accepts an optional
second parameter that can be used to align the
text. Possible values - JLabel.LEFT_ALIGNMENT
- JLabel.RIGHT_ALIGNMENT
- JLabel.CENTER_ALIGNMENT
- JLabel.TOP_ALIGNMENT
- JLabel.BOTTOM_ALIGNMENT
25The JTextField Class
- Similar to JLabel except that the user can edit
the text in the text box. - This is standard component for accepting keyboard
input. - It can be constructed with a default string -
which can be edited. - It can be constructed to allow only a fixed
number of text characters to be entered. - Editing of text is the default. This can be
changes by using the setEditable(false) method.
26JTextField Action Performed
- Can detect changes in text with either of two
methods - When the user presses the Return key Use the
ActionPerformed() method available in
ActionListener. - For finer control over test changes, you can
add a textFieldListener which contains the
textValueChanged() method. This listener detects
individual character changes.
27The JTextArea Class
- Similar to the JTextField class except that it
allows multiple line of text to be entered. - You specify the number of rows and columns in the
editable text area. - The text area is similar to a word processor
window. Text cant be accessed with either the
mouse or the arrow keys. - Listeners are the same as JTextField.
- Scrollbars may be added to the text area.
28Example
import javax.swing. import java.awt. class
JTextAreaTest public static void main (String
args) JFrame frame new JFrame (JTextArea
Test) Container display frame.getContainerP
ane() JTextArea area new JTextArea (4,
20) JScrollPane pane new JScrollPane(area)
area.append (This is the text that goes)
area.append ( into the text area. )
area.append (Yadda, yadda, yadda, yadda )
area.append (This is more stuff)
display.add(pane) frame.pack()
frame.show()
29The JPanel Class
- A JPanel has no appearance of its own.
- A JPanel is a Container that is used to group
several components. - JPanels use various layout managers to place
components into the Container. - JPanels may be embedded.
30Example
import javax.swing. import java.awt. class
JPanelTest public static void main (String
args) JFrame frame new JFrame (JPanel
Test) Container display frame.getContainerP
ane() JPanel top new JPanel (new
BorderLayout()) JPanel bot new JPanel (new
BorderLayout()) top.add(new JLabel(One
West), BorderLayout.WEST) top.add(new
JLabel(One East), BorderLayout.EAST)
bot.add(new JLabel(Two North),
BorderLayout.NORTH) top.add(new Jlabel(Two
South), BorderLayout.SOUTH)
31Example (ctd)
display.add (top, BorderLayout.NORTH)
display.add (bot, BorderLayout.SOUTH)
display.add (new JPanel Display Center,
BorderLayout.CENTER) display.add (new JPanel
Display West, BorderLayout.WEST)
display.add (new JPanel Display East,
BorderLayout.EAST) frame.pack()
frame.show()
32Example Output
JPanelTest
One West
One East
Display West Display Center Display East
Two North Two South
33The JScollPane Class
- Like a JPanel that can be scrolled.
- A JScrollPane can contain only a single
component, but because that component can be a
JPanel. - The JScrollPane can effectively scroll any
collection of components.
34Example
import javax.swing. import java.awt. class
JScrollPaneTest public static void main (String
args) JFrame frame new JFrame (JScrollPane
Test) Container display frame.getContainerPan
e() JPanel panel new JPanel (new
BorderLayout()) JScrollPane pane new
JScrollPanel (pane) panel.add(new
JButton(North), BorderLayout.NORTH)
panel.add(new JTextField(South),
BorderLayout.SOUTH) panel.add(new
JLabel(Center), BorderLayout.CENTER)
35Example (ctd)
String listItems (West1, West2,
West3) JList list new
JList (listItems) panel.addItem(list,
BorderLayout.WEST) JComboBox choice new
JComboBox () choice.addItem(East1)
choice.addItem(East2) choice.addItem(East3
) panel.add(choice, Borderlayout.EAST)
display.add (pane) frame.pack()
frame.show()
36Complete Example
imort javax.swing. import java.awt. import
java.awt.event. public class Converter extends
JFrame implements ActionListener private
final NBUTTONS 12 private JLabel prompt
new JLabel (Distance in miles ) private
JTextField input new JTextField(6) private
JTextArea display new JTestArea (10, 20)
private Jbutton convert new Button
(Convert) private JPanel keypadPanel new
JPanel() private JButton keyPad
37Complete Example (ctd)
private String label 1, 2, 3,
4, 5, 6, 7, 8, 9, C,
0, . public converter ()
getContentPane().setLayout(new FlowLayout())
initKeypad() getContentPane().add(prompt)
getContentPane().add(input) getContentPane().ad
d(convert) getcontentPane().add(display)
getContentPane().addkeypadPanel)
display.setLineWrap(true) display.setEditable(f
alse)
38Complete Example (ctd)
convert.addActionListener(this)
input.addActionListener(this) public void
initKeyPad() keyPad new Jbutton (NBUTTONS)
for (int k0kltkeyPad.lengthk) keyPadk
new JButton (labelk) keypadkaddActionLis
tener(this) keypadpanel.add(keyPadk)
39Complete Example (ctd)
public void actionPerformed (ActionEvent e) if
(e.getSource()convert
e.getsourceinput) double miles
Double.valueOf (input.getText()).do
ubleValue() double km MetricConverter.milesT
oKm (miles)
display.append(miles miles km
kilometers) inpur.setText()
40Complete Example (ctd)
else Jbutton b (Jbutton.getSource() if
(b.getText().equals(C) input.setText()
else input.setText (input.setText()b.getTex
t()) Public static void main (String
args) Converter f new Converter()
f.setSize(400, 300) f.setVisible(true)
f.addWindowListener() public void
windowClosing(WindowEvent e)
System.exit(0)
41Complete Example (ctd)
public class MetricConverter public static
double milesToKm (double miles)
return miles / 0.62