You are on page 1of 6

Refer to web site for notes & programs: Java-Express-Intro and Java-Examples

0.

Objective

Illustrate basic Java concepts such as classes, objects or instances of classes, the
simple development tool TextPad; the idea of events on objects & how events can be used
to trigger responsive actions to the events; basic graphical interface elements like
textfields & buttons and the underlying "infrastructure objects" like "frames" (windows)
& panels & 'content panes' used as 'containers' to hold the more directly user related
objects like fields and buttons.
1.

Demonstrate Behaviors

Demonstrate the behavior of a simple calculator in Java: Y.java and TestY.java


(also an analog in JavaScript Y.html). Run TestY.java. There will be two windows: (1)
the dos window for standard output from the program and for error message output and
(2) the window created by the Java program. You can maximize, resize the windows, etc.
Observe the program response to good data and how bad input causes run-time error
messages in the stdout Dos window (such as: Y.actionPerformed (Y.java:30)) - but the
program does not terminate.
1.

Demonstrate Compilation/Execution

Illustrate compiling & running a Java program. The "class" Y - that is the
calculator object or class - is a blueprint describing the structure of the object. In
TextPad, the shortcuts ctrl+1 compiles the program and ctrl+2 execute the class. Observe
what happens when you compile Y.java class: it creates a file called Y.class. If you try to
execute this class directly you will get an error message "java.lang.NoSuchMethodError:
main" which means you have to run this class from a main program. Similarly, if you
try to execute TestY.java without first compiling it, you will get the error message:
"java.lang.NoClassDefFoundError: TestY". Observe that if you compile the main class
after first deleting the Y.class file, then this triggers compilation of both the main class
and the Y class (Keep an eye on the directory where the files are located so you can see
the compiled class appear.) To execute the program, use ctrl+2. Resize the window that
appears in order to improve the layout of its GUI elements.
3.

Making Instances of Y in TestY

The program (class) TestY creates an instance m of the class Y. Note the
following naming conventions:
class
Y
constructor Y ( )
stored in file Y.java

Make multiple instances, change the window size using the setSize method; test the
setVisible method; shrink-wrap the GUI components using the pack ( ) method. Test the
effect of these methods by placing a read IO statement (such as MyInput.readString( )) to
stall the program execution in order to better understand the method effects. This requires
the MyInput class contained in the directory. the other import statements at the top of the
program import other java class libraries (called packages). Understand the reference to
the Y constructor in the TestY main program. Compare this syntax with declarations like
int K = 3 or double pi = 3.14 except that here it's Y m = new Y( ). If we had renamed
the class Y as Calculator, it could have been more clearly written as: Calculator calc =
new Calculator ( ) corresponding to a class Calculator in a file Calculator with a
constructor Calculator ( ).
Build Blueprint for Calculator class
Establish GUI Component Infrastructure:
1. Initially:
a. Make the class under definition an "extension" of the window or "JFrame"
class. By inheritance this allows the new class to use all the properties and methods
(functions) already defined for the JFrame class methods like setVisible and setSize.
b. Set up the window infrastructure in the 'constructor' for the class. This
includes a so-called panel (JPanel) that you can throw (or 'add') GUI components to, as
well as the so-called "ContentPane" into which the panel itself is added.
2. Declare, and eventually create and add to the window (JFrame extension) the GUI
objects like JTextField, JLabel, JButton.
Specify Event-handling Infrastructure:
3. This includes first indicating (to the compiler) that this class handles button events by
saying it 'implements ActionListener'.
4. Make the buttons sensitive to events (like being clicked) - a process called event
registration in Java.
5. Define an "event-handling" routine (method) to take charge whenever an event occurs.
Also must tell the environment the class is able to handle a certain class of events.
6. Event-handler algorithm This recognizes which button caused the event, gets data
from the fields, converts the data to integer, do the appropriate arithmetic operation
(which the handler can recognize by checking which button caused the event), then send
the results to the output field in the window.

When developing example:


1.
2.
3.
4.
5.
6.
7.

Make a driver that creates a trivial empty JFrame:


Make the JFrame constructor write to the Dos prompt:
Add a JTextField object.
Add a button that triggers write to Dos prompt:
Access data from field and write to prompt as String:
Write (altered) input data to prompt as int.
Finish up with more fields and computation.

It's a window!
It's Alive !
It appears.
It acts.
It reads.
It stores.
It computes.

a. Define a 'shell' version of the class: Define X to contain merely an empty class
invoke from appropriate main class but will get compilation error (check error
messages) because main class tries to use methods like setSize that don't exist for this X
class it has to be declared as an extension of a frame (window) class so it 'inherits'
the frame class methods.
b. Make the 'shell' extend JFrame Compile & run. Get a shrink-wrapped window:
notice what happens if you comment out the pack method: the window then maintains the
size it was set at. Then add an explicit constructor for the class including a little
statement to standard output like "System.out.println("I live");" to show it's really alive.
c. Start adding GUI objects like with: "JTextField text = new JTextField(20);" Notice
nothing appears in the still shrunk window that's because we have not done the
necessary preparatory work which here means: making a panel, adding to the frame's
pane (or contentPane), then adding the text field to the panel. The pane is the part of the
frame below the title bar at the top of the frame to get a hold of it you use
getContentPane() specifically this.getContentPane ( ) i.e.: "this instance of the X
object's content pane." Incidentally note Java's case-sensitivity & naming spelling
conventions. The statements:
JPanel panel = new JPanel();
this.getContentPane().add(panel);
provide the infrastructure for the GUI objects which we then add with:
panel.add(text);
Then add the rest of the GUI text fields & buttons:
JTextField text1 = new JTextField(20);
JTextField text2 = new JTextField(20);
JTextField text3 = new JTextField(20);
and the buttons:
JButton but1 = new JButton("add");
JButton but2 = new JButton("mult");

Note the capitalization for the reserved words like JTextField, JButton, and JPanel. Later,
we'll move the declarations of the fields & buttons outside the constructor so they can
accessed by the event-handler we will define. For now, just add them to the panel.
Check the look of the window resize to taste and note the buttons are at this point
decorative only and do not trigger any action or response when clicked.
d.

Set up the event-handling:

i.
ii.
iii.
iv.
v.

register the buttons as event sources


give the signature for the corresponding (dummy) event-handler
tell compiler this class handles these events
put a message in the handler compare add v. mult before mult registered
make the event-handler recognize the event & respond to it

i.
ii.
iii.
iv.
v.

but1.addActionListener(this);
public void actionPerformed(ActionEvent e){ }
implements ActionListener
System.out.println("hi there");
Be sure the declarations are outside the constructor so they are global &
accessible to the event handler and remove the declarations inside the constructor.
Test effect. Write the conversion line in reverse starting mentally with the getText
method and working back to the declaration.
int num1 = Integer.parseInt(n1.getText()) ;
To prep the number calculated in the program for output to the JTextField:
n3.setText(String.valueOf(num3))

Time permitting describe use of try/catch construction:


try{} catch(Exception x){System.out.println("bad data");}
to intercept runtime errors resulting from bad input data.

The in-class lab below illustrates many of the basic concepts in objectoriented, event-driven, GUI interface design.

In-class Lab: Make Colorizer Interface.

Red

colorMe

Green

reSize

Blue

spawn

See if you can also implement buttons that (1) change the size of the window and (2)
spawn a new Colorizer window object.
Lab steps:
1. Set up a driver main program TestColorizer and a trivial shell for a Colorizer
class. The Colorizer class should say 'extends JFrame'
2. Test TestColorizer for compilation and run time errors. Just shows window.
3. Add a constructor with a println statement.
4. Add a JTextField to the Colorizer class. This requires a JPanel added to a content
pane to which the JTextField is added. Declare the JTextField as well.
5. Add a button that says "colorMe".
6. Register the button with an addActionListener method. This will also require
including the directive 'implements ActionListener' at the class declaration.
7. The above will trigger an error without the standard event handler for this type of
event: the actionPerformed method. Add a dummy version of that and test syntax
with compile.
8. Fill out the event handler by first just using a println to echo to the standard output
window.
9. Acquire and convert to integer the data from JTextField. Test conversion with
println. Use the basic syntax:
Integer.parseInt(Num1.getText ( ) )
10. Create a Color object with the syntax:
c = new Color (R, G, B);
where x, y, and z are the converted integers picked up from the JTextFields.
11. Set the background color of the JPanel with the panel method;
setBackground ( c )
12. Do the resize by reusing the same (first two) JTextFields and the setSize method
on this instance.

Points to keep in mind;


1.
2.
3.
4.
5.
6.

Get your import statements right.


The class and file name should match.
Include a main program with the correct signature in the driver program.
End statements with semi-colons.
Use 'extends JFrame' to build a window type class.
To enliven a button, use:
a. implements actionListener
b. addActionListener
c. actionPerformed event handler
7. Declare objects globally within class so they can be accessed by its methods.
8. Name newly created object instances so they can be referred to by name.
9.
Error Messages
Mistake:
omit 'extends JFrame'
semi-colon expected

Message
can't resolve symbol; method setVisible or setSize
such as if { omitted

You might also like