Description
Need help with this project. I will include lecture notes to help guide and assist you. Please help me complete the java code needed to run this.
Morgan State University
Department of Electrical & Computer Engineering
EEGR 415: Java Programing Applications
Project 2.1
Objective:
Transform Project 1 into a full-fledged GUI application for the classification of fruit feature data.
Create the graphical user interface
Create a graphical user interface for project 1 as follows:
The file menu has the following options:
The view menu only has one menu option, which is a check box that is checked by default.
The combo box under (View Data Samples) has the following:
Hints:
•
•
To get the text in the frames around each main panel, use TitledBorder (Google it)
You should add your Menu bar object to your Frame object using the method setJMenuBar (add
it before you make the frame visible)
Lecture 10
Multidimensional Arrays & Basic
Graphical User Interfaces
1
Two-Dimensional Arrays
â—¼
An two-dimensional array is an array of
references to other arrays:
â—¼
â—¼
â—¼
â—¼
â—¼
â—¼
The top-level array contains references to
other arrays
The lower-level arrays contain data
All arrays must be of the same type
This creates a two-dimensional data structure
Individual elements in the array are addressed with
two subscripts, specifying the row and the column
(in that order) of the particular data item
These arrays store data that is a function of two
independent variables.
2
Two Dimensional Arrays
a1[0][0] a1[0][1] a1[0][2] a1[0][3] a1[0][4]
a1[0]
a1[1][0] a1[1][1] a1[1][2] a1[1][3] a1[1][4]
a1[1]
a1
a1[2]
a1[2][0] a1[2][1] a1[2][2] a1[2][3] a1[2][4]
a1[3]
a1[3][0] a1[3][1] a1[3][2] a1[3][3] a1[3][4]
Array of references
to other arrays
Arrays containing data
3
Declaring 2D Arrays
â—¼
â—¼
We must first declare an array of
references to other arrays, and then
declare the arrays themselves
Example:
double[][] x; // Create ref to an array of arrays
x = new double[3][5]; // Create array objects
â—¼
These steps can be combined on a single
line:
double[][] x = new double[3][5];
4
Initializing 2D Arrays
â—¼
2D arrays may be initialized with nested
array initializers
int[][] b = { {1,2,3}, {4,5,6} };
â—¼
They may also be initialized by reading
data from a file into the array using
nested for loops.
5
Using Two-Dimensional Arrays
â—¼
2D arrays are used to represent data
that is a function of two independent
variables
â—¼
â—¼
A 2D array element is addressed using
the array name followed by a integer
subscript in brackets: a[2][3]
Example:
for ( igen = 0; igen < MAX_GEN; igen++ ) {
for ( itime = 0; itime < MAX_TIME; itime++ ) {
powerSum[itime] += power[igen][itime];
}
}
6
Lab 1
â—¼
â—¼
Initialize a 4x4 array to the values of the
multiplication table
Display the values from the double
dimensioned array using a nested for
loop
7
Lab 2
â—¼
Write a program that initializes the following 2
dimensional arrays :
â—¼
â—¼
â—¼
â—¼
itemNames
Women Double-faced
wool coat
Women Floral Silk Tank
Blouse
Women Chiffon Blouse
Men Cotton Polo Shirt
Children Cable-knit
Sweater
Children Bear Coverall
Cotton
947783
934687
973947
739579
367583
743937
275.25
180.05
50.00
45.55
25.65
28.25
itemNumbers
Unit Prices
Ask the user to enter a price range and display all
information for items within the price range
8
Lab 2
9
Higher-Order Arrays
â—¼
â—¼
The same ideas that apply to 2D arrays can be
extended for arrays of any order
Example: the following statement creates a 3D array
containing a total of 30 elements
double[][][] x = new double[3][5][2];
â—¼
â—¼
â—¼
â—¼
The first element has the subscript range 0 - 2
The second element has the subscript range 0 - 4
The third element has the subscript range 0 - 1
These arrays are used to represent data that is a
function of more than two independent variables
10
Basic Graphical User Interfaces
11
Java GUIs
â—¼
The Java SDK contains to different
Graphical User Interfaces (GUIs)
â—¼
â—¼
â—¼
â—¼
The Abstract Windowing Toolkit (AWT),
which contained the original Java GUI
The Swing package, which is a newer,
more flexible Java GUI
JavaFX which is the newest package that
ships with JDK 8.0 and above
Only the Swing GUI is taught in this
class
12
How GUIs Work
â—¼
â—¼
â—¼
GUIs provide a user with a familiar environment in
which to work, with push buttons, menus, dropdown lists, text fields, etc.
GUI-based programs are harder to program, since
they must be ready for mouse clicks or keyboard
input to any component at any time
Mouse clicks or keyboard inputs are known as
events, and GUI-based programs are event-driven
13
How GUIs Work (2)
â—¼
A GUI consists of:
â—¼
â—¼
â—¼
â—¼
GUI Components, which represent elements on
the screen such as push buttons, text fields, etc.
A Container to hold the components. The
containers in this lecture are JPanel and JFrame.
A Layout Manager to control the placement of
GUI components within the container.
Event handlers to respond to mouse clicks or
keyboard inputs on any component or container in
the GUI
14
Creating and Displaying a GUI
â—¼
To create a GUI:
â—¼
â—¼
â—¼
â—¼
â—¼
â—¼
Create a container class to hold the GUI
components
Select and create a layout manager for the
container
Create components and add them to the container
Create “listener†objects to detect and respond to
the events expected by each GUI component
Register the listeners with appropriate components
Create a JFrame object, and place the completed
container in the center of content pane associated
with the frame.
15
Creating and Displaying a GUI
â—¼
Goal: Create a window with a button
that displays the count of the number of
times clicked
16
Creating and Displaying a GUI (2)
Required
packages
Create GUI
in init
method
Set layout
manager
Create GUI
components
Method (s) to
implement
actions
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import
import
import
public
java.awt.*;
java.awt.event.*;
javax.swing.*;
class FirstGUI extends JPanel {
// Instance variables
private int count = 0;
// Number of pushes
private JButton pushButton; // Push button
private JLabel label;
// Label
// Initialization method
public void init() {
// Set the layout manager
setLayout( new BorderLayout() );
// Create a label to hold push count
label = new JLabel("Push Count: 0");
add( label, BorderLayout.NORTH );
label.setHorizontalAlignment( label.CENTER );
// Create a button
pushButton = new JButton("Test Button");
pushButton.addActionListener( new ButtonHandler(this) );
add( pushButton, BorderLayout.SOUTH );
}
// Method to update push count
public void updateLabel() {
label.setText( "Push Count: " + (++count) );
}
Add listener
for button
}
17
Creating and Displaying a GUI (3)
Create
JFrame
Create and
add window
listener
Add GUI
to JFrame
Define
listener class
for
pushbutton
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public static void main(String s[]) {
// Create a frame to hold the application
JFrame fr = new JFrame("FirstGUI ...");
fr.setSize(200,100);
// Create a Window Listener to handle "close" events
WindowHandler l = new WindowHandler();
fr.addWindowListener(l);
// Create and initialize a FirstGUI object
FirstGUI fg = new FirstGUI();
fg.init();
// Add the object to the center of the frame
fr.getContentPane().add(fg, BorderLayout.CENTER);
// Display the frame
fr.setVisible( true );
}
class ButtonHandler implements ActionListener {
private FirstGUI fg;
main
method, so
the program
starts here
Method init
called here,
so GUI
created here
// Constructor
public ButtonHandler ( FirstGUI fg1 ) {
fg = fg1;
}
// Execute when an event occurs
public void actionPerformed( ActionEvent e ) {
fg.updateLabel();
}
}
18
Creating and Displaying a GUI (3)
â—¼
Need a window listener to close program
class WindowHandler extends WindowAdapter {
/* This method implements a simple listener that
* detects the "window closing event" and stops
* the program.
*/
public void windowClosing(WindowEvent e) {
System.exit(0);
};
}
19
Events and Event Handling
â—¼
â—¼
An event is an object that is created by some
external action (mouse click, key press, etc.)
When an event such as a mouse click occurs,
Java automatically sends that event to the GUI
object that was clicked on.
â—¼
When the event is received by the GUI object,
the object checks to see if any listener object has
registered with it to receive the event, and it
forwards the event to the actionPerformed
method of that object.
20
Events and Event Handling (2)
â—¼
â—¼
The actionPerformed method is known as an
event handler because it performs whatever
steps are required to process the event.
In many cases, the event handler makes a call to
a callback method in the object that created
the GUI, since such methods can update instance
variables within the object directly
â—¼
In the previous example, class
ButtonHandler was a listener, its method
actionPerformed was an event handler,
and method updateLabel was a callback
method
21
Events and Event Handling (3)
â—¼
â—¼
That method calls the
method updateLabel
(callback)
updateLabel updates
the label
Inherited
Method(s)
Constructors
Methods
()
bel
eLa
t
a
upd
Constructors
Instance
variables
ButtonHandler object
Instance
variables
Methods
FirstGUI object
set
T ex
t("
P
+ (ush C
++c oun
ou n t:
t)) "
Constructors
Instance
variables
Methods
ButtonHandler object
io n
P
(Ac erfo
tio rme
nE v d
ent
e)
JButton object
action-Performed
method of the
Methods
Methods
act
Original event:
Mouse click on button
Inherited
Method(s)
â—¼
Instance
variables
Methods
â—¼
A mouse click on the
button creates an event
The event is sent to the
JButton object
The JButton object
sends the event to the
Inherited
Method(s)
â—¼
n
eve
u se
Mo
Constructors
n
ut to
to J B
t
n
t se
Methods
In the previous
example:
Inherited
Method(s)
â—¼
Methods
JLabel object
22
Creating and Displaying a GUI (4)
â—¼
Result after three mouse clicks on the
button:
23
Lab 3
â—¼
Create a GUI application (based on the
prior example) that has two buttons that
either decrement or increment a counter
when pressed
24
The JLabel Class
â—¼
A label is an object that displays a single
line of read-only text and/or an image.
â—¼
â—¼
It does not respond to mouse clicks or
keyboard input.
Constructors:
public
public
public
public
public
public
â—¼
JLabel();
JLabel(String s);
JLabel(String s, int horizontalAlignment);
JLabel(Icon image);
JLabel(Icon image, int horizontalAlignment);
JLabel(String s, Icon image, int horizontalAlignment);
These constructors create a label
containing text s, image image, or both
26
The JLabel Class (2)
â—¼
Methods:
Method
public Icon getIcon()
Description
Returns the image from a JLabel.
public String getText()
Returns the text from a JLabel.
public void setIcon(Icon image)
Sets the JLabel image.
public void setText(String s)
Sets the JLabel text.
public void setHorizontalAlignment(
int alignment)
Sets the horizontal alignment of the JLabel
text and image. Legal values are LEFT,
CENTER, and RIGHT.
public void
setHorizontalTextPosition(
int textPosition)
Sets the position of the text relative to the
image. Legal values are LEFT, CENTER, and
RIGHT.
public void setVerticalAlignment(
int alignment)
Sets the vertical alignment of the JLabel
text and images. Legal values are TOP,
CENTER, and BOTTOM.
public void
setVerticalTextPosition(
int textPosition)
Sets the position of the text relative to the
image. Legal values are TOP, CENTER, and
BOTTOM.
27
Example: The JLabel Class
// Get the images to display
ImageIcon right = new ImageIcon("BlueRightArrow.gif");
ImageIcon left = new ImageIcon("BlueLeftArrow.gif");
// Create a label with icon and text
l1 = new JLabel("Label 1", right, JLabel.LEFT);
add( l1, BorderLayout.NORTH );
// Create a label with text and icon
l2 = new JLabel("Label 2", left, JLabel.RIGHT);
add( l2, BorderLayout.CENTER );
l2.setHorizontalTextPosition( JLabel.LEFT );
// Create a label with text only
l3 = new JLabel("Label 3 (Text only)", JLabel.CENTER);
add( l3, BorderLayout.SOUTH );
}
28
The JButton Class
â—¼
The
â—¼
â—¼
JButton
When a mouse clicks on a button, an
ActionEvent is generated and passed to any
registered listeners.
Constructors:
public
public
public
public
â—¼
class creates a pushbutton.
JButton();
JButton(String s);
JButton(Icon image);
JButton(String s, Icon image);
These constructors create a pushbutton
containing text s, image image, or both
29
Example: Creating Buttons
// Create buttons
b1 = new JButton("Enable",right);
b1.addActionListener( this );
b1.setMnemonic('e');
b1.setToolTipText("Enable middle button");
add(b1);
String s = "Count = " + c;
b2 = new JButton(s,green);
b2.addActionListener( this );
b2.setMnemonic('c');
b2.setEnabled(false);
b2.setToolTipText("Press to increment count");
b2.setPressedIcon(yellow);
b2.setDisabledIcon(red);
add(b2);
b3 = new JButton("Disable",left);
b3.addActionListener( this );
b3.setMnemonic('d');
b3.setEnabled(false);
b3.setToolTipText("Disable middle button");
add(b3);
}
30
ActionEvent Events
â—¼
JButtons generate ActionEvent objects when an
â—¼
event (mouse click) occurs on them.
A listener class for these events must implement the
ActionListener interface, and have an actionPerformed method.
â—¼
â—¼
A listener object must be registered to listen for
ActionEvents on each button.
When a mouse click occurs, the actionPerformed
method of the corresponding listener object will be
called to handle the event
31
Lab 4
â—¼
â—¼
â—¼
â—¼
Modify lab 3 so that the user can not
decrement counter below 0
Disable the “Decrement†button when count is
at 0
Add tool tips to each button
Add a title label to the window
32
The JTextField Class
â—¼
The
â—¼
â—¼
JTextField
When a user types text and presses the ENTER key,
an ActionEvent is generated and passed to any
registered listeners.
Constructors:
public
public
public
public
â—¼
class creates a text field.
JTextField();
JTextField(int cols);
JTextField(String s);
JTextField(String s, int cols);
These constructors create a text field containing
a blank space large enough for cols characters,
the text string s, or both
34
The JPasswordField Class
â—¼
â—¼
The
class is identical to the
JTextField class, except the text typed
into the field is not visible. Instead, a
string of asterisks are shown to represent
the characters typed.
Constructors:
JPasswordField
public
public
public
public
JPasswordField();
JPasswordField(int cols);
JPasswordField(String s);
JPasswordField(String s, int cols);
35
Example: Creating Text Fields
// Create first Text Field
l1 = new JLabel("Visible text here:",JLabel.RIGHT);
add( l1 );
t1 = new JTextField("Enter Text Here",25);
t1.addActionListener( handler );
add( t1 );
// Create Password Field
l2 = new JLabel("Hidden text here:",JLabel.RIGHT);
add( l2 );
t2 = new JPasswordField("Enter Text Here",25);
t2.addActionListener( handler );
add( t2 );
// Create third Text Field
l3 = new JLabel("Results:",JLabel.RIGHT);
add( l3 );
t3 = new JTextField(25);
t3.setEditable( false );
add( t3 );
36
Lab 5
â—¼
â—¼
â—¼
â—¼
â—¼
Modify lab 3 so that a text box is placed at the bottom
of the window to allow user to set counter directly
(default text to show is “Set counterâ€Â)
Do not allow negative values
Handle errors associated with not entering an integer
Use ActionEvent.getActionCommand() method in text
handler to get actual text entered
Make sure Decrement button is disabled if 0 is entered
37
The JComboBox Class
â—¼
â—¼
The JComboBox class field in which a user can
either type text or select a choice from a drop
down list of options.
Constructors:
public JComboBox();
public JComboBox( Object[] );
public JComboBox( Vector );
â—¼
â—¼
These constructors create a combo containing
list of choices from the Object or Vector
A user can be forced to select from the drop
down list only using the method
setEditable(false)
40
Example: Creating Combo Boxes
// Create the JComboBox
String[] s = {"Serif","SansSerif","Monospaced",
"Dialog"};
c1 = new JComboBox(s);
c1.addActionListener( handler );
add( c1 );
// Create the text field with default font
Font font = new Font(c1.getItemAt(0).toString(),
Font.PLAIN, 14);
t1 = new JTextField("Test string",30);
t1.setEditable( false );
t1.setFont( font );
add( t1 );
41
Example: Creating Combo Boxes
Handling Item Selected Event
42
The JCheckBox Class
â—¼
â—¼
â—¼
The JCheckBox class creates a special type of
button that toggles between “on†and “off†each
time it is clicked.
It looks like a small box with a check mark, but
it is really a full-fledged button
Selected Constructors:
public JCheckBox( String s, boolean state );
public JCheckBox( Icon image, boolean state );
public JCheckBox( String s, Icon image, boolean state );
â—¼
These constructors create a check box
containing text s, image image, or both, in initial
state state
43
Example: Creating Check Boxes
// Create the JComboBox for font names
String[] s = {"Serif","SansSerif","Monospaced",
"Dialog"};
c1 = new JComboBox(s);
c1.addActionListener( h1 );
add( c1 );
// Create the text field with default font
Font font = new Font( c1.getItemAt(0).toString(),
Font.PLAIN, 14);
t1 = new JTextField("Test string",20);
t1.setEditable( false );
t1.setFont( font );
add( t1 );
// Create check boxes for bold and italic
cb1 = new JCheckBox("Bold");
cb1.addActionListener( h1 );
cb1.setMnemonic('b');
add( cb1 );
cb2 = new JCheckBox("Italic");
cb2.addActionListener( h1 );
cb2.setMnemonic('i');
add( cb2 );
44
The JRadioButton Class
â—¼
â—¼
The JRadioButton class creates a radio
button, a small circle with a dot in the
center when “onâ€Â.
Selected Constructors:
public JRadioButton( String s, boolean state );
public JRadioButton( Icon image, boolean state );
public JRadioButton( String s, Icon image, boolean state );
â—¼
These constructors create a radio button
containing text s, image image, or both, in
initial state state
45
Button Groups
â—¼
â—¼
â—¼
Radio buttons are grouped together into groups
known as button groups.
Only one button within a group may be on at
any time. If one is turned on, the other radio
buttons in the group will be forced off
Constructor:
public ButtonGroup();
â—¼
Methods:
public void add(AbstractButton b);
// Add button to group
public void remove(AbstractButton b); // Remove from group
46
Example: Creating Radio Buttons
// Create radio buttons
b1 = new JRadioButton("Plain", true );
b1.addActionListener( h1 );
add( b1 );
b2 = new JRadioButton("Bold", false );
b2.addActionListener( h1 );
add( b2 );
b3 = new JRadioButton("Italic", false );
b3.addActionListener( h1 );
add( b3 );
b4 = new JRadioButton("Bold Italic", false );
b4.addActionListener( h1 );
add( b4 );
// Create button group, and add radio buttons
bg = new ButtonGroup();
bg.add( b1 );
ButtonGroup
bg.add( b2 );
bg.add( b3 );
bg.add( b4 );
ensures that the 4
radio buttons are
mutually exclusive
47
Layout Managers
â—¼
Layout managers are classes that control
the location of components within a container
Element
BorderLayout
Standard Layout Managers
Description
A layout manager that lays out elements in a central region and
four surrounding borders. This is the default layout manager for a
JFrame.
BoxLayout
A layout manager that lays out elements in a row horizontally or
vertically. Unlike FlowLayout, the elements in a BoxLayout do
not wrap around. This is the default layout manager for a Box.
CardLayout
A layout manager that stacks components like a deck of cards, only
the top one of which is visible.
FlowLayout
A layout manager that lays out elements left-to-right and top-tobottom within a container. This is the default layout manager for a
JPanel.
GridBagLayout
A layout manager that lays out elements in a flexible grid, where
the size of each element can vary.
GridLayout
A layout manager that lays out elements in a rigid grid.
48
BorderLayout Layout Manager
â—¼
â—¼
The BorderLayout layout manager arranges
components in five regions, known as North, South,
East, West, and Center
Constructors:
public BorderLayout();
public BorderLayout(int horizontalGap, int verticalGap);
â—¼
A layout manager is associated with a container using
the container’s setLayout method:
setLayout( new BorderLayout() );
â—¼
Components are added to specific regions with a
special option of the container’s add method:
add(new Button("North"), BorderLayout.NORTH);
â—¼
Default layout manager for JFrame
49
Example: Creating a BorderLayout
setLayout(new BorderLayout());
add(new Button("North"), BorderLayout.NORTH);
add(new Button("South"), BorderLayout.SOUTH);
add(new Button("East"), BorderLayout.EAST);
add(new Button("West"), BorderLayout.WEST);
add(new Button("Center"), BorderLayout.CENTER);
50
FlowLayout Layout Manager
arranges
components in order from left to right
and top to bottom across a container
â—¼
The FlowLayout layout manager
â—¼
Constructors:
public FlowLayout();
public FlowLayout(int align);
public FlowLayout(int align, int horizontalGap,
int verticalGap);
â—¼
â—¼
The alignment can be LEFT, RIGHT, or CENTER
Default layout manager for JPanel
51
Example: Creating a FlowLayout
setLayout(new FlowLayout(FlowLayout.CENTER,5,0));
add(new JButton("Button 1"));
add(new JButton("Button 2"));
add(new JButton("Long Button 3"));
add(new JButton("B4"));
add(new JButton("Button 5"));
52
GridLayout Layout Manager
â—¼
â—¼
The GridLayout layout manager arranges
components in a rigid rectangular grid structure.
Constructors:
public GridLayout(int rows, int cols);
public GridLayout(int rows, int cols, int horizGap,
int vertGap);
â—¼
Components are added to the grid in order from left
to right and top to bottom
53
Example: Creating a GridLayout
setLayout(new GridLayout(3,2));
add(new JButton("1"));
add(new JButton("2"));
add(new JButton("3"));
add(new JButton("4"));
add(new JButton("5"));
add(new JButton("6"));
54
BoxLayout Layout Manager
â—¼
â—¼
â—¼
â—¼
The BoxLayout layout manager arranges
components within a container in a single row or a
single column.
The spacing and alignment of each element on each
row or column can be individually controlled.
Containers using BoxLayout managers can be nested
inside each other to produce complex layouts
Constructor:
public BoxLayout(Container c, int direction);
â—¼
â—¼
The direction can be X_AXIS or Y_AXIS
Rigid areas and glue regions can be used to space
out components within a BoxLayout
55
Example: Creating a BoxLayout
// Create a new panel
JPanel p = new JPanel();
// Set the layout manager
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
// Add
p.add(
p.add(
p.add(
p.add(
p.add(
buttons
new JButton("Button 1")
Box.createRigidArea(new
new JButton("Button 2")
Box.createRigidArea(new
new JButton("Button 3")
);
Dimension(0,20)) );
);
Dimension(0,5)) );
);
// Add the new panel to the existing container
add( p );
56
Combining Layout Managers to Produce a
Result
â—¼
â—¼
â—¼
To create just the look you want, it is sometimes
useful to create multiple containers inside each
other, each with its own layout manager
For example, a top-level panel might use a
horizontal box layout, and that panel may contain
two or more panels using vertical box layouts
The result is complete control of component
spacing in both dimensions
57
Example: Nested Containers and Layouts
// Create a new high-level panel
JPanel pHoriz = new JPanel();
pHoriz.setLayout(new BoxLayout(pHoriz, BoxLayout.X_AXIS));
add( pHoriz );
// Create two subordinate panels
JPanel pVertL = new JPanel();
JPanel pVertR = new JPanel();
pVertL.setLayout(new BoxLayout(pVertL, BoxLayout.Y_AXIS));
pVertR.setLayout(new BoxLayout(pVertR, BoxLayout.Y_AXIS));
// Add to pHoriz with a horizontal space between panels
pHoriz.add( pVertL );
pHoriz.add( Box.createRigidArea(new Dimension(20,0)) );
pHoriz.add( pVertR );
// Create degrees Celsius field
l1 = new JLabel("deg C:", JLabel.RIGHT);
pVertL.add( l1 );
t1 = new JTextField("0.0",15);
t1.addActionListener( cHnd );
pVertR.add( t1 );
Structure:
pHoriz
pVertL
pVertR
l1
t1
l2
t2
Result:
// Create degrees Fahrenheight field
l2 = new JLabel("deg F:", JLabel.RIGHT);
pVertL.add( l2 );
t2 = new JTextField("32.0",15);
t2.addActionListener( fHnd );
pVertR.add( t2 );
58
Example 2: Plot Sine/Cosine Program
Structure:
Result:
pVert
pHoriz
JCheckBox 1
JCheckBox 2
59
Lab 6
â—¼
â—¼
Modify lab 5 so that you use a combination of
vertical and horizontal box layouts
Add a combo box that allows the user to set
the counter at increments of 10
Vertical Box Layout
Horizontal Box Layout
60
Java Programming
for Engineers
L EC T UR E 8 : I N HER ITANCE, P OLYM OR PHISM , A N D I N T ER FACES
DR . KOF I N YAR KO
1
Subclasses and Superclasses
All classes form a part of a class hierarchy.
â—¦ Every class except Object is a subclass of some other class, and it inherits
instance variables and methods from its parent class.
â—¦ The class can add additional instance variables and methods, and can also
override the behavior of methods inherited from its parent class.
Any class above a specific class in the class hierarchy is a superclass of that
class.
Any class below a specific class in the class hierarchy is a subclass of that
class.
2
Defining Superclasses and Subclasses
Methods and instance variables
defined in class Employee are
inherited by the two subclasses
Employee
Because of inheritance, objects of the
Salaried-Employee and HourlyEmployee classes are also objects of
the Employee class
Object
SalariedEmployee
HourlyEmployee
3
Creating Subclasses
A subclass is defined using the extends keyword to indicate that it inherits
from a superclass
public class SalariedEmployee extends Employee {
The subclass then inherits all non-private instance variables and methods
from its parent class
Instance variables in class Employee should be declared protected so
that they are visible to subclasses but not to the outside world
Methods inherited from the superclass can be overridden in the subclass to
change behaviors
4
Class Inheritance
User ‘super’ to
access the parent
class
5
Constructors in Subclasses
When an object of a subclass is instantiated, a constructor for
its superclass is called either implicitly or explicitly before any
other initialization is performed:
Implicit call to
18
19
20
21
22
23
24
25
26
27
28
29
// Constructors
public SalariedEmployee() {
salary = 0;
}
public SalariedEmployee( String first, String last,
String ssn, double salary) {
// Explicit call to Employee(first, last, ssn)
super(first, last, ssn);
this.salary = salary;
pay = this.salary;
}
default constructor
Employee() before
line 20
Explicit call to
Employee(first,
last, ssn)
6
Lab 1
Create a program called AccountDemo
Create a class ‘Account’ that has private members, ‘name’ and
‘amount’
â—¦ Has constructor to set the name and amount of account
◦ Has method ‘deposit’ to add a deposited amount to the account
â—¦ Has methods getName, getAmount, and setAmount
Create a sub class ‘SavingsAccount’ that simply calls the ‘Account’
constructor with a given amount and the name ‘Savings’
7
Lab 1 Continued
Create a ‘CheckingAccount’ class
◦ The constructor calls the super class constructor with name ‘Checking’ and a given amount
â—¦ Provide a withdraw method
In main method of AccountDemo class
â—¦
â—¦
â—¦
â—¦
â—¦
â—¦
â—¦
Create a new ‘SavingsAccount’ object with initial amount of $10,000
Display the name and the amount
Deposit $5,000 and display the account balance
Create a ‘CheckingAccount’ object with $20,000
Display the name and the amount
Deposit $6,000 and display the account balance
Withdraw $3,000 and display the account balance
8
Lab 1: Output
9
Treating Subclass Objects as Superclass Objects
Since an object of a subclass is also an object of its superclass,
the object can be addressed with either subclass or superclass
references.
This means that objects of many different subclasses can be
combined and manipulated as objects of a single superclass.
10
Treating Subclass Objects as Superclass Objects (2)
Objects
created with
subclass
references
Objects used
with subclass
references
Objects used
with
superclass
references
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Create a SalariedEmployee object
SalariedEmployee s1 = new SalariedEmployee(
"John","Jones","111-11-1111",3000);
// Create an HourlyEmployee object
HourlyEmployee h1 = new HourlyEmployee(
"Jane","Jones","222-22-2222",12.50);
// Create an array of Employee objects
Employee e[] = new Employee[2];
e[0] = s1;
e[1] = h1;
// Caclulate pay using subclass references
System.out.println("Calculation with subclass refs:");
System.out.println("Pay = " + s1.calcPay(160));
System.out.println("Pay = " + h1.calcPay(160));
// Caclulate pay using superclass references
System.out.println("nCalculation with superclass refs:");
for ( int i = 0; i < e.length; i++ )
System.out.println("Pay = " + e[i].calcPay(160));
// List employee info with superclass refs
System.out.println("nEmployee information:");
for ( int i = 0; i < e.length; i++ )
System.out.println("Info: " + e[i].toString());
11
Polymorphism (1)
Defines method1
If a superclass declares a method
method1, then all subclasses of
the class will inherit the method.
Each subclass can override the
inherited method to provide its
own implementation, but they will
all have a method with the
inherited method’s name and
calling parameters.
SuperClass
Object
SubClass1
Overrides method1
with a new
definition.
SubClass2
Overrides method1
with a new
definition.
12
Polymorphism (2)
If objects of the subclasses are treated as objects of the
superclass, and if method1 is called by one of the objects,
then the version of method1 called will automatically be the
correct one for the subclass that the object belongs to.
This behavior is called polymorphism, meaning “many formsâ€Â.
Objects of many types can be processed together, with the
individual behaviors automatically correct for each object.
13
Abstract Classes
If a particular method is overridden in all sub-classes of a
superclass, and if only objects of the subclasses are to be created,
the method code in the superclass will never be executed.
â—¦ If so, then why write the method code in the superclass at all?
â—¦ The method header in the superclass is required for poly-morphic
behavior, but the body of the method is useless.
â—¦ We can declare the superclass method header without writing the
method body. The method becomes an abstract method.
â—¦ A class containing one or more abstract methods is an abstract class.
14
Abstract Classes
An abstract method or class is declared with the abstract
keyword:
public abstract double calcPay( double hours );
No object can be instantiated from an abstract class
Every subclass of an abstract class that will be used to
instantiate objects must provide implementations for all
abstract methods in the superclass.
Abstract classes save time, since we do not have to write
“useless†code that would never be executed.
15
Exampleâ€â€A Shape Class
Superclass:
contains abstract
methods area
and perimeter.
Shape
Object
Circle
Rectangle
Triangle
Subclasses:
implement concrete
methods area and
perimeter.
16
Lab 2
Create a program that contains the abstract class ‘Shape’
◦ Create a ‘counter’ member to keep track of the number of objects
instantiated from this superclass
â—¦ The constructor should increment the counter
◦ Create abstract methods ‘area’ and ‘perimeter’ which will be overridden in
the subclasses
◦ Create method ‘getCount’ to return the number of objects created
â—¦ Create a finalizer to decrement the object count (protected void finalize)
17
Lab 2 (cont)
Create a ‘Circle’ class that is a subclass of the ‘Shape’ class
â—¦
â—¦
â—¦
â—¦
â—¦
â—¦
Has a private member for the radius
The constructor sets the radius
‘Area’ method returns PI*r^2
‘Perimeter’ method returns 2*PI*r
‘toString’ method returns “Circle of radius [x]â€Â
Finalizer should call the super class finalizer
18
Lab 2 (cont)
Create a ‘Triangle’ subclass of the ‘Shape’ super class
â—¦
â—¦
â—¦
â—¦
â—¦
â—¦
Has a private member for the length of a side (s)
Has a constructor that sets the length of a side
‘Area’ method returns sqrt(3)/4*s^2
‘Perimeter’ method returns 3*s
‘toString’ method displays “Triangle of length [x]â€Â
Finalizer calls the super class finalizer
19
Lab 2 (cont)
In ‘main’ method of class
â—¦ Create an array of 2 shapes
◦ Set first element to a ‘Circle’ object of radius 2
◦ Set second element to a ‘Triangle’ object of side 2
◦ Display the number of ‘Shape’ objects created
â—¦ Use a for loop to display the description of each element of array (toString)
and Area and Perimeter of each object
20
Interfaces
An interface is a special type of block containing only method
signatures.
Classes can implement an interface by including an
implements clause in the class header, and defining each
method declared in the interface.
Interfaces exhibit polymorphism. A program can call an
interface method, and the proper version of that method will
be executed depending on the type of object passed by the
method.
26
Example of an Interface
Interface definition
public interface Relation {
// Returns true if a > b
public boolean isGreater( Object a, Object b );
// Returns true if a < b
public boolean isLess( Object a, Object b );
// Returns true if a == b
public boolean isEqual( Object a, Object b );
Method
headers
}
Note that the abstract
keyword is not used in the
interface method headers.
27
Implementing an Interface
public class Line implements Relation {
// Instance variables
private double x1;
private double x2;
private double y1;
private double y2;
//
//
//
//
Note implements clause
First x value
Second x value
First y value
Second y value
...
// Calculate length
public double length( ) {
return Math.sqrt( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) );
}
// Returns true if a > b
public boolean isGreater( Object a, Object b ) {
return ((Line)a).length() > ((Line)b).length();
}
// Returns true if a < b
public boolean isLess( Object a, Object b ) {
return ((Line)a).length() < ((Line)b).length();
}
// Returns true if a == b
public boolean isEqual( Object a, Object b ) {
return ((Line)a).length() == ((Line)b).length();
}
...
Method definitions for all
the interface methods.
Note that the Relation
interface requires
parameters of class
Object, so they must be
cast to Line before use.
}
28
Advantages of Interfaces
Any class can implement an interface, regardless of location in
object hierarchy.
Thus, a method that manipulates the interface can work with
many different types of objects without modification, as long
as all those objects implement the interface.
Example: The method on the next page sorts any objects that
implement the Relation interface, regardless of class
29
Example
public static Object[] sort ( Object[] o ) {
// Declare variables, and define each variable
int i, j;
// Loop index
int iptr;
// Pointer to "smallest" value
Object temp;
// Temporary variable for swapping
This method sorts objects
of any type that
implement the Relation
interface.
// Sort values
for ( i = 0; i < o.length-1; i++ ) {
// Find the minimum value in o[i] through o[nvals-1]
iptr = i;
for ( j = i+1; j < o.length; j++ ) {
if ( ((Relation)o[0]).isLess(
(Relation) o[j], (Relation) o[iptr] ))
iptr = j;
}
// iptr now points to the min value, so swap
// o[iptr] with o[i] if iptr != i.
if (i != iptr) {
temp = o[i];
o[i] = o[iptr];
o[iptr] = temp;
}
Note that the objects must
be cast to type Relation
in order to use the
interface!
}
// Return sorted objects
return o;
}
30
Project 1
package Project;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import chapman.graphics.JPlot2D;
public class Project1 {
private static final int MAX_SAMPLES = 10;
private static final int PROCESSES = 2;
private static double[][] tcData = new double[MAX_SAMPLES][PROCESSES];
private static double[][] fcData = new double[MAX_SAMPLES][PROCESSES];
public static void main(String[] args) {
try {
int i = 0;
int j = 0;
Scanner sc = new Scanner(new File("data.txt"));
boolean trueclass = true;
while (sc.hasNextDouble()) {
double d = sc.nextDouble();
if (d == 1) {
break;
}
if (trueclass) {
tcData[i++][j] = d;
} else {
fcData[i++][j] = d;
}
if (i % 10 == 0) {
j++;
i = 0;
if (j == 2) {
trueclass = false;
j = 0;
}
}
}
sc.close();
String heading = "X1 TRUE X2 TRUE X1 FALSE X2 FALSE";
String separators = "------- ------- -------- --------";
System.out.println(heading);
System.out.println(separators);
for (int k = 0; k < MAX_SAMPLES; k++) {
System.out.printf("%-7s", tcData[k][0]);
System.out.printf(" %-7s", tcData[k][1]);
System.out.printf(" %-8s", fcData[k][0]);
System.out.printf(" %-8s", fcData[k][1]);
System.out.println();
}
double[] x1tr = new double[MAX_SAMPLES];
double[] x2tr = new double[MAX_SAMPLES];
double[] x1fls = new double[MAX_SAMPLES];
double[] x2fls = new double[MAX_SAMPLES];
for (int k = 0; k < MAX_SAMPLES; k++) {
x1tr[k] = tcData[k][0];
x2tr[k] = tcData[k][1];
x1fls[k] = fcData[k][0];
x2fls[k] = fcData[k][1];
}
String x1in = JOptionPane.showInputDialog("Enter X1 feature of new sample");
String x2in = JOptionPane.showInputDialog("Enter X2 feature of new sample");
double x1ind = Double.parseDouble(x1in);
double x2ind = Double.parseDouble(x2in);
JPlot2D pl = new JPlot2D(x1tr, x2tr);
pl.setMarkerState(JPlot2D.MARKER_ON);
pl.setMarkerColor(Color.red);
pl.setMarkerStyle(JPlot2D.MARKER_CIRCLE);
pl.setLineState(JPlot2D.LINE_OFF);
pl.addCurve(x1fls, x2fls);
pl.setMarkerState(JPlot2D.MARKER_ON);
pl.setMarkerColor(Color.blue);
pl.setMarkerStyle(JPlot2D.MARKER_TRIANGLE);
pl.setLineState(JPlot2D.LINE_OFF);
double[] w = { 39.0000, -4.7881, -1.3252 };
double[] xVals = new double[MAX_SAMPLES];
double[] yVals = new double[MAX_SAMPLES];
for (int k = 0; k < MAX_SAMPLES; k++) {
xVals[k] = 5 + (9.0 - 5.0) * ((double) (k) / MAX_SAMPLES);
yVals[k] = (w[0] + xVals[k] * w[1]) / (-w[2]);
}
double classification = 1 * w[0] + x1ind * w[1] + x2ind * w[2];
pl.addCurve(new double[] { x1ind }, new double[] { x2ind });
pl.setMarkerState(JPlot2D.MARKER_ON);
pl.setMarkerColor(Color.orange);
pl.setMarkerStyle(JPlot2D.MARKER_SQUARE);
JOptionPane.showMessageDialog(null,
classification >= 0? “The new sample belongs to TRUE class (good fruit)” : “The new sample belongs to
FALSE class (too ripe)”);
pl.addCurve(xVals, yVals);
pl.setMarkerState(JPlot2D.MARKER_OFF);
pl.setLineColor(Color.green);
pl.setLineStyle(JPlot2D.LINESTYLE_SOLID);
pl.setLineState(JPlot2D.LINE_ON);
JFrame fr = new JFrame(“JPlot2D”);
fr.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
fr.getContentPane().add(pl, BorderLayout.CENTER);
fr.setSize(500, 500);
fr.setVisible(true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Purchase answer to see full
attachment