Topic 8: Basics of GUI Programming
Reading: Chapter 7
Advanced Programming Techniques
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
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.
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
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.
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.
Introduction: Ingredients of Swing GUI
• To create a swing GUI
1. 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).
Outline
• Introduction: Ingredients of Swing GUI
• Creating a frame (window)
• Displaying information in a panel
– Displaying texts
– 2D shapes
– Colors and fonts
– Images
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
Creating a Frame
Most methods for working with JFrame inherited from
superclasses:
Object
JFrame
Component
Container
Window
Frame
JPanel
JComponent
Ancestor of all GUI objects
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, ……
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
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)
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
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
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 object
Dimension getScreenSize --- get size of screen
Image 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
Outline
Introduction: Ingredients of Swing GUI
Creating a frame (window)
Displaying information in a panel
Displaying texts
2D shapes
Colors and fonts
Images
• An Example:
Displaying Information in a Frame
To create a GUI
1. 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
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);
• 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
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.
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.
• 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
Outline
Introduction: Ingredients of Swing GUI
Creating a frame (window)
Displaying information in a panel
Displaying texts
2D shapes
Colors and fonts
Images
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();
}
}
Outline
Introduction: Ingredients of Swing GUI
Creating a frame (window)
Displaying information in a panel
Displaying texts
2D shapes
Colors and fonts
Images
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);
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
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 constants
Color.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);
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
Outline
Introduction: Ingredients of Swing GUI
Creating a frame (window)
Displaying information in a panel
Displaying texts
2D shapes
Colors and fonts
Images
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
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
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);
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);}}
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)
Outline
Introduction: Ingredients of Swing GUI
Creating a frame (window)
Displaying information in a panel
Displaying texts
2D shapes
Colors and fonts
Images
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);
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
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

08graphics

  • 1.
    Topic 8: Basicsof GUI Programming Reading: Chapter 7 Advanced Programming Techniques
  • 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
  • 3.
    Introduction: Ingredients ofSwing GUI Build GUI with javax.Swing, available since JDK1.2 Better than java.awt, JDK1.1. Part of awt still in use.
  • 4.
    Introduction: Ingredients ofSwing 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
  • 5.
    Introduction: Ingredients ofSwing 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.
  • 6.
    Introduction: Ingredients ofSwing 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.
  • 7.
    Introduction: Ingredients ofSwing GUI • To create a swing GUI 1. 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).
  • 8.
    Outline • Introduction: Ingredientsof Swing GUI • Creating a frame (window) • Displaying information in a panel – Displaying texts – 2D shapes – Colors and fonts – Images
  • 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
  • 10.
    Creating a Frame Mostmethods for working with JFrame inherited from superclasses: Object JFrame Component Container Window Frame JPanel JComponent Ancestor of all GUI objects
  • 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, ……
  • 12.
    Creating a Frame Example: classSimpleFrame 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
  • 13.
    Creating a Frame Thingsto 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)
  • 14.
    Creating a Frame importjavax.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
  • 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
  • 16.
    Creating a Frame Needdimension of screen, which is platform dependent Get system-dependent info using java.awt.Toolkit class: getDefaultToolkit --- static method for creating a Toolkit object Dimension getScreenSize --- get size of screen Image getImage --- load image
  • 17.
    class CenteredFrame extendsJFrame { 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
  • 18.
    Outline Introduction: Ingredients ofSwing GUI Creating a frame (window) Displaying information in a panel Displaying texts 2D shapes Colors and fonts Images
  • 19.
    • An Example: DisplayingInformation in a Frame To create a GUI 1. 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
  • 20.
    Displaying Information ina Frame How to do 2, 3, 4? JFrame frame; 2. Container cPane = frame.getContentPane(); 3. JPanel p = new JPanel(); 4. cPane.add(p);
  • 21.
    • 5. Howto 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
  • 22.
    Displaying Information ina 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.
  • 23.
    Note about paintComponent() MainThread 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.
  • 24.
    • How totell 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
  • 25.
    Outline Introduction: Ingredients ofSwing GUI Creating a frame (window) Displaying information in a panel Displaying texts 2D shapes Colors and fonts Images
  • 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
  • 27.
    Step2 : Derivea 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
  • 28.
    • 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(); } }
  • 29.
    Outline Introduction: Ingredients ofSwing GUI Creating a frame (window) Displaying information in a panel Displaying texts 2D shapes Colors and fonts Images
  • 30.
    Using Text Fonts Classjava.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);
  • 31.
    Using Text Fonts Only5 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
  • 32.
    Using Colors Class java.awt.Color Createnew 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 constants Color.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);
  • 33.
    Using Text Fonts Classjava.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”);
  • 34.
    public void paintComponent(Graphicsg) { 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
  • 35.
    Outline Introduction: Ingredients ofSwing GUI Creating a frame (window) Displaying information in a panel Displaying texts 2D shapes Colors and fonts Images
  • 36.
    2D Shapes • Youcan 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
  • 37.
    2D Shapes • Youcan 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
  • 38.
    2D Shapes: drawrectangles 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);
  • 39.
    2D Shapes:draw lineand 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);}}
  • 40.
    Drawing Lines andShapes 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)
  • 41.
    Outline Introduction: Ingredients ofSwing GUI Creating a frame (window) Displaying information in a panel Displaying texts 2D shapes Colors and fonts Images
  • 42.
    Displaying Images Java Toolkitobject 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);
  • 43.
    Displaying Images Java spawnsa 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
  • 44.
    Summary • To createa 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