Chapter 16 How to work with controls and layout managers YG - CS170 Objectives Applied  Create a panel that includes a text area with a.

Download Report

Transcript Chapter 16 How to work with controls and layout managers YG - CS170 Objectives Applied  Create a panel that includes a text area with a.

Chapter 16
How to work with
controls and
layout managers
YG - CS170
1
Objectives
Applied
 Create a panel that includes a text area with a scroll bar.
 Create a panel that includes check boxes and radio buttons with
the controls, and write an event listener that responds to click
events for the controls.
 Create a border that includes both a line style such as etched or
beveled and a title. Then, apply this border to a group of check
boxes, radio buttons, or other controls.
 Create a panel that includes a combo box or list populated with
data from an array or collection and write an event listener that
responds when the user selects an item.
 Create an event handler that can process all of the items selected
in a list that allows multiple selections.
YG - CS170
2
Objectives (continued)
 Create a panel that includes a list whose contents can be changed
by the program.
 Given a desired layout for a panel, draw a grid that represents the
layout, then use the GridBag layout manager to build the panel
with the correct layout.
 Given the requirements for a program that uses text areas, scroll
panes, check boxes, radio buttons, borders, combo boxes, and
lists, write the code to implement the application.
Knowledge
 List two Swing components that are designed to enhance the
appearance or operation of other controls.
 Describe a situation in which you would use a text area rather than
a text field.
YG - CS170
3
Objectives (continued)
 List two ways a program can determine whether a user has
selected a check box or radio button.
 Explain the difference between ActionEvent and ItemEvent for a
combo box.
 Explain the difference between a combo box and a list.
 List six layout managers commonly used to build Swing
applications, and describe the approach each takes to arranging
controls in a panel.
YG - CS170
4
A frame with several new types of components
YG - CS170
5
Swing controls presented in this chapter
Control
Text area
Class
JTextArea
Check box
JCheckBox
Radio button
JRadioButton
List
JList
Combo box
JComboBox
Description
Lets the user enter more than one line
of text.
Lets the user select or deselect an
option.
Lets the user select an option from a
group of options.
Lets the user select one or more items
from a list of items.
Lets the user select a single item from
a drop-down list of items. A combo
box can also let the user enter text
into the text portion of the combo
box.
YG - CS170
6
Components that enhance controls
Component
Border
Class
JBorder
Scroll pane
JScrollPane
Description
Can be used to visually group
components or to enhance the
appearance of an individual
component.
Contains scroll bars that can be
used to scroll through the contents
of other controls. Scroll panes are
typically used with text area and
list controls.
YG - CS170
7
A frame with a text area
YG - CS170
8
Common constructors of the JTextArea class
Constructor
JTextArea(intRows,
intCols)
JTextArea(String,
intRows, intCols)
Description
Creates an empty text area with the
specified number of rows and columns.
Creates a text area with the specified
number of rows and columns starting
with the specified text.
YG - CS170
9
Some methods that work with text areas
Method
setLineWrap(boolean)
setWrapStyleWord(boolean)
append(String)
getText()
setText(String)
Description
If the boolean value is true, the lines
will wrap if they don’t fit.
If the boolean value is true and line
wrapping is turned on, wrapped lines
will be separated between words.
Appends the specified string to the
text in the text area.
Returns the text in the text area as a
String.
Sets the text in the text area to the
specified string.
YG - CS170
10
Code that creates a text area
private JTextArea commentTextArea;
commentTextArea = new JTextArea(7, 20);
commentTextArea.setLineWrap(true);
commentTextArea.setWrapStyleWord(true);
add(commentTextArea);
Code that gets the text stored in the text area
String comments = commentTextArea.getText();
Note
 If the text area is going to receive more text than can be viewed at
one time, you should add the text area to a scroll pane.
YG - CS170
11
A frame that displays a text area in a scroll pane
YG - CS170
12
Common constructors of the JScrollPane class
Constructor
JScrollPane(Component)
JScrollPane(Component,
vertical, horizontal)
Description
Creates a scroll pane that displays the
specified component, along with
vertical and horizontal scrollbars as
needed.
Creates a scroll pane that displays the
specified component and uses the
specified vertical and horizontal
policies.
YG - CS170
13
Fields of the ScrollPaneConstants interface that
set scrollbar policies
Field
VERTICAL_SCROLLBAR_ALWAYS
VERTICAL_SCROLLBAR_AS_NEEDED
VERTICAL_SCROLLBAR_NEVER
HORIZONTAL_SCROLLBAR_ALWAYS
HORIZONTAL_SCROLLBAR_AS_NEEDED
HORIZONTAL_SCROLLBAR_NEVER
Description
Always display a vertical
scrollbar.
Display a vertical scrollbar only
when needed.
Never display a vertical
scrollbar.
Always display a horizontal
scrollbar.
Display a horizontal scrollbar
only when needed.
Never display a horizontal
scrollbar.
YG - CS170
14
Code that uses a scroll pane with a text area
private JTextArea commentTextArea = new JTextArea(7, 20);
commentTextArea.setLineWrap(true);
commentTextArea.setWrapStyleWord(true);
JScrollPane commentScroll = new
JScrollPane(commentTextArea);
add(commentScroll);
Code that creates a scroll pane and sets the scroll
bar policies
JScrollPane commentScroll =
new JScrollPane(commentTextArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
YG - CS170
15
A frame with a check box
YG - CS170
16
Common constructors of the JCheckBox class
Constructor
JCheckBox(String)
JCheckBox(String,
boolean)
Description
Creates an unselected check box with a
label that contains the specified string.
Creates a check box with a label that
contains the specified string. If the boolean
value is true, the check box is selected.
Some methods that work with check boxes
Method
isSelected()
setSelected(boolean)
addActionListener(
ActionListener)
Description
Returns a true value if the check box is
selected.
Checks or unchecks the check box
depending on the boolean value.
Adds an action listener to the check box.
YG - CS170
17
Code that creates the check box
private JCheckBox mailingCheckBox;
mailingCheckBox =
new JCheckBox("Add to mailing list", true);
mailingCheckBox.addActionListener(this);
add(mailingCheckBox);
Code that checks the status of the check box
boolean addToList = mailingCheckBox.isSelected();
YG - CS170
18
An actionPerformed method for the check box
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == mailingCheckBox)
{
if (mailingCheckBox.isSelected())
addressTextArea.setEnabled(true);
else
addressTextArea.setEnabled(false);
}
}
YG - CS170
19
A frame with three radio buttons
How to work with radio buttons
 You must add each radio button in a set of options to a
ButtonGroup object.
 Selecting a radio button automatically deselects all other radio
buttons in the same button group.
YG - CS170
20
Common constructors and methods of the
JRadioButton class
Constructor
JRadioButton(String)
JRadioButton(String,
boolean)
Method
isSelected()
addActionListener(
ActionListener)
Description
Creates an unselected radio button with the
specified text.
Creates a radio button with the specified
text. If the boolean value is true, the radio
button is selected.
Description
Returns a true value if the radio button is
selected.
Adds an action listener to the radio button.
YG - CS170
21
Common constructor and method of the
ButtonGroup class
Constructor
ButtonGroup()
Method
add(AbstractButton)
Description
Creates a button group used to hold a
group of buttons.
Description
Adds the specified button to the group.
YG - CS170
22
Code that creates three radio buttons and adds
them to a panel
private JRadioButton uspsRadioButton, upsRadioButton,
fedexRadioButton;
uspsRadioButton = new JRadioButton("USPS", true);
upsRadioButton = new JRadioButton("UPS");
fedexRadioButton = new JRadioButton("Fedex");
add(uspsRadioButton);
add(upsRadioButton);
add(fedexRadioButton);
ButtonGroup shipViaGroup = new ButtonGroup();
shipViaGroup.add(uspsRadioButton);
shipViaGroup.add(upsRadioButton);
shipViaGroup.add(fedexRadioButton);
YG - CS170
23
Code that determines which radio button is
selected
if (uspsRadioButton.isSelected())
shipVia = "USPS";
else if (upsRadioButton.isSelected())
shipVia = "UPS";
else if (fedexRadioButton.isSelected())
shipVia = "Federal Express";
YG - CS170
24
Radio buttons with an etched and titled border
How to work with borders
 To place controls in a border, you must create a panel, create a
border and apply it the panel, and add the controls to the panel.
 Because a border only groups controls visually, you must still use
a ButtonGroup object to group radio buttons logically.
 To set borders, you must import the javax.swing.border package.
YG - CS170
25
Static methods of the BorderFactory class
Method
createLineBorder()
createEtchedBorder()
createLoweredBevelBorder()
createRaisedBevelBorder()
createTitledBorder(String)
createTitledBorder(Border,
String)
Description
Creates a line border.
Creates an etched border.
Creates a lowered bevel border.
Creates a raised bevel border.
Creates a line border with the
specified title.
Adds the specified title to the
specified border.
Method of the JComponent class used to set
borders
Method
setBorder(Border)
Description
Sets the border style for a component.
YG - CS170
26
Code that creates bordered radio buttons
uspsRadioButton = new JRadioButton("USPS", true);
upsRadioButton = new JRadioButton("UPS");
fedexRadioButton = new JRadioButton("Fedex");
ButtonGroup shipViaGroup = new ButtonGroup();
shipViaGroup.add(uspsRadioButton);
shipViaGroup.add(upsRadioButton);
shipViaGroup.add(fedexRadioButton);
JPanel shipViaPanel = new JPanel();
Border shipViaBorder =
BorderFactory.createEtchedBorder();
shipViaBorder =
BorderFactory.createTitledBorder(shipViaBorder,
"Carrier");
shipViaPanel.setBorder(shipViaBorder);
shipViaPanel.add(uspsRadioButton);
shipViaPanel.add(upsRadioButton);
shipViaPanel.add(fedexRadioButton);
add(shipViaPanel);
YG - CS170
27
A frame with a combo box
YG - CS170
28
Common constructors of the JComboBox class
Constructor
JComboBox()
JComboBox(Object[])
Description
Creates an empty combo box.
Creates a combo box with the objects
stored in the specified array.
YG - CS170
29
Some methods that work with combo boxes
Method
getSelectedItem()
getSelectedIndex()
setSelectedIndex(intIndex)
setEditable(boolean)
getItemCount()
addItem(Object)
removeItemAt(int)
Description
Returns an Object type for the
selected item.
Returns an int value for the index
of the selected item.
Selects the item at the specified
index.
If the boolean value is true, the
combo box can be edited.
Returns the number of items
stored in the combo box.
Adds an item to the combo box.
Removes the item at the specified
index from the combo box.
YG - CS170
30
Some methods that work with combo boxes
(continued)
Method
removeItem(Object)
addActionListener(ActionListener)
addItemListener(ItemListener)
YG - CS170
Description
Removes the specified item
from the combo box.
Adds an action listener to
the combo box.
Adds an item listener to the
combo box.
31
Code that creates the combo box
private ArrayList<Product> products;
products = getProducts();
// returns an ArrayList of products
productComboBox = new JComboBox();
for (Product p : products)
productComboBox.addItem(p.getDescription());
add(productComboBox);
Code that determines which item was selected
int i = productComboBox.getSelectedIndex();
Product p = products.get(i);
YG - CS170
32
A frame that uses an action event listener to
update the display based on the user’s selection
YG - CS170
33
The actionPerformed method of the
ActionListener interface
Method
void actionPerformed(ActionEvent e)
Description
Invoked when an item is
selected.
The itemStateChanged method of the
ItemListener interface
Method
void itemStateChanged(ItemEvent e)
YG - CS170
Description
Invoked when an item is
selected or deselected.
34
Common methods of the ItemEvent class
Method
getSource()
getItem()
getStateChanged()
Description
Returns the source of the event.
Returns the selected item.
Returns an int value that indicates whether an
item was selected or deselected. The field
names for these values are SELECTED and
DESELECTED.
YG - CS170
35
Code that creates a combo box
products = getProducts();
productComboBox = new JComboBox();
for (Product p : products)
productComboBox.addItem(p.getDescription());
productComboBox.setSelectedIndex(0);
productComboBox.addActionListener(this);
add(productComboBox);
Code that implements the ActionListener interface
for the combo box
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == productComboBox)
{
int i = productComboBox.getSelectedIndex();
Product p = products.get(i);
priceTextField.setText(p.getFormattedPrice());
}
}
YG - CS170
36
A frame that includes a list
YG - CS170
37
Common constructors of the JList class
Constructor
JList(Object[])
JList(ListModel)
Description
Creates a list that contains the objects stored in
the specified array of objects.
Creates a list using the specified list model.
YG - CS170
38
Some methods of the JList class
Method
getSelectedValue()
getSelectedIndex()
isSelectedIndex(
intIndex)
setFixedCellWidth(
intPixels)
setVisibleRowCount(
intRows)
Description
Returns the selected item as an Object type.
Returns an int value for the index of the
selected item.
Returns a true value if the item at the
specified index is selected.
Sets the cell width to the specified number of
pixels. Otherwise, the width of the list is
slightly wider than the widest item in the
array that populates the list.
Sets the visible row count to the specified int
value. This only works when the list is
displayed within a scroll pane.
YG - CS170
39
Some methods of the JList class (continued)
Method
setSelectionMode(
mode)
setSelectedIndex(
intIndex)
Description
Sets the selection mode. To allow single
selections, specify
ListSelectionModel.SINGLE_SELECTION.
Selects the item at the specified index.
YG - CS170
40
Code that creates a list
descriptions = getProductDescriptions();
// returns an array of descriptions
productList = new JList(descriptions);
productList.setFixedCellWidth(200);
productList.setVisibleRowCount(5);
productList.setSelectedIndex(0);
productList.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(productList));
Code that gets the selected item
String s = (String)productList.getSelectedValue();
YG - CS170
41
A list that allows multiple selections
YG - CS170
42
Fields of the ListSelectionModel interface used to
set the selection mode
Field
SINGLE_SELECTION
SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION
Description
Allows just one selection.
Allows a single range of selections.
Allows multiple ranges of
selections. This is the default.
Methods of the JList class used to process multiple
selections
Method
getSelectedValues()
getSelectedIndices()
Description
Returns an array of Object types for the
selected items.
Returns an array of ints corresponding to the
indices of the selected items.
YG - CS170
43
Code that creates a list
descriptions = getProductDescriptions();
// returns an array of descriptions
productList = new JList(descriptions);
productList.setFixedCellWidth(200);
productList.setVisibleRowCount(5);
productList.setSelectedIndex(0);
productList.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
add(new JScrollPane(productList));
YG - CS170
44
Code that displays the list selections
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == acceptButton)
{
Object[] selections =
productList.getSelectedValues();
String s = "";
for (Object o : selections)
s += (String)o + "\n";
productTextArea.setText("You selected:\n" + s);
}
}
YG - CS170
45
A frame that lets you add elements to a list
YG - CS170
46
How to work with list models
 To modify the contents of a list, you:
 create a list model to access the data displayed by the list
 pass the list model to the list via the JList constructor
 The list model can be any object that implements the ListModel
interface.
 The most commonly used model is the DefaultListModel class.
YG - CS170
47
Some methods of the DefaultListModel class
Method
addElement(Object)
contains(Object)
get(int)
removeElementAt(int)
size()
clear()
Description
Adds the specified object to the list.
Returns a true value if the list contains the
specified object.
Returns an Object type for the element at
the specified position.
Removes the element at the specified
position.
Returns the number of elements in the list.
Removes all entries from the list.
YG - CS170
48
Code that creates a list
String[] descriptions = getProductDescriptions();
productListModel = new DefaultListModel();
for (String s : descriptions)
productListModel.addElement(s);
productList = new JList(productListModel);
productList.setFixedCellWidth(220);
productList.setSelectedIndex(0);
productList.setVisibleRowCount(5);
add(new JScrollPane(productList));
Code that adds an element to the list
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == addButton)
{
String s = descriptionTextField.getText();
productListModel.addElement(s);
}
}
YG - CS170
49
Examples of the Box and Grid layouts
Note
 The Box and Grid layout managers automatically resize each
component to fill the available space. To avoid unattractive panel
layouts, you can create additional panels to hold the component(s)
you want in each cell, then add these panels to the panel that uses
Box or Grid layout.
YG - CS170
50
Summary of the layout managers
Layout manager
FlowLayout
BorderLayout
CardLayout
BoxLayout
GridLayout
GridBagLayout
Description
Lays out components from left to right.
Lays out components in five regions.
Lays out components on a card where only one
card is visible at a time. Rather than using this
class, you can use the JTabbedPane class.
Lays out components in a horizontal or vertical
row of cells.
Lays out components in a rectangular grid of
cells where each cell is the same size.
Lays out components horizontally and
vertically in a rectangular grid.
YG - CS170
51
Code that creates the Box layout panel
class BoxLayoutPanel extends JPanel
{
public BoxLayoutPanel()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new JLabel("One"));
add(new JTextField("Two"));
add(new JLabel("Three"));
add(new JTextField("Four"));
add(new JCheckBox("Five"));
add(new JButton("Six"));
add(new JButton("Seven"));
add(new JButton("Eight"));
}
}
Code that creates a Grid layout manager
setLayout(new GridLayout(4, 2));
YG - CS170
52
A user interface that uses the Grid Bag layout
YG - CS170
0
1
2
0
JRadioButton
JRadioButton
JPanel
1
JLabel
JList
2
JLabel
JTextField
3
JLabel
JComboBox
4
JCheckBox
5
JButton
JComboBox
JButton
53
How to work with the Grid Bag layout
1. Diagram or sketch the user interface and divide it into rows and
columns.
2. Set the layout to an object of the GridBagLayout class:
setLayout(new GridBagLayout());
3. Create a GridBagConstraints object to hold positioning data:
GridBagConstraints c = new GridBagConstraints();
4. Set the constraints in the GridBagConstraints object:
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
c.gridheight = 1;
c.insets = new Insets(5, 5, 5, 5);
5. Use the add method of the Container class that specifies the
component and its constraints:
add(Component, GridBagConstraints)
6. Repeat steps 4 and 5 until all components have been added.
YG - CS170
54
The pack method of the Window class
Method
pack()
Description
Resizes the window to accommodate the components it
contains.
Note
 When you use the Grid Bag layout manager, it’s helpful to use the
pack method of the Window class to set the frame size. That way,
the size of the frame will automatically be set to accommodate the
components that are added to it.
YG - CS170
55
Fields of the GridBagConstraints class
Field
gridx
gridy
gridheight
gridwidth
ipadx
ipady
Description
An int value that specifies the leftmost cell that the
component occupies.
An int value that specifies the topmost cell that the
component occupies.
An int value that specifies the number of vertical cells
that a component occupies.
An int value that specifies the number of horizontal
cells that a component occupies.
An int value that specifies the amount of internal
horizontal padding to be added to each control.
An int value that specifies the amount of internal
vertical padding to be added to each control.
YG - CS170
56
Fields of the GridBagConstraints class
(continued)
Field
insets
weightx
weighty
anchor
fill
Description
An Insets object that specifies the amount of empty
space to leave on each side of the cell.
A double value that specifies how extra horizontal
space is distributed if the resulting layout is
horizontally smaller than the area allotted.
A double value that specifies how extra vertical space
is distributed if the resulting layout is vertically
smaller that the area allotted.
An int value that specifies the alignment of a
component within a cell.
An int value that specifies what to do with extra space
in a cell.
YG - CS170
57
Fields of the GridBagConstraints class that set
the anchor field
CENTER
NORTH
NORTHEAST
EAST
WEST
SOUTH
SOUTHEAST
Fields of the GridBagConstraints class that set
the fill field
NONE
HORIZONTAL
VERTICAL
YG - CS170
BOTH
58
Other fields of the GridBagConstraints class
Field
RELATIVE
REMAINDER
Description
For the gridx and gridy fields, this field specifies that
the component will be placed next to the last added
component. For the gridwidth and gridheight fields,
this field specifies that the component will be the nextto-last component in a row or column.
For the gridwidth and gridheight fields, this field
specifies that a component is the last component in a
row or column.
YG - CS170
59
A constructor for the Insets class
Constructor
Insets(intTop, intBottom,
(intLeft, intRight)
Description
Creates an Insets object with the
specified spacing for the top, bottom,
left, and right of each cell.
Note
 In most cases, you should set the insets field to create some visual
space between cells. Otherwise, the components in the layout will
appear jammed together.
YG - CS170
60
The code for the Payment application
import
import
import
import
java.awt.*;
java.awt.event.*;
javax.swing.*;
javax.swing.border.*;
public class PaymentApp
{
public static void main(String[] args)
{
JFrame frame = new PaymentFrame();
frame.setVisible(true);
}
}
YG - CS170
61
The code for the Payment application (continued)
class PaymentFrame extends JFrame
{
public PaymentFrame()
{
setTitle("Payment Application");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new PaymentPanel();
this.add(panel);
this.pack();
centerWindow(this);
}
private void centerWindow(Window w)
{
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setLocation((d.width-w.getWidth())/2,
(d.height-w.getHeight())/2);
}
}
YG - CS170
62
The code for the Payment application (continued)
class PaymentPanel extends JPanel implements ActionListener
{
private JRadioButton creditCardRadioButton,
billCustomerRadioButton;
private JList
cardTypeList;
private JTextField
cardNumberTextField;
private JComboBox
monthComboBox,
yearComboBox;
private JCheckBox
verifiedCheckBox;
private JButton
acceptButton,
exitButton;
private JLabel
cardTypeLabel,
cardNumberLabel,
expirationDateLabel;
public PaymentPanel()
{
setLayout(new GridBagLayout());
Border loweredBorder
= BorderFactory.createBevelBorder(BevelBorder.LOWERED);
YG - CS170
63
The code for the Payment application (continued)
// radio button panel
JPanel radioPanel = new JPanel();
ButtonGroup billingGroup = new ButtonGroup();
radioPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
radioPanel.setBorder(
BorderFactory.createTitledBorder(loweredBorder,
"Billing:"));
// credit card radio button
creditCardRadioButton =
new JRadioButton("Credit card", true);
creditCardRadioButton.addActionListener(this);
billingGroup.add(creditCardRadioButton);
radioPanel.add(creditCardRadioButton);
// bill customer radio button
billCustomerRadioButton = new JRadioButton("Bill customer");
billCustomerRadioButton.addActionListener(this);
billingGroup.add(billCustomerRadioButton);
radioPanel.add(billCustomerRadioButton);
YG - CS170
64
The code for the Payment application (continued)
add(radioPanel,
getConstraints(0,0,3,1, GridBagConstraints.WEST));
// card type label
cardTypeLabel = new JLabel("Card type:");
add(cardTypeLabel,
getConstraints(0,1,1,1, GridBagConstraints.EAST));
// card type list
String[] cardNames
= {"Visa", "Master Card", "American Express", "Other"};
cardTypeList = new JList(cardNames);
cardTypeList.setFixedCellWidth(170);
cardTypeList.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
cardTypeList.setVisibleRowCount(3);
JScrollPane cardTypeScrollPane =
new JScrollPane(cardTypeList);
add(cardTypeScrollPane,
getConstraints(1,1,2,1, GridBagConstraints.WEST));
YG - CS170
65
The code for the Payment application (continued)
// card number label
cardNumberLabel = new JLabel("Card number:");
add(cardNumberLabel,
getConstraints(0,2,1,1, GridBagConstraints.EAST));
// card number text field
cardNumberTextField = new JTextField(15);
add(cardNumberTextField,
getConstraints(1,2,2,1, GridBagConstraints.WEST));
// expiration date label
expirationDateLabel= new JLabel("Expiration date:");
add(expirationDateLabel,
getConstraints(0,3,1,1, GridBagConstraints.EAST));
// month combo box
String[] months = { "January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December" };
monthComboBox = new JComboBox(months);
add(monthComboBox,
getConstraints(1,3,1,1, GridBagConstraints.WEST));
YG - CS170
66
The code for the Payment application (continued)
// year combo box
String[] years =
{ "2005", "2006", "2007", "2008", "2009", "2010" };
yearComboBox = new JComboBox(years);
add(yearComboBox,
getConstraints(2,3,1,1, GridBagConstraints.WEST));
// verified check box
verifiedCheckBox = new JCheckBox("Verified");
add(verifiedCheckBox,
getConstraints(1,4,1,1, GridBagConstraints.WEST));
// calculate button
acceptButton = new JButton("Accept");
acceptButton.addActionListener(this);
add(acceptButton,
getConstraints(1,5,1,1, GridBagConstraints.EAST));
// exit button
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
add(exitButton,
getConstraints(2,5,1,1, GridBagConstraints.CENTER));
}
YG - CS170
67
The code for the Payment application (continued)
// a method for setting grid bag constraints
private GridBagConstraints getConstraints(int gridx, int gridy,
int gridwidth, int gridheight, int anchor)
{
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
c.ipadx = 0;
c.ipady = 0;
c.gridx = gridx;
c.gridy = gridy;
c.gridwidth = gridwidth;
c.gridheight = gridheight;
c.anchor = anchor;
return c;
}
YG - CS170
68
The code for the Payment application (continued)
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == exitButton)
System.exit(0);
else if (source == acceptButton)
{
String msg = "";
if (creditCardRadioButton.isSelected())
{
msg = "Bill " +
(String)cardTypeList.getSelectedValue() +
"\nNumber + " + cardNumberTextField.getText() +
"\nExpiration date: " +
(String)monthComboBox.getSelectedItem() +
", " + (String)yearComboBox.getSelectedItem();
if (verifiedCheckBox.isSelected())
msg+= "\nCard has been verified.";
else
msg+= "\nCard has not been verified.";
}
YG - CS170
69
The code for the Payment application (continued)
else
msg = "Customer will be billed.";
JOptionPane.showMessageDialog(this, msg);
cardTypeList.setSelectedIndex(0);
cardNumberTextField.setText("");
monthComboBox.setSelectedIndex(0);
yearComboBox.setSelectedIndex(0);
verifiedCheckBox.setSelected(false);
}
else if (source == creditCardRadioButton
|| source == billCustomerRadioButton)
{
if (creditCardRadioButton.isSelected())
enableCreditCardControls(true);
else if (billCustomerRadioButton.isSelected())
enableCreditCardControls(false);
}
}
YG - CS170
70
The code for the Payment application (continued)
private void enableCreditCardControls(boolean enable)
{
cardTypeLabel.setEnabled(enable);
cardTypeList.setEnabled(enable);
cardNumberLabel.setEnabled(enable);
cardNumberTextField.setEnabled(enable);
expirationDateLabel.setEnabled(enable);
monthComboBox.setEnabled(enable);
yearComboBox.setEnabled(enable);
verifiedCheckBox.setEnabled(enable);
}
}
YG - CS170
71