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
Introduction to GUI Programming
(Part II)
188230 Advanced Computer Programming
Asst. Prof. Dr. Kanda Runapongsa Saikaew
(krunapon@kku.ac.th)
Department of Computer Engineering
Khon Kaen University
1
Agenda
JComponent Methods
Graphics and Painting
Applets and HTML
2
JComponent Class
The Swing components started with “J” are defined by subclasses of the class JComponent, which is itself a subclass of Component
Many useful methods are defined in the Component and JComponent classes and so can be used with any Swing component 3
getWidth() and getHeight()
comp.getWidth() and comp.getHeight() are functions that give the current size of the component, in pixels
One warning: When a component is first created, its size is zero
The size will be set later, probably by a layout manager
A common mistake is to check the size of a component before that size has been set, such as in a constructor
4
setEnable(true) and isEnable()
comp.setEnabled(true) and comp.setEnabled(false) can be used to enable and disable the component
When a component is disabled, its appearance might change, and the user cannot do anything with it
There is a booleanvalued function, comp.isEnabled() that you can call to discover whether the component is enabled
5
setVisible(true), setFont(font), set Color
comp.setVisible(true) and comp.setVisible(false) can be called to hide or show the component
comp.setFont(font) sets the font that is used for text displayed on the component
comp.setBackground(color) and comp.setForeground(color) set the background andforeground colors for the component
6
setOpaque(true)
comp.setOpaque(true) tells the component that the area occupied by the component should be filled with the component’s background color before the content of the component is painted
By default, only JLabels are nonopaque. A nonopaque, or “transparent”, component ignores its background color and simply paints its content over the content of its container
This usually means that it inherits the 7
background color from its container
setToolTipText(string)
comp.setToolTipText(string) sets the specified string as a “tool tip” for the component.
The tool tip is displayed if the mouse cursor is in the component and the mouse is not moved for a few seconds
The tool tip should give some information about the meaning of the component or how to use it
8
setPreferredSize(size)
comp.setPreferredSize(size) sets the size at which the component should be displayed,
if possible
The parameter is of type java.awt.Dimension, where an object of type Dimension has two public integervalued instance variables, width and height
A call to this method usually looks something like “setPreferredSize( new 9
Dimension(100,50) )” setPreferredSize(size)
The preferred size is used as a hint by layout managers, but will not be respected in all
cases
Standard components generally compute a correct preferred size automatically, but it can be useful to set it in some cases
For example, if you use a JPanel as a drawing
surface, it might be a good idea to set a preferred size for it
10
JComponentMethodsDemo
JLabel fname = new JLabel("Firstname:");
fname.setPreferredSize(new Dimension(50,50));
JLabel lname = new JLabel("Lastname:");
JTextField fnameInput = new JTextField(15);
fnameInput.setToolTipText("input your firstname");
11
Drawing on a Component
Sometimes, however, you do want to draw on a component
A JPanel, like any JComponent, draws its content in the method
You have to define your own component class and provide a method in that class for drawing the component
public void paintComponent(Graphics g)
To create a drawing surface, you should define a subclass of JPanel and provide a custom
12
paintComponent() method
Method paintComponent()
Note that the paintComponent() method has a parameter of type Graphics
The Graphics object will be provided by the system when it calls your method
You need this object to do the actual drawing.
To do any drawing at all in Java, you need a graphics context
A graphics context is an object belonging to the class java.awt.Graphics
13
Graphics Objects
Instance methods are provided in this class for drawing shapes, text, and images
Any given Graphics object can draw to only one location
The location will always be a GUI component
belonging to some subclass of JPanel
The Graphics class is an abstract class, which means that it is impossible to create a graphics context directly, with a constructor
14
Class Graphics
The Graphics class is an abstract class, which means that it is impossible to create a graphics context directly, with a constructor
When the paintComponent() method of a component is called by the system, the parameter to that method is a graphics context for drawing on the component 15
Drawing in Subclass of JPanel
When defining a subclass of JPanel for use as a drawing surface
You will almost always want to fill the panel with the background color before drawing other content onto the panel
This is traditionally done with a call to super.paintComponent(g)
public void paintComponent(g) {
super.paintComponent(g);
. . . // Draw the content of the component.
} 16
Redrawing a Component (1/2)
Most components do, in fact, do all drawing operations in their paintComponent() methods
What happens if, in the middle of some other method, you realize that the content of the
component needs to be changed?
You should not call paintComponent() directly to make the change; this method is meant to be called only by the system
17
Redrawing a Component (2/2)
Instead, you have to inform the system that the component needs to be redrawn, and let the system do its job by calling paintComponent()
You do this by calling the component’s repaint() method
The method public void repaint(); is defined in the Component class, and so can be used with any component
You should call repaint() to inform the system 18
that the component needs to be redrawn
When paintComponent() is called
The component first appears on the screen
The component is resized
The component is covered up by another window and then uncovered
The method repaint() is called
19
Coordinates
The screen of a computer is a grid of little squares called pixels
The color of each pixel can be set individually, and drawing on the screen just means setting the colors of individual pixels
20
Graphics and Coordinates
A graphics context draws in a rectangle made up of pixels
A position in the rectangle is specified by a pair of integer coordinates, (x,y)
The upper left corner has coordinates (0,0)
The x coordinate increases from left to right, and the y coordinate increases from top to bottom
21
CoordinateDemoPanel 22
serialVersionUID
Class JPanel implements interface Serializable
which has attribute serialVersionUID
Thus class that its subclass of JPanel is also recommended to set the value of that attribute
a serialVersionUID is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization
23
How to Generate serialVersionID
Using tool called “serialver” which comes with JDK
Syntax
serialver <classname>
Example
24
CoordinateAppDemo
25
setDefaultCloseOperation
window.setDefaultCloseOperation( JFrame.EXI
TON CLOSE ); says that
When the user closes the window by clicking the close box in the title bar of the window, the program should be terminated
This is necessary because no other way is provided to end the program
Without this line, the default close operation of the window would simply hide the window when the user clicks the close box, leaving the program 26
running
A Font
A font represents a particular size and style of text
The same character will appear different
in different fonts
In Java, a font is characterized by a font name, a style, and a size
The available font names are system dependent, but you can always use the following four strings as font names: “Serif”, “SansSerif”, “Monospaced”, and “Dialog”
27
Font Style
The style of a font is specified using named constants that are defined in the Font class.
You can specify the style as one of the four values:
Font.PLAIN
Font.ITALIC
Font.BOLD, or
Font.BOLD + Font.ITALIC
28
Font Size
The size of a font is an integer
Size typically ranges from about 10 to 36, although larger sizes can also be used
The size of a font is usually about equal to the height of the largest characters in the font, in pixels, but this is not an exact rule
The size of the default font is 12
29
Class java.awt.Font
Java uses java.awt.Font for representing fonts
You can construct a new font by specifying its font name, style, and size in a constructor:
Font plainFont = new Font("Serif", Font.PLAIN, 12);
Font bigBoldFont = new Font("SansSerif", Font.BOLD, 24);
Every graphics context has a current font, which is used for drawing text
You can change the current font with the setFont() 30
method
Font Setting Example
If g is a graphics context and bigBoldFont is a font, then the command
g.setFont(bigBoldFont)
will set the current font of g to bigBoldFont
The new font will be used for any text that is drawn after the setFont() command is given
You can find out the current font of g by calling the method g.getFont(), which returns an object of type Font
31
Color
You will probably want to use some color when you draw
Java is designed to work with the RGB color system An RGB color is specified by three numbers that give the level of red, green, and blue, respectively, in the color
A color in Java is an object of the class java.awt.Color
32
Constructing a RGB Color
You can construct a new color by specifying its red, blue, and green components
Syntax:
Color myColor = new Color(r,g,b);
While r, g, and b are integers in the range 0 to 255
33
Referring to Color Names
Color class defines several named constants representing common colors:
Color.WHITE, Color.BLACK, Color.RED
Color.GREEN, Color.BLUE, Color.CYAN
Color.MAGENTA, Color.YELLOW, Color.PINK
Color.ORANGE, Color.LIGHT_GRAY
Color.GRAY,Color.DARK GRAY
34
Getting and Setting Color
One of the properties of a Graphics object is the current drawing color, which is used for all drawing of shapes and text
If g is a graphics context, you can change the current drawing color for g using the method g.setColor(c), where c is a Color
g.setColor(Color.GREEN)
To know what the current drawing color is, you can call the function g.getColor(), which returns 35
an object of type Color
A HSB Color System
In the HSB system, a color is specified by
three numbers called the hue, the saturation, and the brightness
The hue is the basic color, ranging from red through orange through all the other colors of the rainbow
The brightness is pretty much what it sounds like
A fully saturated color is a pure color tone
In Java, the hue, saturation and brightness are always specified by values of type float in the range from 0.0F to 1.0F
Example: Color randomColor = 36
Color.getHSBColor( (float)Math.random(), 1.0F, 1.0F );
Foreground & Background colors
Every component has an associated foreground color and background color The component is filled with the background color before anything else is drawn
Although some components are “transparent,” meaning that the background color is ignored
When a new graphics context is created for a component, the current drawing color is set to the foreground color
37
Setting Foreground & Background Colors
The foreground color and background color are properties of the component, not of a graphics context
The foreground and background colors can be set by instance methods
setForeground(c)
setBackground(c)
This can be useful if you want them to use colors that are different from the defaults.
38
Graphics and Shapes
The Graphics class includes a large number of instance methods for drawing various shapes, such as lines, rectangles, and ovals
The shapes are specified using the (x,y) coordinate system
They are drawn in the current drawing color of the graphics context which you can set by calling method setColor(color) 39
Drawing String and Line
drawString(String str, int x, int y)
Draws the text given by the string str
The string is drawn using the current color and font of the graphics context
x specifies the position of the left end of the string
y is the ycoordinate of the baseline of the string
drawLine(int x1, int y1, int x2, int y2)
Draws a line from the point (x1,y1) to the point (x2,y2)
40
Drawing Rectangle & Oval
drawRect(int x, int y, int width, int height)
Draws the outline of a rectangle
The upper left corner is at (x,y), and the width and height of the rectangle are as specified.
drawOval(int x, int y, int width, int height)
Draws the outline of an oval
The oval is one that just fits inside the rectangle specified by x, y, width, and height.
41
Drawing Round Rectangle
drawRoundRect(int x, int y, int width, int height, int xdiam, int ydiam)
Draws the outline of a rectangle with rounded corners
The basic rectangle is specified by x, y, width, and height, but the corners are rounded
The degree of rounding is given by xdiam and ydiam
The corners are arcs of an ellipse with horizontal diameter xdiam and vertical diameter ydiam which 42
have typical values as 16
Drawing 3D Rectangle
draw3DRect(int x, int y, int width, int height, boolean raised)
Draws the outline of a rectangle that is supposed to have a threedimensional effect, as if it is raised from the screen or pushed into the screen
The basic rectangle is specified by x, y, width, and height
The raised parameter tells whether the rectangle seems to be raised from the screen or pushed into it
The 3D effect is achieved by using brighter and darker versions of the drawing color for different edges of the 43
rectangle
Drawing Arc
drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Draws part of the oval that just fits inside the rectangle specified by x, y, width, and height
The part drawn is an arc that extends arcAngle degrees from a starting angle at startAngle degrees
Angles are measured with 0 degrees at the 3 o’clock position (the positive direction of the 44
horizontal axis)
Filling Shapes
fillRect(int x, int y, int width, int height)
fillOval(int x, int y, int width, int height)
Draws a filledin rounded rectangle.
fill3DRect(int x, int y, int width, int height, boolean raised)
Draws a filledin oval.
fillRoundRect(int x, int y, int width, int height, int xdiam, int ydiam)
Draws a filledin rectangle
Draws a filledin threedimensional rectangle.
fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Draw a filledin arc. 45
Graphics2D
All drawing in Java is done through an object of type Graphics
The Graphics class provides basic commands for such things as drawing shapes and text and for selecting a drawing color
These commands are adequate in many cases, but they fall far short of what’s needed in a serious computer graphics program
Java has another class, Graphics2D, that 46
provides a larger set of drawing operations
Drawings Using Graphics2D
Graphics2D is a subclass of Graphics, so all the methods from the Graphics class are also available in a Graphics2D
Drawing in Graphics2D is based on shapes, which are objects that implement an interface
named Shape
Shape classes include Line2D, Rectangle2D, Ellipse2D, Arc2D, and CubicCurve2D, among others
All these classes are defined in the package java.awt.geom
47
Shortcomings of the AWT
The capabilities of the Graphics object of the AWT are rather limited
Shortcomings of the AWT include
Limited available fonts
Lines drawn with a singlepixel width
Shapes painted only in solid colors
The inability to properly scale drawings prior to printing
48
Java 2D
Java 2D is probably the second most significant addition to the Java 2 Platform surpassed only by the Swing GUI components
The Java 2D API provides a robust package of drawing and imaging tools to develop elegant, professional, highquality graphics
49
Java 2D Capabilities
Local fonts: all local fonts on the platform are available for drawing text
Explicit control of the drawing pen: thickness of lines, dashing patterns, and segment connection styles are available
Transformations of the coordinate system—
translations, scaling, rotations, and shearing—
are available
50
Java 2D Drawing Process: Step 1
Cast Graphics object to Graphics2D
public void paintComponent(Graphics g) {
super.paintComponent(g); // Typical Swing Graphics2D g2d = (Graphics2D)g;
g2d.doSomeStuff(...);
...}
All methods that return Graphics in Java return Graphics2D in Java 2 and later
paint, paintComponent
getGraphics
51
Java 2D Drawing Process: Step 2
Set pen parameters
g2d.setPaint(fillColorOrPattern);
g2d.setStroke(penThicknessOrPattern);
g2d.setComposite(someAlphaComposite);
g2d.setFont(someFont);
g2d.translate(...);
g2d.rotate(...);
g2d.scale(...);
g2d.shear(...);
g2d.setTransform(someAffineTransform);
52
Java 2D Drawing Process: Step 3
Create a Shape object
Rectangle2D.Double rect = ...;
Ellipse2D.Double ellipse = ...;
Polygon poly = ...;
GeneralPath path = ...;
// Satisfies Shape interface
SomeShapeYouDefined shape = ...;
Most shapes are in the java.awt.geom package
There is a corresponding Shape class for most of the drawXxx methods of Graphics (see next slide)
53
Builtin Shape Classes
Arc2D.Double, Arc2D.Float
Area (a shape built by union, intersection, subtraction and xor of other shapes)
CubicCurve2D.Double, CubicCurve2D.Float
Ellipse2D.Double, Ellipse2D.Float
GeneralPath (a series of connected shapes), Polygon
Line2D.Double, Line2D.Float
QuadCurve2D.Double, QuadCurve2D.Float (a spline curve)
Rectangle2D.Double, Rectangle2D.Float, Rectangle
54
RoundRectangle2D.Double, RoundRectangle2D.Float
Java 2D Drawing Process: Step 4
Draw an outlined or filled version of the Shape
g2d.draw(someShape);
g2d.fill(someShape);
The legacy methods are still supported
drawString still commonly used
drawLine, drawRect, fillRect still somewhat used
55
Drawing Shapes: Example Code
56
setPaint and getPaint Methods
Use setPaint and getPaint to change and retrieve the Paint settings.
When you fill a Shape, the current Paint attribute of the Graphics2D object is used.
Possible arguments to setPaint are:
A Color (solid colorColor implements Paint interface)
A GradientPaint (graduallychanging color combination)
A TexturePaint (tiled image)
A new version of Paint that you write yourself.
57
Paint Classes: Details
Color
Has the same constants (Color.RED, Color.YELLOW) as the AWT version, plus some extra constructors
GradientPaint
Constructors take two points, two colors, and optionally a boolean flag that indicates that the color pattern should cycle
Colors fade from one color to the other
58
Paint Classes: Details
TexturePaint
Constructor takes a BufferedImage and a Rectangle2D, maps the image to the rectangle, then tiles the rectangle
Creating a BufferedImage from a GIF or JPEG
First load an Image normally, get its size, create a BufferedImage that size with BufferedImage.TYPE_INT_ARGB as image type
Get the BufferedImage's Graphics object via createGraphics
Draw the Image into the BufferedImage using drawImage
59
Gradient Fills: Example Code
60
Working with Images
There are a number of common tasks when working with images
Loading an external GIF, PNG JPEG image format file into Java 2D™'s internal image representation.
Directly creating a Java 2D image and rendering to it
Drawing the contents of a Java 2D image on to a drawing surface.
Saving the contents of a Java 2D image to an external GIF, PNG, or JPEG image file.
61
Two Main Classes for Images
The java.awt.Image class
Superclass that represents graphical images as rectangular arrays of pixels.
The java.awt.image.BufferedImage class
Extends the Image class to allow the application to operate directly with image data (for example, retrieving or setting up the pixel color).
Applications can directly construct instances of this class.
A cornerstone of the Java 2D immediatemode imaging API
62
Reading/Loading an Image
Java 2D™ supports loading these external image formats into its BufferedImage format using its Image I/O API which is in the javax.imageio package
Image I/O has builtin support for GIF, PNG, JPEG, BMP, and WBMP
Image I/O is also extensible so that developers or administrators can "plugin" support for additional formats.
63
Loading an Image File (1/2)
64
Loading an Image File (2/2)
65
Drawing an Image
boolean Graphics.drawImage(Image img, int x, int y, ImageObserver observer);
The x,y location specifies the position for the topleft of the image
The observer parameter notifies the application of updates to an image that is loaded asynchronously
The observer parameter is not frequently used directly and is not needed for the 66
BufferedImage class, so it usually is null
Drawing an Image Demo
Using setPaint method to set color
Using fill method to fill the area with a shape
67
Drawing an Image Demo Result
68
Using Local (SystemSpecific) Fonts
Local fonts: Lookup Fonts First
Use the getAvailableFontFamilyNames or getAllFonts methods of GraphicsEnvironment. GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
env.getAvailableFontFamilyNames() ;
env.getAllFonts(); // Much slower than just getting names!
Safest Option:
Supply list of preferred font names in order, loop down looking for first match
69
Supply standard font name as backup
Example: ListFonts
70
Drawing with Local Fonts
71
What is an Applet?
An applet is a program written in the Java programming language that can be included in an HTML page
When you use a Java technologyenabled browser to view a page that contains an applet
The applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM).
72
Class Applet and JApplet
An applet must be a subclass of the java.applet.Applet class, which provides the standard interface between the applet and the browser environment
Swing provides a special subclass of Applet, called javax.swing.JApplet, which should be used for all applets that use Swing components to construct their GUIs.
73
Life Cycle of Applet (1/2)
init
This method is intended for whatever initialization is needed for your applet
It is called after the param attributes of the applet tag.
start
This method is automatically called after init method
It is also called whenever user returns to the page containing the applet after visiting other pages.
74
Life Cycle of Applet (2/2)
stop
You can use this method to stop an animation.
destroy
This method is automatically called whenever the user moves away from the page containing applets
This method is only called when the browser shuts down normally
Thus, the applet can be initialized only once, started and stopped one or more times in its 75
life, and destroyed only once.
When to write Applets vs. Applications
An applet runs in the context of a web browser, being typically embedded within an html page
A Java application runs standalone, outside the browser
Applets are particularly well suited for providing functions in a web page which require more interactivity or animation than HTML
A graphical game, complex editing, or interactive data visualization
The end user is able to access the functionality 76
without leaving the browser
Loading Applets in a Web Page
In order to load an applet in a web page, you must specify the applet class with appropriate applet tags. A simple example is below:
<applet code=HelloAppletWorld.class width="200" height="200"></applet>
For development and testing purposes, you can run your applet using appletviewer application appletviewer HelloAppletWorld.html
77
How to convert an application program into an applet program
You need to create a subclass of java.applet.Applet in which you override the init method to initialize your applet's resources
The same way the main method initializes the application's resources.
init might be called more than once and should be designed accordingly
Moreover, the toplevel Panel needs to be added to the applet in init; usually it was added to a Frame in main. 78
HelloWorldApplet Demo
79
Applet Life Cycle Demo (1/2) 80
Applet Life Cycle Demo (2/2)
81
What Applets Can Do
Applets can usually make network connections to the host they came from.
Applets running within a Web browser can easily cause HTML documents to be displayed.
Applets can invoke public methods of other applets on the same page.
Applets that are loaded from the local file system (from a directory in the user's CLASSPATH) have none of the restrictions that 82
applets loaded over the network do. What Applets Cannot Do
Current browsers impose the following restrictions on any applet that is loaded over the network:
An applet cannot load libraries or define native methods
It cannot ordinarily read or write files on the host that's executing it
It cannot make network connections except to the host that it came from
It cannot start any program on the host that's executing it.
83
It cannot read certain system properties.
References
David J. Eck, ”Introduction to Programming Using Java”, Version 5.0, December 2006 http://math.hws.edu/javanotes/
“Working with Images” from http://java.sun.com/docs/books/tutorial/2d/images/in
“Java Tutorials: Applets” from http://java.sun.com/docs/books/tutorial/deployment/
“2D Drawing” from http://courses.coreservlets.com/CourseMaterials/ja
84