Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
GRAPHICS PROGRAMMING
Section A – Java
1 - Introduction
2 - Installation & First Programs
3 - GUI: Swing & Input Dialog Box
4 - GUI: JFrame
5 - GUI: JButton
6 - GUI: Look and Feel
7 - GUI: JList
8 - GUI: Layout Managers
9 - GUI: JMenu
Gary Hill
December 2003
Java 1 of 1
GRAPHICS PROGRAMMING
1 Introduction
Syllabus, Teaching & Learning Strategy, Assessment Schedule, Resources.
Integrated Development Environments (IDE's)
In theory, it is easiest to use an IDE, even 'Sun strongly encourages the use of a professional
Integrated Development Environment (IDE)'. Although these will be mentioned below, this
course will initially use the JDK via the command line.
Borland http://www.borland.com/jbuilder/personal/
JBUILDER PERSONAL
•
JBuilder 9 Personal
If you already have the JBuilder Personal software and need your activation key, get your
activation key here
What is JBuilder 9 Personal?
Speed coding and debugging with an integrated, extensible source code editor, graphical
debugger, compiler, visual designers, timesaving wizards, sample applications, and support
for Java standards. Get started quickly using the included tutorials. Develop on the
Windows,® Linux,® and Solaris® platforms. Rapidly build Java applications using the
Borland AppBrowser™ integrated development environment, refactorings, build and
configuration management tools, CVS version control, and Two-Way-Tools.™ Easily create
JavaBeans® with BeansExpress.™ Speed coding and reduce syntax errors with
CodeInsight™ and ErrorInsight™ technologies.
JBuilder Personal is a fully functional, entry-level version of JBuilder for personal, noncommercial use. The JBuilder Personal license does not expire.
To install the latest jdk within JBuilder you will need to go to:
Project - Default project properties - Paths - jdk -..... change jdk etc..
Also Java 3D will need to be set up following the instructions from the Borland Developer
Network.
Sun One Studio 4
The Sun[tm] ONE Studio 4 (formerly Forte™ for Java™ ) software is available for
immediate download so you can quickly begin taking advantage of this robust integrated
development environment to boost your productivity. Choose from versions for the
Solaris™, Linux, or Windows platforms, available in both English and Japanese languages.
Before You Download
•
Read the Getting Started Guide for installation and configuration information:
o Community Edition (PDF)
Gary Hill
December 2003
Java 2 of 2
GRAPHICS PROGRAMMING
Enterprise Edition for Java (PDF)
Mobile Edition (PDF)
Read the product family Release Notes and the Mobile Edition Release Notes for the
latest information on the product.
The Sun ONE Studio product requires additional software products, which are
available on the Sun ONE Studio product CD, or from the following downloads:
o Java™ 2 Platform, Standard Edition, v. 1.4 (J2SE™ 1.4) software
If you are an Early Access customer planning to upgrade to the released product,
please read our FAQ on moving from Early Access software to the released version.
o
o
•
•
•
Gary Hill
December 2003
Java 3 of 3
GRAPHICS PROGRAMMING
2 Installation & First Program
Installation
The course will be using the latest version of Java 2 (SDK 1.4.2). Download this and the
accompanying documentation from Sun:
•
•
Java[tm] 2 Platform, Standard Edition, v. 1.4.2 (J2SE[tm]1.4.2) software filename:
j2sdk-1_4_2-windows-i586.exe
Documentation j2sdk-1_4_2-doc.zip
Install in a directory: C:\j2sdk1.4
2003/2004 Install Recommendations
Java SDK
Step 1: Install j2sdk-1_4_2-windows-i586.exe in the directory c:\j2sdk1.4
Step 2: Install j2sdk-1_4_2-doc.zip in the directory c:\j2sdk1.4
Forte IDE
Step 3: Install j2sdk-1_4_0-forte_ce-4-bin-windows.exe in the recommended directory e.g.
c:\forte_jdk. forte should locate the previously installed sdk in c:\j2sdk1.4
Java3D
Step 4: Install java3d-1_3_1-windows-i586-opengl-sdk.exe in c:\j2sdk1.4
Step 5: Install java3d-1_3_1-doc.zip in the directory c:\j2sdk1.4
For Win 95/98
Edit your 'autoexec.bat' file to include the following: PATH c:\j2sdk1.4\bin;
Gary Hill
December 2003
Java 4 of 4
GRAPHICS PROGRAMMING
For Win NT/2000
Edit the 'Systems Variables' PATH (Control Panel>System> Environment) to include: PATH
c:\j2sdk1.4\bin;
For Win XP
Edit the 'Systems Variables' PATH (Control Panel>System>Advanced>Environment
Variables) to include: PATH C:\win....; .... C:\jdk1.4\bin; ...
To check the above works type javac and java in a command window. If correct various help
information will be displayed.
Hopefully, the above should work. For further details consult Cadenhead & Lemay (2000) or
www.sun.com.
Text Editor
Notepad is a useful text editor, but has the limitation that the code syntax is not highlighted.
All IDE's use colour-coded syntax highlighting, which assists programming.
One such editor available under the GNU license which is 'freeware' is Jext (Java Text
Editor) at www.jext.org
Jext does not just syntax highlight for java, but many more languages such as ASP, C, C++,
Eiffel, Java, JSP, Perl, PHP3, HTML, TeX, XML... The latest Jext version was 3.1 is
2.2MB download size. There will be other editors available with syntax highlighting, but this
is just one that will be suitable for java programming.
File Administration
Before writing your first application and applet, make a directory for your Java files (md
c:\java (Win) or mkdir java (Unix/Linux)).
Remember to always make a safe copy of your work on floppy disk, you may need it at a
later date!
Coding Conventions
public class HelloApplication
Class names start with an uppercase letter and each successive word.
private int age;
private int initialAmount;
Variable names start with a lowercase letter, but each successive word should be an
uppercase letter.
public void showSquares()
Methodnames start with a lowercase letter, but each successive word should be an uppercase
letter.
static final int MILES_PER_KILOMETER
Constant are all uppercase letters with each word separated by an underscore..
For further details regarding Java Code Conventions see thefollowing Sun: Java Code
Gary Hill
December 2003
Java 5 of 5
GRAPHICS PROGRAMMING
Conventions ( JavaCodeConventions.pdf 82 KB ) or
http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
First Program (Using the JDK)
Follow the notes from the Your First Cup of Java: to write your first 'application' and 'applet'.
Comments
There are three ways to identify comments. The first two are the same as those used in
C/C++.
Single line comments use: // prints ‘Hello, world!’ to the screen with
a line break.
Multiple line comments use:
/* It is important to carefully work through each line of
source code and enter verbose comments.
Use a reference book or the web to help you understand and
comment the code.
Good programing practice dictates that you should include a
block of header information that
gives a summary of all the key program information. As a
minimum include those in
'HelloApplication.java' below.
*/
The third type of comment /**...............*/ can be used to assist in the
generation of Java Documentation. HTML code can also be embedded within these
comments. To generate the documentation type 'C:\java>javadoc -author -version
HelloApplication.java' and an HTML file will be produced 'Generating
HelloApplication.html'. This is a useful way of documenting a large program.
/**
Program:
Application to say 'Hello World'
Filename: HelloApplication.java
@author:
© Gary Hill (200WXYZ)
Course:
BSc Computing
Module:
CSY3019 Graphics Programming
Tutor:
Gary Hill
@version: 2.0 Incorporates name and age!
Date:
20/09/02
*/
public class HelloApplication
{
public HelloApplication()
{
int age = 21;
String name = new String();
// default constructor to create
empty string
name = "Gary";
// assignment operator, assigns
"Gary" to name
{
Gary Hill
December 2003
Java 6 of 6
GRAPHICS PROGRAMMING
System.out.println("Hello World,\nMy name is "+name+" and I am
"+age+" years old.");
}
}
public static void main(String[] args)
{
HelloApplication hello1 = new HelloApplication();
}
}
new: The new operator is a 'dynamic memory allocation operator' and is used to 'create an
instance' or 'instantiate an object' (See Appendix: Definitions in Object-Oriented Java
Programming).
First Application (Forte for Java)
This description relates to the use of Forte for Java, Community Edition v4.0. Forte is a
complex Integrated development environment IDE. The simplest way to run your first java
application is as follows:
Open Forte
Select File, Open then your HelloApplication.java file from your java directory.
Forte will ask you whether this file should be in the default package. Accept this and
continue. This will mean that your java directory is used as the default directory for all your
remaining projects i.e. your *.java & *.class files are saved in this directory.
Linux
On Linux Red Hat (Gnome desktop) in MY22, 20 & 32 Sun One is installed in the usr/local
directory. It is useful to add a 'launcher' to your lower toolbar as follows:
Start/Foot>Panel>Add to panel>Launcher
Gary Hill
December 2003
Java 7 of 7
GRAPHICS PROGRAMMING
In the 'Create launcher applet' fill in the following details:
Name:
Sun One
Comment: Forte Community Edition 4
Command: /usr/local/forte_4j/bin/runide.sh
Type:
Application
Icon:
/usr/local/forte_4j/bin/icons/ide.ico
Applets
To view your applet you can use a java enabled browser, butit is simpler to use the JDK's
'appletviewer.
A novel way to run your applet without writing a separate HTML file, is to embed your
<applet> code at the headof your java source code.
This enables you to quickly develop and test your applets:
/**
Program:
Filename:
@author:
Course:
Module:
Tutor:
@version:
Date:
*/
Applet to say 'Hello World'
HelloApplet.java
©Gary Hill (200WXYZ)
BSc Computing
CSY3018 Graphics Programming
Gary Hill
2.0 commented
05/07/02
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
import java.applet.*; //enables access to the java.applet.Applet class
import java.awt.*; //enables access to the java.awt.Graphics class
/*
<applet code="HelloApplet.class" width=200 height=60>
</applet>
*/
// the applet size is 200 pixels wide by 60 pixels high
public class HelloApplet extends Applet
{
public void init()// paint method (others are init, start)
{
}
public void paint(Graphics g) // Display "Hello World!"
{
g.drawString("Hello world!", 50, 25);
}
}
To view the above applet type:
C:/java> javac HelloApplet.java [to compile the source code HelloApplet.java into the byte
code HelloApplet.class]
C:/java> appletviewer HelloApplet.java
Gary Hill
December 2003
Java 8 of 8
GRAPHICS PROGRAMMING
To run your applet (HellApplet.java) in a java enabled browser an HTML file is required
(HelloApplet.html) as follows:
<html>
<applet code="HelloApplet.class" width=200 height=60>
</applet>
</html>
To view the above applet:
Select the HTML file (HelloApplet.html) from the browser, or type
C:/java> appletviewer HelloApplet.html
First Applet (Forte for Java)
This description relates to the use of Forte for Java, Community Edition v4.0. Forte is a
complex Integrated development environment IDE. The simplest way to run your first java
applet is as follows:
Right click the mouse on the Java applet
Select properties from the popup menu
Select the Execution tab from the properties popup
Click on Default Debugging and select Applet Debugging
Click on External Execution and selct Applet Execution
Applet imports
Gary Hill
December 2003
Java 9 of 9
GRAPHICS PROGRAMMING
import java.awt.*; //enables access to the java.awt.Graphics class
AWT is the Abstract Window Toolkit, which provides the Java graphical user interface
(GUI), in this case access to the Graphics class for the drawString() method.
import java.applet.*;//enables access to the java.applet.Applet class which are required to run
applets.
Alternatively Swing could be used by using the following import:
import javax.swing.*// or import javax.swing.JApplet.
Note:
Ensure that you have compiled and run your first 'application' and 'applet' from above and
named and commented your programs carefully.
Work through Sun's Java Tutorial Getting Started paying particular attention to the:
Lesson: A Closer Look at HelloWorld
Java applets are covered in Sun's Java Tutorial - Lesson: The Anatomy of an
Applet .
Exercise
Write a java application that extends HelloApplication.java, called SquaresApplication.java
that provides the following:
Prints the program name and your name etc. as a title screen
which outputs the squares of all the numbers between 0 and 100 in the format:
square of 0 is 0
square of 1 is 1
sqaure of 2 is 4
Gary Hill
December 2003
Java 10 of 10
GRAPHICS PROGRAMMING
Gary Hill
December 2003
Java 11 of 11
GRAPHICS PROGRAMMING
3 - Graphical User Interface (GUI)
Input Dialog Box & Numerical Output
Swing
Swing which is part of the Java Foundation Classes (JFC) was introduced to further enhance
support for and extend the Graphical User Interface (GUI) components with a pluggable look
and feel (Macintosh, Microsoft, Solaris).
Swing improved numerous Abstract Window Toolkit (AWT) components such as Button,
Scrollbar, Label, etc. which became JButton, JScrollbar, JLabel respectively. New
components were also introduced e.g. tree view, list box, and tabbed panes etc.
Using Swing contents pane and formating numerical output.
The Applet ( JTempApplet.java ) converts a fahrenheit input value as a String then converts
the input to a double before using formula to calculate centigrade from fahrenheit
c = ( 5.0 / 9.0 ) * ( f - 32 )
The output is then formatted to produce two decimal places (similar to the use of placeholder
in 'C' where %6.2d would be used).
/**
Program:
JApplet to display the output of Fahrenheir to Centigrade
conversion
Filename:
JTempApplet.java
@author:
© Gary Hill (200WXYZ)
Course:
BSc Computing
Module:
CSY3019 Graphics Programming
Tutor:
Gary Hill
@version:
1.0
Date:
20/09/02
*/
import javax.swing.*;
//enables access to the javax.swing.JApplet
class
import java.awt.*;
//enables access to the java.awt.Graphics
class
import java.text.DecimalFormat;
//enables access to DecimalFormat
/*
<applet code="JTempApplet.class" width=300 height=65>
</applet>
*/
public class JTempApplet extends JApplet
{
double centNumber;
//declare global Centigrade variable
double fahNumber;
//declare global Fahrenheit variable
public void init()
Gary Hill
// initialize applet by obtaining
December 2003
Java 12 of 12
GRAPHICS PROGRAMMING
fahrenheit value
{
String fahrenheit;
// string for fahrenheit entered by
user
fahrenheit = JOptionPane.showInputDialog("Enter your
Fahrenheit temperature" );
fahNumber = Double.parseDouble(fahrenheit); //convert from
type String to type double
centNumber = ( 5.0 / 9.0 ) * ( fahNumber - 32 );
//conversion calculation on doubles
}
public void paint( Graphics g )
//draw result on the applet
{
super.paint( g );
// call inherited version of method
paint
g.drawRect( 15, 10, 270, 20 ); // draw rectangle starting at
(15, 10) which is 270
// pixels wide and 20 pixels
high
DecimalFormat twoDecPlaces = new DecimalFormat("0.00");
//two decim
g.drawString(twoDecPlaces.format(fahNumber)+" Fahrenheit is
"
+twoDecPlaces.format(centNumber)+" Centigrade", 25,
25 );
} // end method paint
} // end class JTempApplet
In an Application, the result could have been shown using a 'Message Dialog' box as follows:
JOptionPane.showMessageDialog(null, twoDecPlaces.format(fahNumber)+"
Fahrenheit is "
+twoDecPlaces.format(centNumber)+" Centigrade",
"Results", JOptionPane.PLAIN_MESSAGE);
The 'showMessageDialog' requires four arguments:
argument 1 is the screen position (null = centre of screen),
argument 2 is the message
argument 3 is the title bar label for the dialog box
argument 4 is the type of dialog box (.PLAIN_MESSAGE = plain message without an icon
to the left of the message). Other 'types' include ERROR_MESSAGE,
INFORMATION_MESSAGE, QUESTION_MESSAGE & WARNING_MESSAGE
Gary Hill
December 2003
Java 13 of 13
GRAPHICS PROGRAMMING
Note:
The html code is embedded within the *.java source, but using the Sun One IDE will not
work. You will either need to run appletviewer JTempApplet.java within a command
window or creat a html file (JTempApplet.html) and run from within a java enabled browser:
<html>
<applet code="JTempApplet.class" width=300 height=65>
</applet>
</html>
Exercise:
Write a java program, JDayCounter.java, that uses an input dialog box
(JOptionPane.showInputDialog) and an applet for the output (g.drawString) to improve the
command-line version shown below:
Gary Hill
December 2003
Java 14 of 14
GRAPHICS PROGRAMMING
4 - GUI: JFrame
Swing and JFrames are covered in Sun's Java Tutorial - Trail: Creating a GUI with
JFC/Swing and Lesson: User Interfaces that Swing: A Quick Start Guide
Figure 11.1 The JFrame Containment Hierarchy (java.sun.com)
JFrames will be used here to introduce a number of the Swing component. The first example,
as usual, will be a JFrame 'Hello World" application (HelloJFrame.java).
/**
Program:
Filename:
@author:
Course:
Module:
Tutor:
@version:
Date:
*/
Swing JFrame to say 'Hello World'
HelloJFrame.java
© Gary Hill (200WXYZ)
BSc Computing
CSY3019 Graphics Programming
Gary Hill
1.0
14/10/03
import java.awt.*;
class
import javax.swing.*;
class
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
//enables access to the java.awt.Graphics
//enables access to the javax.swing.JFrame
public class HelloJFrame extends JFrame
{
public HelloJFrame()//could use (String title) to declare title, instead
of ..
{
super ("HelloJFrame Frame"); //..set the JFrame title
Container yourContainer = getContentPane(); // get content pane and
name it
JLabel yourJLabelText = new JLabel("Hello World");
yourContainer.add(yourJLabelText);
Gary Hill
December 2003
Java 15 of 15
GRAPHICS PROGRAMMING
pack(); //sets the frame size to preferred size of its
contents/components
setSize(250, 150); //set size of JFrame to width=250 height=150
setVisible(true); //display the JFrame
}
public static void main(String[] args)
{
HelloJFrame test = new HelloJFrame(); //HelloJFrame("Hello JFrame
Frame");
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //close frame the
Swing way
}
}// end class HelloJFrame
Exercise:
Convert the above two Applet/Option Pane programs ( JDayCounter.java, JTempApplet) to
Applications (JTempApplication.java & JDayApplication.java) using 'inputMessageDialog
& the JLabel &/or showMessageDialog.
JDayApplication.java:
.. and even ...
Gary Hill
December 2003
Java 16 of 16
GRAPHICS PROGRAMMING
Gary Hill
December 2003
Java 17 of 17
GRAPHICS PROGRAMMING
5 - GUI: JButton
The first Swing example JFrame 'Hello World" application (HelloJFrame.java) introduced a
number of the Swing components. The next application (HelloJButton.java) will introduce:
Button (JButton)
Button Handler (ButtonHandler)
Action Listener (ActionListener)
Background Colour (setBackground)
Text Labels (JLabel)
Text Field (JTextField)
Tool Tip Text (setToolTipText)
Figure 12.1 The JButton & JLabel Component Hierarchy (java.sun.com)
The Button Class
(see: Introduction to Programming Using Java, V3.0, Summer 2000, David J.
Eck)
An object of class Button is a push button. Buttons use components, events, and listeners
described below:
Constructors
The Button class has a constructor that takes a string as a parameter. This string becomes the
label displayed on the button. For example: stopGoButton = new Button("Go")
Events
When the user clicks on a button, the button generates an event of type ActionEvent. This
event is sent to any listener that has been registered with the button.
Listeners
An object that wants to handle events generated by buttons must implement the
ActionListener interface. This interface defines just one method, "pubic void
actionPerformed(ActionEvent event)", which is called to notify the object of an action event.
Registration of Listeners
Gary Hill
December 2003
Java 18 of 18
GRAPHICS PROGRAMMING
In order to actually receive notification of an event from a button, an ActionListener must
be registered with the button. This is done with the button's addActionListener() method.
For example: stopGoButton.addActionListener(buttonHandler)
Event methods
When actionPerformed(event) is called by the button, the parameter, event, contains
information about the event. This information can be retrieved by calling methods in the
ActionEvent class. In particular, event.getActionCommand() returns a String giving the
command associated with the button. By default, this command is the label that is displayed
on the button.
Component methods
There are several useful methods in the Button class. For example,
stopGoButton.setLabel("Stop") changes the label displayed on the button to "Stop". And
stopGoButton.setActionCommand("sgb") changes the action command associated to this
button for action events.
Of course, Buttons alsohave all the general Component methods, such as setEnabled() and
setFont(). The setEnabled() and setLabel() methods of a button are particularly usefulfor
giving the user information about what is going on in the program. A disabled button is better
than a button that gives an obnoxious error message such as "Sorry, you can't click on me
now!"
/**
Program:
Filename:
@author:
Course:
Module:
Tutor:
@version:
Date:
*/
Swing JFrame with JButtons
HelloJButton.java
© Gary Hill (200WXYZ)
BSc Computing
CSY3019 Graphics Programming
Gary Hill
1.0
15/01/02
import java.awt.*;
class
import javax.swing.*;
class
import java.awt.event.*;
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
//enables access to the java.awt.Graphics
//enables access to the javax.swing.JFrame
//for button clicks and mouse movement
public class HelloJButton extends JFrame
{
JTextField helloTextField;
//declare JTextField
JButton helloButton;
//declare JButton
JLabel yourJLabelText;
//declare JLabel
public HelloJButton()//could use (String title) then super(title) and
declare title.
{
super ("HelloJButton Frame"); //set the JFrame title
Container yourContainer = getContentPane(); // get content pane and
Gary Hill
December 2003
Java 19 of 19
GRAPHICS PROGRAMMING
name it
yourContainer.setLayout(new FlowLayout(FlowLayout.CENTER)); //
center components
yourContainer.setBackground(Color.yellow); //set the background
colour to yellow
helloButton = new JButton("Press");
helloButton.setToolTipText("Press me");
/ tip.
yourContainer.add(helloButton);
// create button
// gives a mouse over help
// create an instance of inner class ButtonHandler to use for button
event handling
ButtonHandler bHandler = new ButtonHandler();
helloButton.addActionListener( bHandler );
yourJLabelText = new JLabel("Press the above button for response:");
yourContainer.add(yourJLabelText);
//add label to container
helloTextField = new JTextField("", 12 );
display button response
helloTextField.setEditable( false );
editing
yourContainer.add( helloTextField );
container
//create text field to
//prevent text field
//add text field to
pack(); //helps determine the window's size from the added components
preferred sizes
setSize(200, 150); //set size of JFrame to width=200 height=150
setVisible(true); //display the JFrame
}
private class ButtonHandler implements ActionListener // inner class
for button event handling
{ // handle button event
int noPress = 1;
//integer variable to keep account of
button presses
public void actionPerformed( ActionEvent event )
{
if (event.getSource() == helloButton)
//(event.getActionCommand()=="Press")could also be used
{
helloTextField.setText(" Press " + noPress); //set the text to
this..
noPress++;
//increment
}
}
} // end private inner class ButtonHandler
public static void main(String[] args)
{
HelloJButton testHelloJButton = new HelloJButton();
//HelloJFrame("Hello JFrame Frame");
testHelloJButton.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//close frame the Swing
}
}// end class HelloJButton
Gary Hill
December 2003
Java 20 of 20
GRAPHICS PROGRAMMING
Note: Instead of using a private abstract inner class for handling the button events, as above,
the actionPerformed() method can be included within the class and the class modified so
that it implements ActionListener.
See HelloJButton2.java.
Note: Layout Managers will be covered in a later section, but one way of maintaning the
layout and look of your application is to restrict a user resizing your JFrame. To do this a
method inherited from class java.awt.Frame, setResizable(boolean). Therefore above the
main method could be altered to include a third line:
testHelloJButton.setResizable(false);//prevents resizing of the JFrame
Example
Write an application similar to above (HelloJButton.java) that includes three button (Red,
Green and Blue) which when pressed indicate which button has been pressed by showing
Red, Green or Blue in the text field and also changing the background to the appropriate
colour (RGBJButton.java).
Gary Hill
December 2003
Java 21 of 21
GRAPHICS PROGRAMMING
6 - GUI: Look and Feel
Java allow the programmer to set the look and feel of any graphical user interface (GUI)
bythe use of the UIManager's method setLookAndFeel as follows:
Cross Platform - the default Java GUI look and feel
(UIManager.getCrossPlatformLookAndFeelClassName())
System - the look and feel set for the current operating system / desktop
(UIManager.getSystemLookAndFeelClassName())
Metal - the Java GUI look and feel ("javax.swing.plaf.metal.MetalLookAndFeel")
Windows - Microsoft look and feel
("com.sun.java.swing.plaf.windows.WindowsLookAndFeel")
Motif - Sun and Unix look and feel ("com.sun.java.swing.plaf.motif.MotifLookAndFeel")
Macintosh - Apple look and feel ("javax.swing.plaf.mac.MacLookAndFeel")
(See: Sun's Java Tutorial: How to Set the Look and Feel)
For each of the looks and feels the programmer would need to incorporate the following code
(unless you except the default):
Cross Platform
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName())
;
}
catch (Exception e)
{
System.err.println("Couldn't use the system "+ "look and feel:
" + e);
}
HelloJButton testHelloJButton = new HelloJButton();
//HelloJFrame("Hello JFrame Frame");
testHelloJButton.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//close frame the Swing
}
}// end class HelloJButton
System
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
System.err.println("Couldn't use the system "+"look and feel:
Gary Hill
December 2003
Java 22 of 22
GRAPHICS PROGRAMMING
"+e);
}
Metal
try
{
UIManager.setLookAndFeel(("javax.swing.plaf.metal.MetalLookAndFeel"));
}
catch (Exception e)
{
System.err.println("Couldn't use the system "+"look and feel:
" + e);
}
Windows
try
{
UIManager.setLookAndFeel(("com.sun.java.swing.plaf.windows.WindowsLookAndF
eel"));
}
catch (Exception e)
{
System.err.println("Couldn't use the system "+"look and feel:
" + e);
}
Motif
try
{
UIManager.setLookAndFeel(
("com.sun.java.swing.plaf.motif.MotifLookAndFeel"));
}
catch (Exception e)
{
System.err.println("Couldn't use the system "
+ "look and feel: " + e);
}
Macintosh
try
{
Gary Hill
December 2003
Java 23 of 23
GRAPHICS PROGRAMMING
UIManager.setLookAndFeel(
("javax.swing.plaf.mac.MacLookAndFeel"));
}
catch (Exception e)
{
System.err.println("Couldn't use the system "
+ "look and feel: " + e);
}
Example
Adapt your Red, Green and Blue application to use the above look and feel types
(RGBJButton.java) to see the difference, if any.
Gary Hill
December 2003
Java 24 of 24
GRAPHICS PROGRAMMING
7 - GUI: JList
/**
Program:
Filename:
@author:
Course:
Module:
Tutor:
@version:
Date:
*/
Swing JList Application
RGBJList.java
© Gary Hill (200WXYZ)
BSC Computing
CSY3019 Graphics Programming
Gary Hill
1.0
22/09/02
import java.awt.*;
class
import javax.swing.*;
class
import javax.swing.event.*;
javax.swing.event.JList class
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
//enables access to the java.awt.Graphics
//enables access to the javax.swing.JFrame
//enables access to the
public class RGBJList extends JFrame
{
JTextField helloTextField;
//declare JTextField
JList colorList;
//declare JList for colour selection
Container yourContainer;
String colorNames[] = { "Black", "Blue", "Cyan","Dark Gray", "Gray",
"Green",
"Light Gray", "Magenta", "Orange", "Pink", "Red", "White",
"Yellow" };
Color colors[] = { Color.black, Color.blue, Color.cyan, Color.darkGray,
Color.gray, Color.green, Color.lightGray, Color.magenta,
Color.orange,
Color.pink, Color.red, Color.white, Color.yellow };
public RGBJList()
//could use (String title) then
super(title) and declare title.
{
super ("RGBJList Application");
//set the JFrame title
yourContainer = getContentPane();
//get content pane and
name it
yourContainer.setLayout(new FlowLayout(FlowLayout.CENTER)); // center
components
yourContainer.setBackground(Color.yellow); //set the background
colour to yellow
colorList = new JList( colorNames );
//create a list with items
in colorNames array
colorList.setVisibleRowCount( 6 );
colorList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION ); //do
not allow multiple selections
yourContainer.add( new JScrollPane( colorList ) );//add a JScrollPane
containing JList to content pane
colorList.addListSelectionListener(
// set up event handler
new ListSelectionListener()
{
// anonymous inner class for list selection
events
Gary Hill
December 2003
Java 25 of 25
GRAPHICS PROGRAMMING
public void valueChanged( ListSelectionEvent event )
handle list selection events
{
yourContainer.setBackground(colors[
colorList.getSelectedIndex()]);
//
helloTextField.setText(colorNames[colorList.getSelectedIndex()]);
}
}
// end anonymous inner class
);
// end call to addListSelectionListener
JLabel yourJLabelText = new JLabel("Select a background 'colour' from
the list above:");
yourContainer.add(yourJLabelText);
//add label to container
helloTextField = new JTextField("", 12 );
display button response
helloTextField.setEditable( false );
editing
yourContainer.add( helloTextField );
container
pack();
setSize(350, 250);
height=250
setVisible(true);
}
//create text field to
//prevent text field
//add text field to
//set size of JFrame to width=350
//display the JFrame
public static void main(String[] args)
{
RGBJList testRGBJList = new RGBJList();
//RGBJList("RGBJList
Application");
testRGBJList.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //close
frame the Swing way
//JDK1.3 version of addWindowListener
}
}// end class RGBJList
Note: Instead of using an annonymous abstract inner class for handling the list selection
events, as above, the valueChanged() method can be included within the class and the class
modified so that it implements ListSelectionListener . See RGBList2.java.
Example
Stage 1: Write an application similar to above that includes includes a list of at least ten
currencies which when selected indicate the currency choice in the text field
Gary Hill
December 2003
Java 26 of 26
GRAPHICS PROGRAMMING
(CurrencyJList.java).
Stage 2: Adapt the Currency application to show another text field that includes the exchange
rate for the selected currency.
Gary Hill
December 2003
Java 27 of 27
GRAPHICS PROGRAMMING
8 - GUI: Layout Managers
In Java there are a numberof layout manager that enable you to place components onto a
container (JFrame etc.). These include:
•
•
•
•
•
•
FlowLayout
GridLayout
BorderLayout
CardLayout
GridBagLayout
BoxLayout
(See: Sun's Java Tutorial Lesson: Laying Out Components Within a Container)
For simple applications only one layout manager may be required, but for a complicated GUI
it is necessary to combine any number of layout managers to create the desired GUI. This is
achieved by adding a number of JPanels to one the main Container (or a JPanel before
adding to the main Container). The JPanels can use any of the layout managers to enable
the components to be added to it. The JPanels can then be added to the main Container.
The example below illustrates the use of 5 JPanels added to the Container. The JPanels use
the FlowLayout layout manager and the JPanels are added to the Container using
BorderLayout.
Gary Hill
December 2003
Java 28 of 28
GRAPHICS PROGRAMMING
Gary Hill
December 2003
Java 29 of 29
GRAPHICS PROGRAMMING
Example
Use the resources available (see: Indicative Reading and Other Resources) to experiment
with each type of Layout Manager. Use your Currency Application (CurrencyJList.java)
from above. Alternatively, a good exercise is to attempt to emulate the Calualtor GUI
available within all Windows Operating Systems as the XP version below:
Gary Hill
December 2003
Java 30 of 30
GRAPHICS PROGRAMMING
9 - GUI: JMenu
To create the familiar 'Windows' GUI menu bar in an application (also applets) the stages are
as follows:
Create an object of the JMenuBar class.
Call the window's setJMenuBar( ) method to give the menu bar to the window.
Create objects of the JMenu class for each menu you want in the menu bar.
Call the JMenuBar object's add( ) method to add each menu object to the menu bar.
Create objects of the JMenuItem (or JCheckboxMenuItem) classe/s for each item you want
to appear in the menus.
Call the menus' add( ) methods in order to add each item to its appropriate menu.
Remember to addActionListener to each JMenuItem.
Note: Variations on JMenuItem include: JCheckBoxMenuItem, JRadioButtonMenuItem.
There is also another type of JMenu is the JPopupMenu.
Figure 16.1 The Menu Component Hierarchy (java.sun.com)
Each of the above steps is covered in the application (GraphicsJFrame.java) below:
Gary Hill
December 2003
Java 31 of 31
GRAPHICS PROGRAMMING
/**
Program:
Filename:
@author:
Course:
Module:
Tutor:
@version:
Notes
Date:
*/
Java Graphics Screen Application
GraphicsJFrame.java
© Gary Hill (200WXYZ)
BSC Computing
Graphics Programming
Gary Hill
1.1
1.1 Added centreWindow method
28/10/03
import java.awt.*;
BorderLayout
import javax.swing.*;
JPanel class
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
//enables access to the
Container &
//enables access to the javax.swing.JFrame &
public class GraphicsJFrame extends JFrame implements
ActionListener//ActionListener for menu only
{
Container yourContainer;
//declare container
DrawingArea drawingArea;
//declare JPanel for drawing
JScrollPane scrollsVH;
//declare vertical & horizontal scrolling
JMenuBar topMenuBar;
//declare Menu Bar
JMenu fileMenu, editMenu, searchMenu, helpMenu; //declare sub-Menus
JMenuItem exitItem, fontItem, foreColor, backColor, helpItem, aboutItem;
String aboutBoxString = (" Application written by\n © Gary Hill
BSc(Hons) MSc MPhil PGCE\n"
+ " Principal Lecturer - Computer Systems,\n School of
Technology & Design,\n"
+ " University College Northampton\n St Georges Avenue,\n "
+ " Northampton, NN2 6JD,\n United Kingdom\n E-Mail:
[email protected]\n"
+ " Tel.(Work) +44 (0)1604 735500 Ext. 3077\n
http://www.eng.nene.ac.uk/~gary/\n"
+ " Fax.(Work) +44 (0)1604) 792650/717813.") ;
JLabel statusBar = new JLabel(" Example - DrawingArea JPanel");
Gary Hill
December 2003
Java 32 of 32
GRAPHICS PROGRAMMING
public GraphicsJFrame()
//could use (String title) then
super(title) and declare title.
{
super ("Java 2D/3D Graphics Application");
//set the JFrame title
yourContainer = getContentPane();
// get content pane and
name it
yourContainer.setLayout(new BorderLayout());
// use border layout
drawingArea = new DrawingArea();
scrollsVH = new JScrollPane(drawingArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollsVH.setBackground(Color.white); //set background colour for the
drawing area to white
yourContainer.add(scrollsVH, BorderLayout.CENTER);//add V & H
scrolling to container
yourContainer.add(statusBar, BorderLayout.SOUTH);
menuSetup();
//standard menu set up method - requires
actionListener
pack();
setSize(500, 350);
//set default size of JFrame to width=500
height=350
centreWindow();
setVisible(true);
//display the JFrame
}
public void menuSetup()
{
topMenuBar = new JMenuBar();
//create a menu bar
setJMenuBar(topMenuBar);
//set the menu bar to the JFrame
fileMenu = new JMenu("File");
// File menu, with open, save,
exitItem = new JMenuItem("Exit");
fileMenu.add(exitItem);
exitItem.addActionListener(this);
topMenuBar.add(fileMenu);
//EXIT item
//add the items to the menu
//add the listener to the item
//add the menu to the menu bar
editMenu = new JMenu("Edit");
// edit menu, could have copy,
exit
paste
foreColor = new JMenuItem("Foreground Colour"); //Foreground Colour
item
editMenu.add(foreColor);
//add the items to the menu
foreColor.addActionListener(this); //add the listener to the item
backColor = new JMenuItem("Background Colour"); //Background Colour
item
editMenu.add(backColor);
//add the items to the menu
backColor.addActionListener(this); //add the listener to the item
topMenuBar.add(editMenu );
searchMenu = new JMenu("Search");
topMenuBar.add(searchMenu);
helpMenu = new JMenu("Help");
// help menu, with
about application
helpItem = new JMenuItem("Help Topics");
helpMenu.add(helpItem);
helpItem.addActionListener(this);
aboutItem = new JMenuItem("About...");
helpMenu.add(aboutItem);
Gary Hill
December 2003
help topics,
Java 33 of 33
GRAPHICS PROGRAMMING
aboutItem.addActionListener(this);
topMenuBar.add(helpMenu);
}
public void centreWindow()
{
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = getSize();
if (frameSize.height > screenSize.height)
{
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width)
{
frameSize.width = screenSize.width;
}
setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == exitItem)
{
System.exit(0);
}
if (e.getSource() == foreColor)
{ //Handle the "Foreground Color" menu item
Color color = JColorChooser.showDialog(this,"Foreground Color",
getForeground());
System.out.println("Foreground Color is Red = "+
color.getRed() +" G= "+color.getGreen()+" B=
"+color.getBlue());
if (color != null)
{
drawingArea.setForeground(color);
setForeground(color);
}
}
if (e.getSource() == backColor)
{ //Handle the "Foreground Color" menu item
Color color = JColorChooser.showDialog(this,"Background Color",
getBackground());
if (color != null)
{
scrollsVH.setBackground(color);
}
drawingArea.setBackground(Color.white);
System.out.println("Background Color is Red = "
+color.getRed() +" G= "+color.getGreen()+" B=
"+color.getBlue());
}
if (e.getSource() == helpItem)
JOptionPane.showMessageDialog(null, "Help Topics chosen.");
if (e.getSource() == aboutItem)
JOptionPane.showMessageDialog(null, aboutBoxString, "About the
author",
JOptionPane.INFORMATION_MESSAGE);
this.repaint();
//repaints menu after item is selected
}
Gary Hill
December 2003
Java 34 of 34
GRAPHICS PROGRAMMING
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
System.err.println("Couldn't use the system look and feel: " +
e);
}
GraphicsJFrame test = new GraphicsJFrame(); //GraphicsJFrame("Java
2D/3D Graphics Application");
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //close frame
Swing way
}
}// end class GraphicsJFrame
/**
Program:
Filename:
@author:
Course:
Module:
Tutor:
@version:
Date:
*/
Java Graphics Screen Application
<BR>
DrawingArea.java
<BR>
© Gary Hill (200WXYZ)
<BR>
BSC Computing
<BR>
Graphics Programming
<BR>
Gary Hill
<BR>
1.1
<BR>
28/10/03
<BR>
import java.awt.*;
BorderLayout
import javax.swing.*;
JPanel class
//enables access to the
Container &
//enables access to the javax.swing.JFrame &
class DrawingArea extends JPanel
{
public void paint(Graphics g)
{
g.drawString("A drawRect rectangle", 175, 100);
position
g.drawString("This 'DrawingArea' will be used for
applications", 100, 200);
g.setColor(Color.blue);
//set colour to
g.drawRect(25, 25, 425, 150);
//Rectangle x ,
height
}
}// end class DrawingArea
Gary Hill
December 2003
//string & x, y
our graphics
blue
y, width &
Java 35 of 35
GRAPHICS PROGRAMMING
Message Dialog
The text editor application (GraphicsJFrame.java) above makes use of a 'Message Dialog'
box to provide an About box as follows:
if (e.getSource() == aboutItem)
JOptionPane.showMessageDialog(null, " Application........");
The showMessageDialog method requires four arguments:
argument 1 is the screen position (null = centre of screen),
argument 2 is the message
argument 3 is the title bar label for the dialog box
argument 4 is the type of dialog box (.PLAIN_MESSAGE = plain message without an icon
to the left of the message). Other 'types' include ERROR_MESSAGE,
INFORMATION_MESSAGE, QUESTION_MESSAGE & WARNING_MESSAGE.
Gary Hill
December 2003
Java 36 of 36
GRAPHICS PROGRAMMING
Application Icon
You may have noticed that the GraphicsJFrame application above has an application icon in
the top left hand corner of the JFrame, instead of the default steaming cup of java coffee!
Add your own application icon as follows using the setIconImage method inherited by
JFrame from the java.awt.Frame class:
setIconImage(Toolkit.getDefaultToolkit().createImage
(GraphicsJFrame.class.getResource("rat_icon.gif")));//set application icon
or
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image icon = toolkit.getImage(getClass().getResource("rat_icon.gif"));
setIconImage(icon); //see here
See the API Documentation for further details.
Applications
To incorporate text and styled text, even HTML, into an application see JTextPane and
JEditorPane.
Gary Hill
December 2003
Java 37 of 37