+ All Categories
Home > Documents > 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

Date post: 31-Dec-2015
Category:
Upload: gyles-preston
View: 214 times
Download: 0 times
Share this document with a friend
49
1 Inner Classes, Software Inner Classes, Software Design Patterns, Swing Design Patterns, Swing API API James Atlas James Atlas July 1, 2008 July 1, 2008
Transcript
Page 1: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

11

Inner Classes, Software Inner Classes, Software Design Patterns, Swing APIDesign Patterns, Swing API

James AtlasJames Atlas

July 1, 2008July 1, 2008

Page 2: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 22

ReviewReview

• Last week’s Quiz/AssignmentLast week’s Quiz/Assignment Use polymorphism for functionality that depends Use polymorphism for functionality that depends

on the typeon the type• Formatting of MediaItem subclassesFormatting of MediaItem subclasses

• Use of instanceof is generally bad practiceUse of instanceof is generally bad practice Subclasses should call superclass constructorsSubclasses should call superclass constructors

• super(title,year, …)super(title,year, …)

• StreamsStreams

• CollectionsCollections

Page 3: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 33

QuizQuiz

Page 4: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 44

Inner/Nested ClassesInner/Nested Classes

• An An inner class is a class that is defined inside is a class that is defined inside of another classof another class

• Why would you want inner classes?

Page 5: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 55

Inner/Nested ClassesInner/Nested Classes

• An An inner class is a class that is defined inside is a class that is defined inside of another classof another class

• Why would you want inner classes?An object of an inner class can directly access

the implementation (private/protected members) of the object that defined it

Inner classes can be hidden from other classes in the same package

Inner classes are very convenient with event-driven (GUI) programming

Can implement helper classes/functions

Page 6: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 66

Example: Example: java.util.Map/java.util.HashMapjava.util.Map/java.util.HashMappublic class HashMap<K,V>

extends AbstractMap<K,V>

implements Map<K,V>, Cloneable, Serializable

{

...

private abstract class HashIterator<E> implements Iterator<E> {

...

final Entry<K,V> nextEntry() {

...

if ((next = e.next) == null) {

Entry[] t = table;

while (index < t.length && (next = t[index++]) == null);

}

}

}

}

Page 7: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 77

Alternative Inner Class Alternative Inner Class ConstructorConstructor• using an object of the outer classusing an object of the outer classpublic class Bird extends ZooAnimal {

int beakLength;

public class Cage {

Shape shape;

Material material;

}

}

Bird b = new Bird();Bird b = new Bird();

Bird.Cage bc = b.new Cage();Bird.Cage bc = b.new Cage();

Page 8: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 88

Static Inner Class ConstructorStatic Inner Class Constructorpublic class Bird extends ZooAnimal {

int beakLength;

public static class Cage {

Shape shape;

Material material;

}

}

Bird b = new Bird();Bird b = new Bird();

Bird.Cage bc = new Bird.Cage();Bird.Cage bc = new Bird.Cage();

Page 9: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 99

Local Inner ClassesLocal Inner Classes

• Specific/Specific/locallocal to to one method onlyone method only define inner classes within a block of codedefine inner classes within a block of code

• additionally have access to any additionally have access to any finalfinal variables within the block of codevariables within the block of code

Page 10: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 1010

Local Inner Classes and Local Local Inner Classes and Local VariablesVariablesprivate double balance = 1;

public void start(final double rate){

// local to start methodclass InterestAdder implements ActionListener{ public void actionPerformed(ActionEvent evt) { double interest = balance * rate / 100; balance += interest; }}

ActionListener adder = new InterestAdder();Timer t = new Timer(1000, adder);t.start();

}

Page 11: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 1111

Anonymous Inner ClassesAnonymous Inner Classes

• When using a local inner class, we can take When using a local inner class, we can take this process a step furtherthis process a step further

• If you only want to make a If you only want to make a singlesingle object of a object of a certain class, you do not need to give the certain class, you do not need to give the class a name! class a name! Called an Called an anonymous inner classanonymous inner class

Page 12: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 1212

Anonymous Inner ClassesAnonymous Inner Classes

public void start(final double rate){

ActionListener adder = new ActionListener( ){ public void actionPerformed(ActionEvent evt) { double interest = balance * rate / 100; balance += interest; }};Timer t = new Timer(1000, adder);t.start();

}

Where construction parameters would go

Page 13: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 1313

Anonymous Inner ClassesAnonymous Inner Classes

• Confusing syntax!Confusing syntax!

• Create a new class that implements the Create a new class that implements the ActionListener interfaceActionListener interfacerequired method, actionPerformed(), is defined required method, actionPerformed(), is defined

inside the bracesinside the braces

• Any needed parameters are inside the Any needed parameters are inside the parentheses, following the parentheses, following the supertype name: name:

new SuperType(construction parameters){

inner class methods and data};

Page 14: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 1414

Summary of Inner ClassesSummary of Inner Classes

Type Scope Inner? Summary

StaticStatic MemberMember NoNo Can access static fields of Can access static fields of enclosing class.enclosing class.

MemberMember MemberMember YesYes

Accesses static and non-static Accesses static and non-static fields of enclosing class. fields of enclosing class. Associated w/ an instance of Associated w/ an instance of enclosing class.enclosing class.

LocalLocal LocalLocal YesYesLocal to a block of code. Can Local to a block of code. Can access final fields of containing access final fields of containing scope. Java statement.scope. Java statement.

AnonymousAnonymousOnly Only point point

defineddefinedYesYes

Not named. Class definition and Not named. Class definition and object instantiation in same object instantiation in same statement. Java expression.statement. Java expression.

Page 15: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 1515

Software Design PatternsSoftware Design Patterns

• A “hot topic” in the 1990sA “hot topic” in the 1990s

• Design Patterns: Elements of Reusable Design Patterns: Elements of Reusable Object-Oriented SoftwareObject-Oriented Software Erich Gamma, Richard Helm, Ralph Johnson, Erich Gamma, Richard Helm, Ralph Johnson,

and John Vlissides (AKA - Gang of Four)and John Vlissides (AKA - Gang of Four) http://en.wikipedia.org/wiki/Design_Patternshttp://en.wikipedia.org/wiki/Design_Patterns Highly influential in Software EngineeringHighly influential in Software Engineering

Page 16: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 1616

What is a Software Design What is a Software Design Pattern?Pattern?• Recurring solution to common problems in Recurring solution to common problems in

software designsoftware design

• Types of patterns:Types of patterns: CreationalCreational StructuralStructural BehavioralBehavioral ArchitecturalArchitectural

Page 17: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 1717

Creational PatternsCreational Patterns

• Abstract factoryAbstract factory

• Factory methodFactory method

• BuilderBuilder

• Lazy initializationLazy initialization

• Object poolObject pool

• PrototypePrototype

• SingletonSingleton

• UtilityUtility

Page 18: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 1818

Factory MethodFactory Method

• Interface for creating an objectInterface for creating an object

Example:Example:enum MediaType {BOOK, DVD, etc.};

public static MediaItem createFromString(String line) {

MediaType type = figureOutMediaType(line);

switch(type) {

case MediaType.BOOK:

return new Book(line);

case MediaType.DVD:

return new DVD(line);

// etc.

}

}

Page 19: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 1919

Structural PatternsStructural Patterns

• AdapterAdapter

• BridgeBridge

• CompositeComposite

• DecoratorDecorator

• FacadeFacade

• FlyweightFlyweight

• ProxyProxy

Page 20: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 2020

Decorator PatternDecorator Pattern

Where have we seen this pattern before?

Page 21: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 2121

Behavioral PatternsBehavioral Patterns• Chain of responsibilityChain of responsibility

• CommandCommand

• InterpreterInterpreter

• IteratorIterator

• MediatorMediator

• MementoMemento

• ObserverObserver

• StateState

• StrategyStrategy

• SpecificationSpecification

• Template methodTemplate method

• VisitorVisitor

Page 22: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 2222

ObserverObserver

• publish/subscribe patternpublish/subscribe pattern

• Used in Java’s GUI event handlingUsed in Java’s GUI event handling

Component Event Listener

Event

generates handles

Page 23: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 2323

Architectural PatternsArchitectural Patterns• LayersLayers

• Presentation-abstraction-controlPresentation-abstraction-control

• Three-tierThree-tier

• PipelinePipeline

• Implicit invocationImplicit invocation

• Blackboard systemBlackboard system

• Peer-to-peerPeer-to-peer

• Service-oriented architectureService-oriented architecture

• Naked objectsNaked objects

• Model-View-ControllerModel-View-Controller

Page 24: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 2424

Model-View-Controller (MVC) Model-View-Controller (MVC) PatternPattern

Java GUI Example:•Model = javax.swing.table.TableModel•View = javax.swing.JTable•Controller = javax.swing.event.TableModelListener

Page 25: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 2525

Object-oriented Design Object-oriented Design DiscussionDiscussion• "Program to an 'interface', not an "Program to an 'interface', not an

'implementation'." (Gang of Four 1995:18)'implementation'." (Gang of Four 1995:18)

• Pros/Cons? Pros/Cons?

• Agree/Disagree?Agree/Disagree?

Page 26: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 2626

Object-oriented Design Object-oriented Design DiscussionDiscussion• "Favor 'object composition' over 'class "Favor 'object composition' over 'class

inheritance'." (Gang of Four 1995:20)inheritance'." (Gang of Four 1995:20)

• What is object composition?What is object composition?

• Pros/Cons?Pros/Cons?

Page 27: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 2727

Object-oriented Design Object-oriented Design DiscussionDiscussion• "Because inheritance exposes a subclass to "Because inheritance exposes a subclass to

details of its parent's implementation, it's details of its parent's implementation, it's often said that 'inheritance breaks often said that 'inheritance breaks encapsulation'". (Gang of Four 1995:19)encapsulation'". (Gang of Four 1995:19)

• Agree/Disagree?Agree/Disagree?

Page 28: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 2828

Java GUI ProgrammingJava GUI Programming

• Abstract Windows Toolkit (AWT)Abstract Windows Toolkit (AWT)

• SwingSwing

Page 29: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 2929

AWT ProgrammingAWT Programming

• Prior to Java 2 (version 1.2), all graphics Prior to Java 2 (version 1.2), all graphics programming was done with the programming was done with the Abstract Abstract Window Toolkit (AWT)Window Toolkit (AWT)

• AWT relies on AWT relies on peer entities to draw its to draw its graphics componentsgraphics componentse.g., an AWT window maps to a system peer e.g., an AWT window maps to a system peer

window (a AWT window maps to a Windows or window (a AWT window maps to a Windows or X-Windows window)X-Windows window)

• Operating system draws the peer entity Operating system draws the peer entity based on what is in the AWT entitybased on what is in the AWT entity

Page 30: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 3030

AWT ProgrammingAWT Programming

• Drawing peer entities is a very Drawing peer entities is a very slowslow process process• Java 2 introduced Java 2 introduced Swing, javax.swing• Swing still uses AWT framesSwing still uses AWT frames

directly draws on themdirectly draws on themoperating system does notoperating system does notMakes graphics process platform-independentMakes graphics process platform-independentImproves speedImproves speed

Page 31: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 3131

Swing and AWTSwing and AWT

• Swing does not completely replace AWTSwing does not completely replace AWT

• Using the Swing graphics programming Using the Swing graphics programming modelmodelspeeds things up speeds things up allows more efficiently writing graphics program allows more efficiently writing graphics program

code code

• We will write graphics code that uses Swing We will write graphics code that uses Swing

Page 32: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 3232

FramesFrames

• Most basic unit of graphics programmingMost basic unit of graphics programming

• A window that is not contained within A window that is not contained within another windowanother window or a or a top-level window

• An example of a An example of a containercontainer A A containercontainer is something that can contain other is something that can contain other

user interface componentsuser interface components

• JFrameJFrame Swing class implements a frame Swing class implements a frame

Page 33: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 3333

FramesFrames

• The most basic type of frame…The most basic type of frame…import javax.swing.*;public class SimpleFrameTest {

public static void main(String args[]) {SimpleFrame frame = new SimpleFrame(); frame.setVisible(true);

}}class SimpleFrame extends JFrame {

public SimpleFrame() {setSize(WIDTH, HEIGHT);

}public static final int WIDTH = 300;public static final int HEIGHT = 200;

}

Page 34: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 3434

Components & ContainersComponents & Containers

• ComponentsComponents Abstract classAbstract class Everything you see is a componentEverything you see is a component

• Superclass of ContainerSuperclass of Container Many methodsMany methods

• some deprecated: be carefulsome deprecated: be careful

• ContainerContainer Concrete implementation of ComponentConcrete implementation of Component Base class of many classesBase class of many classes Can add and remove components to containerCan add and remove components to container

Page 35: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 3535

Screen ResolutionScreen Resolution

• Since people use various screen Since people use various screen resolutions, how can a programmer resolutions, how can a programmer determine how big to make the frame?determine how big to make the frame?

Page 36: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 3636

Screen ResolutionScreen Resolution

• Since people use various screen Since people use various screen resolutions, how can a programmer resolutions, how can a programmer determine how big to make the frame?determine how big to make the frame? Determine the screen resolutionDetermine the screen resolution Obtain system-information, such as screen Obtain system-information, such as screen

resolution, using a resolution, using a ToolkitToolkit object object• Toolkit has a method Toolkit has a method getScreenSizegetScreenSize() that () that

returns the screen resolution as a returns the screen resolution as a DimensionDimension class objectclass object

Toolkit, Dimension: part of Toolkit, Dimension: part of java.awtjava.awt package package

Page 37: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 3737

Screen ResolutionScreen Resolution

• Dimension object holds a width and height Dimension object holds a width and height value, in pixelsvalue, in pixels public instance fieldspublic instance fields

Toolkit kit = Toolkit.getDefaultToolKit();Dimension screenSize = kit.getScreenSize();int screenWidth = screenSize.width;int screenHeight = screenSize.height;

Page 38: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 3838

Example: A Centered WindowExample: A Centered Window

class CenteredFrame extends JFrame {

public CenteredFrame() { Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screenSize = kit.getScreenSize(); int screenHeight = screenSize.height; int screenWidth = screenSize.width;

setSize(screenWidth / 2, screenHeight / 2); setLocation(screenWidth / 4, screenHeight / 4);

setTitle(“My Centered Frame”);}

}

Page 39: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 3939

Drawing on a FrameDrawing on a Frame

• JFrame contains JFrame contains ContentPane a Container object within the JFrame holds a Container object within the JFrame holds

components you add, placing them in the framecomponents you add, placing them in the frame the part of the frame that holds UI componentsthe part of the frame that holds UI components

Page 40: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 4040

Using a Content PaneUsing a Content Pane

• To put a component in a JFrameTo put a component in a JFrame get an object variable that refers to the content get an object variable that refers to the content

panepane make a componentmake a component add the component to the content paneadd the component to the content pane

Container contentPane = getContentPane();Component comp1 = . . .; // make a componentComponent comp2 = . . .; // make a componentcontentPane.add(comp1); // add comp1 to the c-panelcontentPane.add(comp2); // add comp2 to the c-panel

Page 41: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 4141

Adding a PanelAdding a Panel

• JPanelJPanel implements a panel implements a panel A panel has a surface on which you can drawA panel has a surface on which you can draw A panel is itself a A panel is itself a containercontainer

• can add components to a panelcan add components to a panel Useful in designing layoutsUseful in designing layouts

Page 42: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 4242

Drawing on a PanelDrawing on a Panel• To draw on a panel:To draw on a panel:

Define a new class that extends the JPanel classDefine a new class that extends the JPanel class Override the Override the paintComponentpaintComponent() method in derived class() method in derived class

• paintComponentpaintComponent() method takes one parameter() method takes one parameter an object of type an object of type GraphicsGraphics

• GraphicsGraphics object: a collection of settings for drawing object: a collection of settings for drawing images and text, such as colors and fontsimages and text, such as colors and fonts

• All drawing in Java must go through a Graphics All drawing in Java must go through a Graphics objectobject

Page 43: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 4343

Drawing on a PanelDrawing on a Panel

class MyPanel extends JPanel{

public void paintComponent(Graphics g){

// code for drawing goes here

}}

Page 44: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 4444

The paintComponent Method()The paintComponent Method()

• paintComponentpaintComponent() is called () is called automaticallyautomatically by by the system whenever the container needs the system whenever the container needs to be redrawn on the screento be redrawn on the screenDo not call this method yourselfDo not call this method yourselfIt will be called when it needs to beIt will be called when it needs to be

• If you need to force repainting of the If you need to force repainting of the screen, call the screen, call the repaintrepaint() method() methodcauses paintComponent() to be called for all causes paintComponent() to be called for all

needed components with appropriate Graphics needed components with appropriate Graphics objectsobjects

Page 45: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 4545

Drawing on a PanelDrawing on a Panel

• The paintComponent() method, which does The paintComponent() method, which does the drawing, takes a Graphics objectthe drawing, takes a Graphics object

• Measurements on a Graphics object is done Measurements on a Graphics object is done in pixels, as an offset from the top-left cornerin pixels, as an offset from the top-left cornerThe (0,0) coordinates represent the top-left The (0,0) coordinates represent the top-left

corner of the container on which you are drawingcorner of the container on which you are drawing

Page 46: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 4646

Drawing on a PanelDrawing on a Panel

• Displaying text is a special type of drawing, Displaying text is a special type of drawing, called called rendering textrendering text

• To render text on a panel, call To render text on a panel, call drawStringdrawString()()

class HelloWorldPanel extends JPanel{

public static final int MESSAGE_X = 75;public static final int MESSAGE_Y = 100;

public void paintComponent(Graphics g){

super.paintComponent(g);

g.drawString(“Hello World.”,MESSAGE_X, MESSAGE_Y);

}}

Page 47: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 4747

Drawing on a PanelDrawing on a Panel

• Notice we call the superclass (JPanel) Notice we call the superclass (JPanel) paintComponent() methodpaintComponent() method

• The JPanel class has its own idea on how to The JPanel class has its own idea on how to draw/paint the paneldraw/paint the panelFills in the background colorFills in the background color

• To make sure background color gets filled, To make sure background color gets filled, call the superclass paintComponent() call the superclass paintComponent() methodmethodEvery JPanel should color its backgroundEvery JPanel should color its background

Page 48: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 4848

Creating a Font ObjectCreating a Font Object

Font sansbold14 = new Font(“SansSerif”, Font.BOLD, 14);Font helvi12 = new Font(“Helvetica”, Font.ITALIC, 12);

•After a Font object has been created, you can change the font that the Graphics object uses by calling setFont()

• For example…For example…Font sansbold14 = new Font(“SansSerif”, Font.BOLD, 14);g.setFont(sansbold14);g.drawString(“Hello there in SansSerif.”, 75, 100);

Page 49: 1 Inner Classes, Software Design Patterns, Swing API James Atlas July 1, 2008.

July 1, 2008July 1, 2008 James Atlas - CISC370James Atlas - CISC370 4949

Example GUIExample GUI


Recommended