comp201 java programming part ii: gui programming topic 8: basics of graphics programming reading:...
Post on 21-Dec-2015
245 views
TRANSCRIPT
COMP201 Java Programming
Part II: GUI Programming
Topic 8: Basics of Graphics Programming
Reading: Chapter 7
COMP201 Topic 8 / Slide 2
Outline
Introduction: Ingredients of Swing GUI
Creating a frame (window)
Displaying information in a panel Displaying texts 2D shapes Colors and fonts Images
COMP201 Topic 8 / Slide 3
Introduction: Ingredients of Swing GUI
Top-level container: JFrame (Window) in this case
Menu bar (optional)
contentPane: contains all visible components Intermediate containers to organize
various GUI components: JPanels in this case
JPanel3JPanel1
JPanel2
Build GUI with javax.Swing, JDK1.2
Better than java.awt, JDK1.1
COMP201 Topic 8 / Slide 4
To create a swing GUI1. Create a top-level container: JFrame
2. Get contentPane of the top-level container
3. Create JPanels and add GUI components to the JPanels
4. Layout the JPanels onto the contentPane.
JPanels can contain Atomic components such as JButtons and Jlabels (Topic 10) Custom graphics such as text, shapes, and images (This Topic)
Introduction: Ingredients of Swing GUI
COMP201 Topic 8 / Slide 5
Creating a Frame Frame: top-level window, not contained inside another
window.
Use JFrame class in javax.swing package.
What can you do with JFrame:- Create a new one- get/setSize- get/setLocation- get/setTitle- show/hide
- toFront/toBack- is/setResizable- dispose- setIconImage
COMP201 Topic 8 / Slide 6
Creating a Frame Most methods for working with JFrame inherited from
superclasses:
Object
JFrame
Component
Container
Window
FrameJPanel
JComponent
Ancestor of all GUI objects
COMP201 Topic 8 / Slide 7
Creating a Frame
java.awt.Component: getLocation, setBounds, setLocation, getSize, setSize, setBackground, setForeground, repaint, ……
java.awt.Window:toFront, toBack, show, hide, ……
java.awt.Frame: dispose, setResizable, setTitle, setIcomImage, ……
COMP201 Topic 8 / Slide 8
Creating a Frame Example:
class SimpleFrame extends JFrame{ public SimpleFrame() { setSize(WIDTH, HEIGHT); }
public static final int WIDTH = 300; public static final int HEIGHT = 200;}
Default constructor of JFrame is called.
Default size of a JFrame: 0x0
COMP201 Topic 8 / Slide 9
Creating a Frame Things to know about coordinates
– Units are expressed pixels (depends on resolution)– Coordinate system is vertically-flipped from Cartesian– (0,0) is upper left corner of screen– Frame defaults to location (0,0) and size (0,0)
COMP201 Topic 8 / Slide 10
Creating a Frame
import javax.swing.*;public class SimpleFrameTest{ public static void main(String[] args) { SimpleFrame frame = new SimpleFrame(); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.show(); }} // SimpleFrameTest.java
Create a SimpleFrame. Show it. JDK1.3 feature
COMP201 Topic 8 / Slide 11
Internal Structure of JFrame
JFrameJRoot
JLayerPane
menu bar
glass pane
content paneButton
COMP201 Topic 8 / Slide 12
Instance fields of JRootPane:
protected JMenuBar menuBarprotected Container contentPaneprotected JLayeredPane layeredPane
Manages the menu bar and content pane. Menu bar positioned at top of frame and content
pane fills the remaining areaprotected Component glassPane The glass pane that overlays the menu bar and
content pane, so it can intercept mouse movements and such.
…..
COMP201 Topic 8 / Slide 13
Creating a Frame
Frame Positioning: Want a frame that Is centered in the middle of the screen Covers ¼ of the screen (Run CenteredFrameTest.java).
Coordinate system: Units are expressed in pixels (effects depend on monitor resolution)
COMP201 Topic 8 / Slide 14
Creating a Frame
Also need dimension of screen, which is platform dependent
Get system-dependent info using java.awt.Toolkit class:
getDefaultToolkit --- static method for creating a Toolkit objectgetScreenSize --- get size of screengetImage --- load image
class CenteredFrame extends JFrame{ public CenteredFrame() { // get screen dimensions Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screenSize = kit.getScreenSize(); int screenHeight = screenSize.height; int screenWidth = screenSize.width;
// center frame in screen setSize(screenWidth / 2, screenHeight / 2); setLocation(screenWidth / 4, screenHeight / 4);
// set frame icon and title Image img = kit.getImage("icon.gif"); setIconImage(img); setTitle("CenteredFrame"); }} //CenteredFrameTest.java
COMP201 Topic 8 / Slide 16
An Example:
Displaying Information in a Frame
To create a GUI1. Create a top-level container: JFrame
2. Get contentPane of the top-level container
3. Create JPanels and add GUI components to the JPanels
4. Add the JPanels onto the contentPane.
COMP201 Topic 8 / Slide 17
Displaying Information in a Frame
How to add JPanel onto the contentPane of JFrame?
JPanel p = new JPanel();Container cPane = frame.getContentPane();cPane.add(p);
COMP201 Topic 8 / Slide 18
How to add custom graphics, in this case a text string, to JPanel? A JPanel draws its contents by calling its paintComponent
method (inherited from JComponent). We can:
– Define a new class that extends JPanel– Override the paintComponent method to draw what we want.
Class MyPanel extends JPanel{ public paintComponent(Graphics g){ super.paintComponent(g); // draw background
// code for drawing }}
Displaying Information in a Frame
COMP201 Topic 8 / Slide 19
Displaying Information in a Frame
Method paintComponent is called automatically when opening, resizing, and moving window.
Never call it explicitly.
Use the repaint method of Component to force repainting.
COMP201 Topic 8 / Slide 20
How to tell paintComponent(Graphics g) what and how to draw?
The method takes a java.awt.Graphics object as input.
We encapsulate information about what/how to draw in the Graphics object.
Next:– Displaying texts– Colors and fonts– 2D shapes– Images
Displaying Information in a Frame
COMP201 Topic 8 / Slide 21
Example: NotHelloWorld Step1. Derive a new class NotHelloWorldPanel by extending JPanel and
specify what we want to draw on the panel and how.
class NotHelloWorldPanel extends JPanel{ public void paintComponent(Graphics g) { // Draw background
super.paintComponent(g);
g.drawString("Not a Hello, World program", MESSAGE_X, MESSAGE_Y); } public static final int MESSAGE_X = 75; public static final int MESSAGE_Y = 100;} //NotHelloWorld.java
Step2 : Derive a new class NotHelloWorldFrame by extending JFrame, create a NotHelloWorldPanel and add it to the contentPane of the frame.
class NotHelloWorldFrame extends JFrame{ public NotHelloWorldFrame() { setTitle("NotHelloWorld"); setSize(WIDTH, HEIGHT); // add panel to frame NotHelloWorldPanel panel = new NotHelloWorldPanel(); Container contentPane = getContentPane(); contentPane.add(panel); } public static final int WIDTH = 300; public static final int HEIGHT = 200;} //NotHelloWorld.java
• Step3 : Create a NotHelloWorldFrame and show it.
import javax.swing.*;import java.awt.*;
public class NotHelloWorld{ public static void main(String[] args) { NotHelloWorldFrame frame = new NotHelloWorldFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show(); }}
COMP201 Topic 8 / Slide 24
Using Text Fonts
Class java.awt.Font Create Font objects:
Font f1 = new Font(“Serif”, Font.PLAIN, 20);Font f2 = new Font(“Serif”, Font.PLAIN +
Font.ITALIC, 16);
Using fonts:Graphics g;g.setFont(f1);
g.drawString("Not a Hello, World program",
75, 100);
COMP201 Topic 8 / Slide 25
Using Text Fonts
Only 5 font families guaranteed to exist
– SansSerif, Serif, Monospaced, Dialog, DialogInput
– Can ask for others by name(“Arial”) but may not get what you want
– Find out all available fonts on a machine using the getAvailableFontFamilyNames method of the GraphicsEnvironment class.
Style limited to PLAIN, BOLD, ITALIC
Default using plain 12pt SansSerif
COMP201 Topic 8 / Slide 26
Using Text Fonts
Class java.awt.FontMetricsMethods for getting information about fonts:
NotHelloWorld2.java
COMP201 Topic 8 / Slide 27
Using Colors
Class java.awt.Color Create new color objects: Color c = new Color(100, 25, 200);
• Red-green-blue (RGB) color model• Each component can have in range 0 to 255
13 predefined color constantsColor.black, Color.red, Color.green, etc.
Using Colors: Graphics2D g; g.setPaint(Color.pink); g.drawString(“Hi”, 55, 55); g.setPaint(c); g.drawString(“there”, 80, 55);
public void paintComponent(Graphics g) { super.paintComponent(g); setFonts(g); String s1 = "Not a "; String s2 = "Hello, World"; String s3 = " Program"; int w1 = fm.stringWidth(s1); int w2 = fim.stringWidth(s2); int w3 = fm.stringWidth(s3); Dimension d = getSize(); int cx = (d.width - w1 - w2 - w3) / 2; int cy = (d.height - fm.getHeight()) / 2 +fm.getAscent(); g.setFont(f); g.drawString(s1, cx, cy); cx += w1; g.setFont(fi); g.setColor(Color.red); g.drawString(s2, cx, cy); cx += w2; g.setFont(f); g.drawString(s3, cx, cy); }
COMP201 Topic 8 / Slide 29
2D Shapes
You can draw lines, rectangles, ellipses, etc, using class
java.awt.Graphics drawLine, drawArc, drawPolygon drawPolyline, drawRect, drawRoundRect, draw3DRect, fillRect,
The subclass java.awt.Graphics2D is better
Need cast:public void paintComponent(Graphics g)
{ Graphics2D g2 = (Graphics2D) g; …
}
COMP201 Topic 8 / Slide 30
2D Shapes You can draw by using the methods shown on the previous slides.
It’s better to use the geometric shape classes: java.awt.geom.*Line2D, Rectangle2D, Ellipse2D, Point2D, …
All those classes implement the Shape interface and Graphics2D has method draw(Shape s)
All are abstract classes with two concrete static inner classes. E.g.Rectangle2D.Double, Rectangle2D.Float
Usually use the Double version. The Float version saves space but is troublesome
float f = 1.2; //illegal. Need cast: float f = (float) 1.2;
See DrawTest.java
COMP201 Topic 8 / Slide 31
2D Shapes: draw rectangles
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; // draw a rectangle double leftX = 100; double topY = 100; double width = 200; double height = 150; Rectangle2D rect = new Rectangle2D.Double(leftX, topY,width, height); g2.draw(rect);
COMP201 Topic 8 / Slide 32
2D Shapes:draw line and circle // draw the enclosed ellipse Ellipse2D ellipse = new Ellipse2D.Double(); ellipse.setFrame(rect); g2.draw(ellipse);
// draw a diagonal line g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height)); // draw a circle with the same center double centerX = rect.getCenterX(); double centerY = rect.getCenterY(); double radius = 150;
Ellipse2D circle = new Ellipse2D.Double(); circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius); g2.draw(circle);}}
COMP201 Topic 8 / Slide 33
Drawing Lines and Shapes
Paint Mode
Default: last drawn shape covers earlier one. XOR mode:
If you draw one shape twice in XOR mode, the second one erases the first one.
COMP201 Topic 8 / Slide 34
Displaying Images Java Toolkit object can read GIF and JPEG files. Get image from file Image image =
Toolkit.getDefaultToolkit().getImage(FileName);
Get image from the Net: URL u = new URL(http://www.somehwere/ImageFile); Image image = Toolkit.getDefaultToolkit().getImage(u);
Display image: g.drawImage(image, x, y, null);
COMP201 Topic 8 / Slide 35
Displaying Images
Java spawn a separate thread to load image, which run in parallel with the main thread.
Use MediaTracker class to wait until image is completely loaded before drawing
public ImagePanel() { image = Toolkit.getDefaultToolkit().getImage ("Cat.gif"); MediaTracker tracker = new MediaTracker(this); tracker.addImage(image, 0); try { tracker.waitForID(0); } catch (InterruptedException e) {} } Example: ImageTest.java
COMP201 Topic 8 / Slide 36
Summary
To create a Swing GUI Create JPanels and add GUI components to the JPanels
– Custom graphics: Override the paintComponent(Graphics g) method Encapsulate what and how to draw in the graphics object
– Predefined GUI components: simply add to the panel (Topic 10)
– Hierarchical: Panels can contain other panels
Create a top-level container: JFrame and layout the JPanels onto the contentPane of the container