Transcript Java & GUI

CS4273: Distributed System Technologies and Programming I
Lecture 2: Introduction to Java and GUI
Important References for Java Manuals
• Web site for Java Swing (GUI)
http://download.oracle.com/javase/tutorial/uiswing/
• Web site for Java Swing Event handler
http://download.oracle.com/javase/tutorial/uiswing/events/index.html
• Web site for Java 2 Standard Edition
http://www.oracle.com/technetwork/java/javase/overview/index.html
• Sample Programs
Source codes of demo programs are in unix system: ~jia/www/java/
2
Java: an Object-Oriented Programming Language
Object-Oriented Programming:
• Encapsulation
• Inheritance
• Polymorphism
3
Class and Method Definition
•
class consists of fields and methods:
class class-name [extends superclass]
[implements interface] {
variable declarations;
method declarations;
}
•
method declaration:
[modifiers] returnT method (args) {
statements;
}
public class dummyButton extends JApplet {
String font;
int style, size;
private JButton bold, italic;
public void init() {
bold = new JButton("BOLD");
add(bold);
add(italic = new JButton("ITALIC"));
font = "Helvetica";
style = Font.PLAIN;
size = 48;
}
public void paint(Graphics g) {
super.paint(g);
g.setFont(new Font(font, style, size));
g.drawString("Hello Java!", 50, 100);
}
class butnhandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
………}
4
Object Initialization and Constructor
•
•
All variables must be initialized before use. Java automatically sets some
initial values for variables of the class, but not variables in methods.
A constructor is a special method, with the same name as the class, for
initialization. Java provides an empty & no-argument constructor if a class
does not have one.
class Rabbit {
int Age;
Rabbit (int Age) { //constructor
this.Age = Age; }//differentiate from the Age in the parameter
void run(int duration,boolean zigzag){ ... }
}
class RabbitGame {
public static void main(string[] args) {
Rabbit bunny = new Rabbit(3);
….
}
5
Class Inheritance and Method Overriding
•
•
•
When a method has the same
name as in the superclass, the
method overrides the one in
superclass. Otherwise the
superclass methods are
inherited with no change.
The top class in Java is
“object”. Every class is a
descendent of object
(implicitly inherited).
Keyword super refers to the
superclass’ methods or
variables.
class Animals {
int Age;
Animals (int Age) { this.Age = Age; }
void wish ()
{ System.out.println ("I want to eat"); }
}
class Rabbit extends Animals {
.. .. ..
Rabbit (int Age, char Color) {
super (Age);
// call super constructor
this.Color = Color;
}
void wish () {
// method over-ride
super.wish();
// call a super method
System.out.println("I want a carrot"); }
}
Rabbit my_rabbit = new Rabbit(3, ‘B’);
my_rabbit.wish();
// ? output ?
6
Modifier: static
•
•
•
A variable or method defined as class Rabbit {
static means that the variable
static int rabbits_count = 0;
or the method belongs to the
int Age;
class, and they are not with
Rabbit (int Age) {
objects.
rabbits_count++; // access static var
Static variables / methods are
this.Age = Age;
class variables / methods. There
}
is only one copy of them in the
static int count() {// only use class variable
system.
return rabbits_count;
Class methods can only access
}
class variables. It cannot use
}
“this” reference, cannot call
Object Template
normal methods, etc. But
static vars,
…
normal methods can access
class variables.
object
object
7
Modifiers: public, private, protected, final
•
•
•
•
public: can be used everywhere.
private: can be used only in its own class, not even from its subclass.
protected: can be accessed within its own package.
final defines:
– a class can’t be extended
– a method can’t be overridden
– a variable cannot be modified (constant)
final class Rabbit extends Animal {
final float  = 3.14;
….
final int run(int duration, boolean zigzag) { …. } // method 1
}
8
Abstract Methods and Abstract Classes
•
•
•
An abstract method is a method that has no implementation. It allows
subclasses to implement the method according to their own needs.
An abstract class is a class that contains at least one abstract method.
An abstract class must be FULLY implemented before it can be
instantiated.
abstract class Animals {
int Age;
Animals (int Age) { this.Age = Age; }
abstract void wish ();
}
class Rabbit extends Animals {
.. .. ..
void wish () {
// implement the abstract method
System.out.println("I want a carrot"); }
}
9
Interface and its Implementation
•
•
•
An interface is a class that all its methods are abstract.
There are many interfaces in Java, especially for event handlers, that
require implementations.
When defining a class which implements an interface, uses the format:
class xxx implements interface {
method declaration;
…….
method declaration;
}
•
If a class implements some methods of an interface, not all of them,
then this class becomes an abstract class.
10
Graphical User Interface (GUI)
Containers and Components
• Containers provide a rectangular display area in which
components are positioned. A container can also contain
other containers.
• Components are positioned relative to the top left corner
(0,0) of its container and are located using the container’s
coordinate space.
• Components are added to a container using the add()
method.
11
Containers/Components
Containers:
JFrame, equivalent to windows.
JPanel, applet’s display area is JPanel. It is often used to organize
components together in display.
Atomic Components:
JButtons (JCheckBoxes, JRadioButtons)
JComboBox
JLabels
JTextField (JTextArea)
Popup menus
ScrollPane
12
A Simple Example of Buttons
public class dummyButton extends JApplet {
public void init() {
setLayout(new FlowLayout(FlowLayout.CENTER));
bold = new JButton("bold");
add(bold);
add(italic = new JButton("italic"));
}
public void paint(Graphics g) {
super.paint(g);
g.setFont(new Font(MyFont, MyStyle, MySize));
g.drawString("Hello Java!", 50, 100);
}
………..
13
Java Event Handling Model
• When user clicks a button or presses a key, an
event is generated. The button clicked is called
“event source”.
• For each event source, you need to delegate a
Listener object to listen to it.
• When the listener object hears an event, it
invokes a method to process the event.
button
Listener
Object
Event
bold = new JButton(“bold”);
bold.addActionListener(new BtnHandler());
public class BtnHandler implements ActionListener
{ …….
public void actionPerformed (ActionEvent e)
{
// code to handler start button }
}
14
Make Buttons Responsive
The steps making buttons responsive:
1. write an event handler which
implements interface
ActionListener. Interface
ActionListener has only one
method actionPerformed.
2. implement method
actionPerformed in the interface.
3. add action listener (your event
handler) to each event source.
public class dummyButton extends JApplet {
public void init() {
add(bold = new Button("bold"));
bold.addActionListener (new butnhandler());
…. }
class butnhandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (e.getSource() == bold)
style = Font.BOLD;
if (e.getSource() == italic)
style = Font.ITALIC;
repaint();
}
}
}
15
TextField
Textfiled is used for getting Text Input from users.
• TextField is constructed as:
JTextField tf = new JTextField(“input here”, 20);
add(tf);
• an “action” event is generated when the user types “return” in a
TextField. You need to add an event-handler to the JTextField object by:
tf.addActionListener (new actionAdapter());
• get the input text by:
String InputStr = tf.getText();
• set the text field (for display) by:
tf.setText(“wrong input”);
16
TextArea
TextArea is used to display or edit a number of rows and cols.
There is no event handler associated with it. It can be used
with ScrollPane to make it scrollable.
• TextArea can be constructed by:
JTextArea ta = new JTextArea(row, col);
• display text in a TextArea by:
ta.setText(String str); OR
ta.append(String str);
• get the whole text in TextArea by:
ta.getText();
17
Event handling for TextField
JTextField event is “action” type:
class TextHandler implements ActionListener {
// jia/www/java/gui/textField.java
public void actionPerformed (ActionEvent e){
public class textFieldTest extends JApplet {
if (e.getSource() == textin) {
JTextField textin, textout;
textArea.setText(textin.getText());
JTextArea textArea;
textout.setText(textin.getText());
public void init() {
}
}}}
setLayout(new FlowLayout());
add(textin = new JTextField("",20));
textin.addActionListener (
new TextHandler ());
textArea = new JTextArea(10,20);
add(textArea);
add(textout = new JTextField("initial",20));
}
18
GUI Event Handlings
•
Action Events. Event sources:
– JButton, List,
– JTextField,
– JMenuItem, etc.
•
Item Events. Event sources:
–
–
–
–
•
JCheckbox,
JButtonGroup (RadioButton),
JComboBox
JChoice (Pop-up menu)
Mouse Events.
– Mouse press / release
– Mouse drag / move
•
Key Events
– Key press / release
– Key typed
…………
19
CheckBox, ButtonGroup (RadioButton)
Checkbox allows users to tick (true / false). A checkbox can be used independently.
• a Checkbox is created by:
new JCheckbox();
ButtonGroup is a group of checkboxes, only one of them can be selected.
• a ButtonGroup is created by:
g = new ButtonGroup();
• a RadioButton is created & added to Group by:
btn = new JRadioButton();
g.add(btn);
// add btn to group g
•
•
•
When a checkbox is clicked, an event of type ItemEvent is generated. A handler for
ItemEvent type of events implements the interface ItemListener.
Interface ItemListener has only one method itemStateChanged(). You need to
implement it.
For each checkbox, an event handler (an object of type addItemListener) should
be added to it.
20
Choice and Event Handler
•
•
Choice is a drop-down menu of choices, created by
c = Choice().
A choice item is added in by:
c.addItem(“item”);
•
An “item” event is generated when an item of the Choice is selected
and you can get the item by:
String e.getItem();
•
•
// c is a choice
// e is the event
Choice event handler is the same as CheckBox, which implements
interface ItemListener. ItemListener has a method
itemStateChanged (ItemEvent e).
An event handler object must be added to a Choice (the entire dropdown menu) by:
addItemListener()
21
Mouse Event and Handler
•
•
•
•
Two interfaces, MouseListener and MouseMotionListener,
are for mouse events. Two adapters MouseAdapter and
MouseMotionAdapter are provided for the interfaces. You
may either implement the interfaces or extend the adapters.
Mouse events include click, press, release, move, drag
(press-move), etc.
You need to implement all the methods in interfaces or
redefine (override) the necessary methods in adapters.
Add an Adapter object to the window in which you want to
catch mouse events.
22
Event Listener Interface and Adapter
•
•
For easy programming, some listener interfaces have
Adapter classes, which have default implementations of
all methods in the respective interfaces.
If the Adapter of a listener interface is provided, you don’t
have to implement the whole interface. You only need to
override some methods necessary to perform your work.
23
Example of Mouse Event Handler
//file:mouseDrawAline.java
import java.awt.event.*;
public class mouseDrawAline extends JApplet {
Point start = new Point(0,0), end = new Point(10,10);
public void init() {
addMouseListener(new myMouseAdapter());
addMouseMotionListener(
new myMouseMotionAdapter());
}
public void paint(Graphics g) {
super.paint(g); // clear existing paintings
g.drawLine(start.x, start.y, end.x, end.y);
}
class myMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent e) {
start.x = e.getX(); start.y = e.getY();
}
public void mouseReleased(MouseEvent e) {
end.x = e.getX(); end.y = e.getY();
repaint(); }
}
class myMouseMotionAdapter extends
MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
end.x = e.getX(); end.y = e.getY();
repaint();
}
}
24
Keyboard Event
• The interface for keyboard event handler is KeyListener.
• KeyListener has an adapter KeyAdapter. A keyevent handler class can
either implement KeyListener interface, or extend KeyAdapter class.
• Three methods defined in KeyListener:
– keyPressed (keyEvent), called when any key is pressed
– keyTyped (keyEvent), called only when a non-function key is pressed
– keyReleased (keyEvent), called when a key is released after keyPressed
or keyTyped event.
• Three methods on keyEvent allows you to get keycode:
– event.getKeyCode()
– event.getKeyChar(), get printable letter of the key
– event.getKeyText(keyCode), get string name of the key
25
Keyboard Event
public class keyTest extends JApplet {
public void init() {
setLayout (new BorderLayout ());
JTextArea textArea = new JTextArea( 30, 30 );
add("Center", textArea);
textArea.addKeyListener(new
myKeyAdapter());
}
class myKeyAdapter extends KeyAdapter {
public void keyPressed( KeyEvent event ) {
int keycode = event.getKeyCode();
String line = "Key pressed code: "+keycode;
line = line+ " & Text: "+
event.getKeyText(keycode);
textArea.setText(line+"\n");
}
public void keyTyped( KeyEvent event ){
textArea.append("Key typed: "+
event.getKeyChar()+"\n");
}
public void keyReleased(KeyEvent event ) {
textArea.append("Key released: "+
event.getKeyChar());
}
26
Event Processing Model in Java:
Event Types and Adapters
Java.lang.object
Java.awt.event.ComponenetAdapter
Java.awt.event.KeyAdapter
Java.awt.event.MouseAdapter
Java.awt.event.MouseMotionAdapter
Java.awt.event.WindowAdapter
Java.awt.event.ContainerAdapter
……………..
27
Event Dispatching
•
•
•
Each component in a container is an object that has two methods,
dispathEvent() and processEvent().
When an event is generated by an external device (mouse, kbd, etc), the outmost container’s dispatchEvent() is invoked, which dispatches the event
recursively layer by layer to the right component (i.e., event source).
When a component finds itself is the source of the event, it calls
processEvent(e) to process the event.
// dispatch an event to the right component
void dispatchEvent(AWTEvent e) {
……
if (newEventsOnly) {
if (eventEnabled(e)) {
processEvent(e);
}
…….
}
28
Process Event
Method processEvent() of the component is the
root of all of the event-type processing functions.
case MouseEvent.MOUSE_EIXTED:
processMouseEvent((MouseEvent)e);
break;
case MouseEvent.MOUSE_MOVED:
case MouseEvent.MOUSE_DRAGGED:
protected void processEvent(AWTEvent e) {
if (e instanceof FocusEvent) {
processFocusEvent((FocusEvent) e);
} elseif (e instanceof MouseEvent) {
switch(e.getId()) {
processMouseMotionEvent((Mouse
Event)e);
break; }
} else if (e instanceof KeyEvent) {
processKeyEvent((KeyEvent)e);
} elseif (e instanceof ComponentEvent) {
case MouseEvent.MOUSE_PRESSED:
case MouseEvent.MOUSE_RELEASED:
case MouseEvent.MOUSE_CLICKED:
case MouseEvent.MOUSE_ENTERED:
processComponentEvent((CompEve
nt) e); }
}
29
MouseMotion Event Handler (example)
•
Method addMouseMotionListener(mymouseMotionAdapter) does:
mouseMotionListener  mymouseMotionAdapter
•
Methods .mouseMoved or .mouseDragged are implemented by you.
protected void processMouseMotionEvent(MouseEvent e) {
if (mouseMotionListener != null) {
int id = e.getId();
switch(id) {
case Mouseevent.MOUSE_MOVED:
mouseMotionListener.mouseMoved(e);
break;
case Mouseevent.MOUSE_DRAGGED:
mouseMotionListener.mouseDragged(e);
break;
}
}
}
processEvent
processMouseMotionEvent
userHandlerObj.mouseMoved
30
action Event Processing
•
•
Button’s event handler overrides
processEvent(). For action event, the
code in the right-hand box is
executed.
addActionListener(myactionAdapter)
does:
actionListener  myactionAdapter
protected void processEvent(AWTEvent e) {
if (e instanceof ActionEvent) {
processActionEvent((Actionevent) e);
return;
}
super.processEvent(e);
}
processActionEvent(ActionEvent e) {
if (actionListener != null)
actionListener.actionPerformed(e);
}
31
Window Layout
•
•
•
•
The default layout manager of content-panes is
BorderLayout(); the default layout for JPanel is
FlowLayout();
The default layout manager can be disabled by
setLayout().
The common layouts are FlowLayout, BorderLayout, and
GridLayout.
Use JPanel to effectively organize components in different
layouts and then arrange the JPanels in top-layer Layouts.
32
Flow Layout
• FlowLayout(align, hgap, vgap);
• setLayout(new FlowLayout(FlowLayout.CENTER));
33
Border Layout
• BorderLayout()
• To add components into a
container with BorderLayout,
the add method needs to specify
“North”, “South”, “East”,
“West”, or “Center”.
• The component at the Center
automatically fills the whole
unoccupied rectangle area from
the center.
34
Grid Layout (Cont.)
• GridLayout(rows, cols, hgap, vgap)
• When adding components into a frame with GridLayout, it fills the
row from left to the right before moving to the next row.
• Example of displaying a calculator pad:
public class calculator extends JApplet {
public void init() {
setLayout(new GridLayout(3,4,5,5));
add(new Button(“0”));
……
add(new Button(“9”));
}
35
Use Panel to Organize Components
~jia/www/java/gui/layoutTest.java
36