Chapter 10 Getting Started with Graphics Programming

Download Report

Transcript Chapter 10 Getting Started with Graphics Programming

Getting Started with Graphics
Programming
Graphics Class Hierarchy
 Frames
– Creating frames, centering frames, adding
components to frames
 Layout Managers

– FlowLayout, GridLayout, BorderLayout

Drawing on Panels
– The paintComponent() method
Using Colors
 Drawing Geometric Figures

– Lines, Rectangles, Ovals, Arcs, and Polygons
Getting Started with Graphics
Programming






Graphics Class Hierarchy
Frames
Layout Managers
Drawing on Panels
Using Colors
Drawing Geometric Figures
Graphical User Interface (GUI)

AWT - Abstract Windowing Toolkit
import java.awt.*;
(Heavyweight) AWT components are automatically mapped to the
platform-specific components.

SWING - GUI for Java (since Version 1.2)
import javax.swing.*;
(Lightweight) Swing components are painted directly on canvas
using Java code (excepts for the components that are subclasses of
java.awt.Window and java.awt.Panel). Swing components are
less dependent on platform and use less of the native GUI
resources.
GUI Concepts
Component: This is superclass of all user interface
classes (Buttons, Text Boxes, Labels, Menus, Lists, etc).
 Container: This is to group components.
Frames, panels and applets are examples of containers.
 Panel: This is invisible container that holds UI
components. Panels can be nested. JPanel can be used
as a canvas to draw graphics.
 Layout Manager: A manager is used to position and
place components in a container.
 Graphics: This is an abstract class that provides a
graphical context for drawing shapes and strings.

GUI Concepts, cont.
JComponent: This is superclass for all the lightweight
Swing components. Its subclasses (JLabel,JList,
JButton,JMenu, etc.) are the basic elements for
constructing the GUI.
 Color: This class deals with the colors of graphics
components.
 Font: This is used for string drawing in Graphics.

You can specify font type (SansSerif), style (Bold), and size (24
points).

Event Handling: How to respond to events such
as mouse clicks, button clicks, keyboard input, frame
events.
Java Class Hierarchy
javax.swing starts with J
Object
Component
Window
Container
Frame
JComponent
JFrame
JLabel
Panel
JCheckBox
JPanel
...
JButton
JComponent
.
JCheckBoxMenuItem
AbstractButton
JMenuItem
JMenu
JButton
.JRadioButtonMenuItem
.JToggleButton
JCheckBox
JRadioButton
.JEditorPane
JComponent
.JTextComponent
.JTextField
.JPasswordField
.JTextArea
.JLabel
.JList
.JComboBox
.JMenuBar
.JPanel
.JOptionPane
.JScrollBar
.JScrollPane
.JPopupMenu
.JSeparator
.JSlider
.JTabbedPane
.JRootPane
.JPane
.JProgressBar
.JToolBar
.JSplitPane
.JTable
.JTree
.JColorChooser
.JInternalFrame
.JToolTip
.JLayeredPane
.JTableHeader
.JFileChooser
Frames
 Frame
is a window that is not contained inside
another window.
 Frame
is the basis to contain other user interface
components in Java graphical applications.
 The
Frame class can be used to create windows.
UI Components
Frame
Pull-down Menus
Pull-down Menus
Applet
Panel
User Interface
Components (UI)
Panel
Panel
User Interface
Components
User Interface
Components
Panel
Panel
User Interface
Components
User Interface
Components
Panel
Panel
Panel
Panel
UI
UI
UI
panel
Creating Frames
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("Test Frame");
frame.setSize(400,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
Centering Frames
• By default, a frame is displayed in the upperleft corner of the screen.
• To display a frame at a specified location, use
the setLocation(x,y) method in the
JFrame class. This method places the upperleft corner of a frame at location (x,y).
Centering Frames, cont.
(0,0)
Screen
(x, y)
Frame
frameHeight
screenWidth
screenWidth
screenHeight
Centering Frames
import javax.swing.*;
public class MyFrame {
public static void main(String[] args)
{
JFrame frame = new JFrame("Test Frame");
frame.setVisible(true);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.setSize(400,300);
Dimension frameSize = frame.getSize();
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
int x = (screenSize.width - frameSize.width)/2;
int y = (screenSize.height - frameSize.height)/2;
frame.setLocation(x,y);
}
}
Adding Button into a Frame
The button is always centered in the frame and
occupies the entire frame no matter how you resize the
frame.
 This is because components are put in the frame by
the content pane’s layout manager, and the default
layout manager for the content pane places the button
in the center.
• For some functions, such as adding a JComponent, you cannot
use JFrame.add, but instead you must first get the associated
Container object of the JFrame , ContentPane, with
JFrame.getContentPane(), and add to that.
Adding Button into a Frame
JFrame frame = new JFrame();
frame.setTitle("Test JButton");
Container cp = frame.getContentPane();
JButton button = new JButton("OK");
cp.add(button);
Layout Managers
 Java’s
layout managers provide a level of
abstraction to automatically map your user
interface on all windowing systems.
 The
UI components are placed in containers.
Each container has a layout manager to arrange
the UI components within the container.
Kinds of Layout Managers

FlowLayout

GridLayout

BorderLayout

GridBagLayout

CardLayout
Kinds of Layout Managers
CardLayout ... later
The FlowLayout Manager
The
FlowLayout is the simplest layout manager.
The
components are arranged in the container from left
to right in the order in which they were added.
When
one row becomes filled, a new row is started.
Default layout for panels.
 Can be centered, left or right: FlowLayout.LEFT,

FlowLayout.CENTER, or FlowLayout.RIGHT.
Flow Layout: examples
FlowLayout Constructors

public FlowLayout(int align, int hGap, int
vGap)
Constructs a new FlowLayout with a specified alignment,
horizontal gap, and vertical gap. The gaps are the distances in
pixel between components.

public FlowLayout(int alignment)
Constructs a new FlowLayout with a specified alignment and
a default gap of five pixels for both horizontal and vertical.

public FlowLayout()
Constructs a new FlowLayout with a default center alignment
and a default gap of five pixels for both horizontal and
vertical.
FlowLayout: Example
import javax.swing.*;
import java.awt.*;
public class MyFrame
{
public MyFrame()
{
Container container = getContentPane();
container.setLayout(new FlowLayout());
for(int i=1; i <= 10; i++)
container.add(new JButton(“Component”+i));
}
public static void main(String[] args) {
MyFrame frame = new MyFrame();
frame.setTitle(“Test FlowLayout”);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
frame.setVisible(true);
}
}
FlowLayout: Example
Container container = getContentPane();
container.setLayout(new FlowLayout());
The GridLayout Manager

The GridLayout manager arranges components
in a grid (matrix) formation with the number of
rows and columns defined by the constructor.

The components are placed in the grid from left to
right starting with the first row, then the second, and so
on.
GridLayout Constructors

public GridLayout(int rows, int columns)
Constructs a new GridLayout with the specified
number of rows and columns.

public GridLayout(int rows, int columns,
int hGap, int vGap)
Constructs a new GridLayout with the specified
number of rows and columns, along with specified
horizontal and vertical gaps between components.
Border Layout
Screen is divided into 5 areas:
Centre, North, South, East, West.
 Centre area is greediest (will take as much space as
possible).
 Others will try to paint at least to their preferred size.
 All components will try to maximise themselves.
 Most useful one for laying out of main frame.

The BorderLayout Manager
The BorderLayout manager divides the window into five
areas: East, South, West, North, and Center.
Components are added to a BorderLayout by using
method
add(Component, constraint);
where constraint is
BorderLayout.East,
BorderLayout.South,
BorderLayout.West,
BorderLayout.North, or
BorderLayout.Center.
Example
public MyFrame()
{
Container container = getContentPane();
container.setLayout(new BorderLayout(5,10));
container.add(new JButton(“East”,
BorderLayout.East);
container.add(new JButton(“South”,
BorderLayout.South);
container.add(new JButton(“West”,
BorderLayout.West);
container.add(new JButton(“Center”,
BorderLayout.Center);
container.add(new JButton(“Center”,
BorderLayout.North);
}
The BorderLayout Manager
Using Panels as Containers
 Panels
act as smaller containers for grouping
user interface components.
 It
is recommended that you place the user
interface components in panels and place the
panels in a frame.
 You
can also place panels in a panel.
Border Layout Nested
Example: Microwave oven
This example uses panels to organize components.
The program creates a user interface for a microwave oven.
Example: Two Panels
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4,3));
for(i=1; i<=9; i++) {
p1.add(new JButton(“ ”+i));
}
p1.add(new JButton(“ 0”));
p1.add(new JButton(“Start”));
p1.add(new JButton(“Stop”));
//
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
p2.add(new JTextField(“Time to be displayed here”),
BorderLayout.NORTH);
p2.add(p1,BorderLayout.CENTER);
Example: Add Panels
Container container = getContentPane();
container.setLayout(new BorderLayout());
container.add(p2, BorderLayout.EAST);
container.add(new Button(“Food to be placed here”),
BorderLayout.CENTER);
Drawing on Panels
JPanel can be used to draw graphics (including
text) and enable user interaction.

To draw in a panel, you create a new class that
extends JPanel and override the
paintComponent() method to tell the panel
how to draw things.

 You
can then display strings, draw geometric
shapes, and view images on the panel.
The Color Class
Color c = new Color(r, g, b);
r,g, and b specify a color by its red, green, and
blue components.
Example:
Color c = new Color(128, 100, 100);
Setting Colors
You can use the following methods to set the
component’s background and foreground colors:
setBackground(Color c);
setForeground(Color c);
Example:
setBackground(Color.yellow);
setForeground(Color.red);
Drawing Geometric Figures

To draw in a panel, create a new class that extends
JPanel and overrides the paintComponent()
method.

Then one can display strings, draw geometrical shapes,
and view images on the panel.

Although one can draw things directly in a frame or
an applet using the paint() method, using JPanel
for to draw messages and shapes and to show images
is recommended; this way the drawing does not
interfere with other components.
Drawing Geometric Figures

The signature of the paintComponent method:
public void paintComponent(Graphics g)

The Graphics object g is created automatically by the
Java runtime system. This object controls how information
is drawn.
g.drawLine(x1,y1,x2,y2);
g.drawRect(x0,y0,width,height);
Drawing Geometric Figures

Drawing Lines

Drawing Rectangles

Drawing Ovals

Drawing Arcs

Drawing Polygons

Drawing Strings
Drawing Lines
g.drawLine(x1, y1, x2, y2);
(x1 , y1)
(x2 , y2)
Drawing Rectangles

g.drawRect(x, y, w, h);

g.fillRect(x, y, w, h);
(x, y)
h
w
Drawing Rounded Rectangles

g.drawRoundRect(x, y, w, h, aw, ah);

g.fillRoundRect(x, y, w, h, aw, ah);
(x, y)
ah
aw
h
w
Drawing Ovals

g.drawOval(x, y, w, h);

g.fillOval(x, y, w, h);
(x, y)
h
w
Drawing Arcs


g.drawArc(x, y, w, h, angle1, angle2);
g.fillArc(x, y, w, h, angle1, angle2);
(x, y)
angle2
angle1
w
h
Drawing Polygons
int[] x = {40, 70, 60, 45, 20};
int[] y = {20, 40, 80, 45, 60};
g.drawPolygon(x, y, x.length);
g.fillPolygon(x, y, x.length);
(x[0], y[0])
(x[1], y[1])
(x[3], y[3])
(x[4], y[4])
(x[2], y[2])
Drawing Polygons, cont.
int[] x = {40, 70, 60, 45, 20};
int[] y = {20, 40, 80, 45, 60};
Polygon poly = new Polygon(x,y,5);
g.drawPolygon(poly);
g.fillPolygon(poly);
(x[0], y[0])
(x[1], y[1])
(x[3], y[3])
(x[4], y[4])
(x[2], y[2])
Example: Drawing
import javax.*;
import java.awt.*;
public class TestGraphics()
{
public TestGraphics() {
setTitle(“Test Draw”);
getContentPane().add(new DrawPanel());
}
public static void main(Strings[] args) {
TestGraphics frame = new TestGraphics();
frame.setSize(300,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
Example: Drawing
public class DrawPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setBackground(Color.white);
g.setColor(Color.red);
g.drawRect(100,100,100,100);
g.drawString(“Test Draw”,110,230);
g.setColor(Color.green);
g.drawLine(50,50,250,250);
}
}