COMP201 Java Programming Topic 8: Basics of GUI Programming Reading: Chapter 7
Dec 19, 2015
COMP201 Topic 8 / Slide 2
Objectives and Outline Objectives:
Understanding general structure of GUI Creating frames and displaying information
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 Build GUI with javax.Swing, available since JDK1.2
Better than java.awt, JDK1.1. Part of awt still in use.
COMP201 Topic 8 / Slide 4
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
Atomic components.
JPanel3JPanel1
JPanel2
Containment hierarchy of Swing components in GUI
COMP201 Topic 8 / Slide 5
Introduction: Ingredients of Swing GUI
Top-level containers: Provide a place for other Swing components to paint themselves. Other top-level containers: Jdialog, JApplet
Every top-level container contains an intermediate container known as a content pane. The content pane contains all of the visible components in the window's GUI. Exception to rule: menu bar
JPanel is an intermediate container. Can be used to simplify the positioning of the button and label. Other intermediate containers: JScrollPane, JTabbedPane
– Play a more visible, interactive role in a program's GUI.
COMP201 Topic 8 / Slide 6
Introduction: Ingredients of Swing GUI
JComponent: The base class for all Swing components (everything except
JFrame). Knows how to paint itself
– protected void paintComponent(Graphics g)
Atomic components such as JLabel, JButton are JComponents JPanels
– can contain atomic components such as JButtons and Jlabels. Or JPanels themselves (Topic 10)
– Are JComponents themselves. Can override the paintComponent method to display text, shapes, and image.
COMP201 Topic 8 / Slide 7
To create a swing GUI1. Create a top-level container: JFrame
2. Get contentPane of the top-level container
3. Create JPanels
4. Layout the JPanels onto the contentPane.
5. Add components to JPanels or draw on them.
6. Create menu bar (Topic 10).
7. Handle events (Topic 9).
Introduction: Ingredients of Swing GUI
COMP201 Topic 8 / Slide 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
Creating a Frame
Frame Positioning: Want a frame that Is centered in the middle of the screen Covers ¼ of the screen (Run CenteredFrameTest.java). Shows java cup (image) when minimized
COMP201 Topic 8 / Slide 16
Creating a Frame
Need dimension of screen, which is platform dependent
Get system-dependent info using java.awt.Toolkit class:
getDefaultToolkit --- static method for creating a Toolkit objectDimension getScreenSize --- get size of screenImage getImage --- 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 18
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 19
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
4. Add the JPanels onto the contentPane.
5. Add GUI components to the JPanels or draw on them
COMP201 Topic 8 / Slide 20
Displaying Information in a Frame
How to do 2, 3, 4?
JFrame frame;2. Container cPane = frame.getContentPane();3. JPanel p = new JPanel();
4. cPane.add(p);
COMP201 Topic 8 / Slide 21
5. How to draw custom graphics, in this case a text string, to JPanel? A JPanel is a JComponent
– Has method paintComponent to draw itself.
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 22
Displaying Information in a Frame
Method paintComponent(Graphics g) is called automatically when opening, resizing, and moving window. Graphics object automatically created.
Never call it explicitly.
Use the repaint method of Component to force repainting.
COMP201 Topic 8 / Slide 23
Note about paintComponent()
Main Thread Event Dispatch Thread
Single thread rule: Modify GUI components only in the event dispatch thread to avoid corruption.
repaint() creates an paintEvent and sends it to the event dispatch thread for handling.
calling paintComponent() directly violates the single thread rule.
COMP201 Topic 8 / Slide 24
How to tell paintComponent(Graphics g) what and how to draw?
The method takes a java.awt.Graphics object as input.– Graphics: class for graphics context
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 25
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 26
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 29
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 30
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 31
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 32
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.setColor(Color.pink); g.drawString(“Hi”, 55, 55); g.setColor(c); g.drawString(“there”, 80, 55);
COMP201 Topic 8 / Slide 33
Using Text Fonts
Class java.awt.FontMetrics
Methods for getting information about fonts:Graphics g;
Font f = new Font("SansSerif", Font.BOLD, 14);
FontMetrics fm = g.getFontMetrics(f);
int w = fm.stringWidth(“Not Hello”);
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); }
NotHelloWorld2.java
COMP201 Topic 8 / Slide 35
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 36
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; …
} The cast is legal because paintComponent automatically receives a Graphics2D object if SDK is Java 2D enabled
COMP201 Topic 8 / Slide 37
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 38
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 39
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 40
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.
Graphics: public abstract void setXORMode(Color c1)
COMP201 Topic 8 / Slide 41
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 42
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 43
Displaying Images
Java spawns 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 44
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