Title: Java Applet and GUI Basics
1Java Applet and GUI Basics
- K.P. Chow
- University of Hong Kong
2Java Applets - Example
- import java.applet.Applet
- import java.awt.Graphics
- public class Simple extends Applet
- stringBuffer buffer
- public void init ()
- buffer new StringBuffer()
- addItem(initializing ...)
-
- public void start ()
- addItem(starting ...)
-
public void stop () addItem(stopping
...) public void destroy ()
addItem( prepare for unloading ...)
3Java Applets - Example (cont)
- void addItem(String newWord)
- System.out.println(newWord)
- buffer.append(newWord)
- repaint()
-
- public void paint (Graphics g)
- g.drawRect(0,0,size().width-1,size().height-1)
- g.drawString(buffer.toString(),5,15)
-
4Applet Execution in a Browser
5Applet Execution in a Browser (cont)
6Applet Execution in Details
7Applet - Drawing Graphics
- import java.applet.
- import java.awt.
- public class GApplet extends Applet
- static final String message
- Hello World
- private Font font
- public void init()
- font new Font(Helvetica,
- Font.BOLD,48)
-
public void paint(Graphics g) g.setColor(Color.
pink) // pink oval g.fillOval(10,10,330,100)
g.setColor(Color.red)// red outline g.drawOval(1
0,10,330,100) g.drawOval(9,9,330,100) g.drawOv
al(8,8,330,100) g.drawOval(7,7,330,100) g.set
Color(Color.black) g.setFont(font) g.drawStrin
g(message,40,75)
8Applet - Drawing Graphics (cont)
9Applet - Reading Applet Parameters
- HTML for the following applet
- ltAPPLET codeColorScribble.class width300
height300gt - ltPARAM nameforeground value0000FFgt
- ltPARAM namebackground valueFFCCCCgt
- lt/APPLETgt
- public class ColorScribble extends Scribble
- public void init()
- super.init()
- Color fggetColorParameter(foreground)
- Color bggetColorParameter(background)
- if ( fg ! null ) this.setForeground(fg)
- if ( bg ! null ) this.setBackground(bg)
-
-
10Applet - Reading Applet Parameters (cont)
- protected Color getColorParameter(String name)
- String valuethis.getParameter(name)
- int intvalue
- try
- intvalueInteger.parseInt(value,16)
-
- catch ( NumberFormatException e )
- return null
- return newColor(intvalue)
-
11Applet - Reading Applet Parameters (cont)
- public String getParameterInfo()
- // used by web browser for info about params
- String info
- foreground,hexidecimal color value,
foreground color , - background,hexidecimal color value,
background color -
- return info
-
- public String getAppletInfo()
- // used by About dialog box
- return Scribble v.0.02
-
12Exercise - Applet Reading Parameters
- Implement StaticLabel class which takes a text
string and displays it centered in an applet.
The font and label can be passed as parameters
from HTML. Following is an example HTML file and
the corresponding display. - lttitlegtStatic Lablelt/titlegt
- lthrgt
- ltapplet codeStaticLabel.class width200
height80gt - ltparam namelabel valueHello, worldgt ltparam
namefontname valueCouriergt - ltparam namefontslant valueitalicgt ltparam
namefontweight valueboldgt - ltparam namefontsize value24gt
- lt/appletgt lthrgt
13Applet Debugging
- Put a main method in any class, even a class that
runs as an applet or a class that isnt the main
routine of your application. - Test individual classes using the main
- Use main as different entry point to different
program - Cut down number of files
- at least 3 files .java, .class, .html
- Use appletviewer
14JAR Files
- Group together a number of files, called JAR
(Java ARchive) - Convenience a program may consist of several
class files, jpg files and audio files - Efficiency reduce overhead of sending several
files - PKZIP was used in JDK 1.0.2
- Use utility jar to create JAR file, e.g.
- jar cvf myJarFile.jar .class .jpg
- HTML tag
- ltAPPLET ARCHIVEmyJarFile.jar CODEmyapplet.class
- WIDTH600 HEIGHT250gt lt/APPLETgt
15JAR Files (cont)
- Java applet to extract noncode files
- import
- public class view extends Applet
- URL MyURL
- Image MyImg
- ImageProducer MyImageProd
- public void init()
- Toolkit toolToolkit.getDefaultToolkit()
- MyURLgetClass().getResource(titan.jpg)
- try
- MyImgProd (ImageProducer) MyURL.getContent()
- catch
-
-
-
-
16GUI Libraries
- Basic areas of functionalities
- Create user interface controls or components,
such as scrollbars, buttons - Support for giving behavior to the controls by
GUI events - Support for grouping and arranging the controls
on the screen - Support for accessing window manager facilities,
such as which window has input focus, reading
JPEG, etc - Related graphics libraries provide support for
graphics operations such as draw an arc, fill a
polygon, etc - Before JDK 1.1
- Java GUI operations supported by AWT (Abstract
Window Toolkit) - Support portability give GUI programmer a common
binary Windowing interface (API) with different
native window systems - GUI methods make calls to native code library,
uses underlying native window system to
manipulate GUI objects
17GUI Programming
- Declare controls declare buttons, menus, etc.
- Event handling implement an interface to provide
the event handler that responds to control
activity - Layout add the controls to container, containers
are what you display on the screen
18Event Handling
- Examples of events
- a mouse is clicked
- an item on a scrollable list is selected
- a button is pressed
- some text is entered into a text field or text
area - Event handling mechanisms
- Old model use inheritance to tie together your
code and the event mode - JDK 1.1 event model use delegation-based model,
register a callback with event-handling classes
19Old Model Event Handling
20Old Model - using action()
- import java.applet.Applet
- import java.awt.
- public class evui extends Applet
- Panel botPanel
- public void init ()
- setLayout(new FlowLayout())
- botPanel new Panel() add(botPanel)
- botPanel.add(new TextField(TextField))
- botPanel.add(new Button(Button 1))
- botPanel.add(new Button(Button 2))
-
21Old Model - using action() (cont)
- public boolean action(Event e, Object o)
- if ( e.target instance of Button )
- String str (String) o
- if ( str.equals(Button 1))
- showStatus(First Button!)
- else if (str.equals(Button 2))
- showStatus(Second Button!)
- else
- return false
- return true
- else if ( e.target instanceof TextField)
- showStatus(TextArea (String) o)
- else return false
- return true
-
22JDK 1.1 Event Handling
- 2 key tasks
- register an event listener (object)
- implement an event handler (method)
- An event listener is an object of a class that
implement one or more event listener interfaces
from package java.awt.event - Delegation event model an event handler is a
method that is automatically called in response
to a particular type of event
23JDK 1.1 Event Handling Example
- import java.applet.Applet
- import java.awt.
- import java.awt.event.
- import javax.swing.
- public class MyButtons extends JApplet
- private JButton pushButton1, pushButton2
- public void init()
- pushButton1 new JButton(Button 1)
- ActionListener alnew ActionListener()
- public void actionPerformed(ActionEvent e)
- applet.showStatus(You pressed
- e.getActionCommand())
-
-
- pushButton1.addActionListener(al)
- add(pushButton1)
24JDK 1.1 Event Handling Example (cont)
- pushButton2 new JButton(Button 2)
- ActionListener al2new ActionListener()
- public void actionPerformed(ActionEvent e)
- applet.showStatus(You pressed
e.paramString()) - pushButton2.addActionListener(al2)
- add(pushButton2)
-
-
25Exercise - Alice in Wonderland
- Program an Alice in Wonderland applet a panel
with 2 buttons, one of which makes the panel grow
larger, the other smaller. - Hint
- Use ActionerListener
- Use resize(int width, int height) which resize a
Container. - resize(d.width10,d.height10) and
resize(d.width-10,d.height-10)
26Event Handling Basic Framework
- Interface SomethingListener has one or more
methods that is called when the corresponding
SomethingEvent occurs - Write a class that implements a SomethingListener
interface - Declare an object, called, say myHandler, of your
class - On your component, called the addSomethingListener
(myHandler) method
27Event Handling Basic Framework (cont)
28Event Handler Interface
29Event Handler Interface (cont)
30Event Handling - example with text
- import java.applet.Applet
- import java.awt.
- import java.awt.event.
- import javax.swing.
- public class MyTextfield extends JApplet
- private JTextField text1, text2
- private JTextFieldHandler handler
- public void init ()
- setBackground(Color.lightGray)
- handler new TextFieldHandler(this)
- text1 new JTextField() // textfield with
default sizing - text1.addActionListener(handler)
- add(text1)
- text2 new JTextField(Enter text) //
textfield with default text - text2.addActionListener(handler)
- add(text2)
-
31AWT Event Handling - action listener with text
(cont)
- class TextFieldHandler implements ActionListener
- private JApplet applet
- public TextFieldHandler(Applet a) applet a
- public void ActionPerformed (ActionEvent e)
- applet.showStatus(Text is
e.getActionCommand()) -
-
32Exercise - Form
- Program an applet that will display a form for
telephone directory enquiry that can capture the
following information - Name (20 characters)
- An indication of whether it is an exact search or
partial search - Address (30 characters)
- An indication of whether it is an exact search or
partial search - A list of districts, e.g. Lai Chi Kok, Cheung Sha
Wan, Tai Po, Yau Ma Tai, North Point, Peak,
Aberdeen - Selection for one of the districts HK, KLN, NT
- 2 buttons Submit Query and Clear (which clear
all input) - Number type phone number, fax number, pager
number, mobile number - Directory type residential, business, government