Java Programming: From the Ground Up Chapter 18 Graphics: AWT and Swing.

Post on 02-Jan-2016

228 views 3 download

Transcript of Java Programming: From the Ground Up Chapter 18 Graphics: AWT and Swing.

Java Programming:From the Ground Up

Chapter 18Graphics: AWT and Swing

Components and Containers

Java provides a hierarchy of classes that facilitates GUI

programming, Java’s Component hierarchy

Components and Containers

• At the top of the hierarchy is the (abstract) Component class.

• A component is an object that can be displayed on the screen.

• Buttons, text boxes, checkboxes and labels are all components.

• A window is also a component.

Components and Containers

• Every component, such as a button, a checkbox, a text box, or a window is an object belonging to some class that extends Component.

• The upper left corner of a container is designated as position (0, 0) and (x, y) is the point located x pixels to the right of and y pixels down from (0, 0).

Component methods

• void setSize (int width, int height)sets the size of a component so that its width is width pixels and its height is height pixels. This method can be used to resize a button or a window.

• void setLocation(int x, int y) places a component at position (x, y) of the container that holds it When a component is placed at position (x, y), the upper left-hand corner of the component is placed at (x, y). void setBounds(int x, int y, int width, int height)

• places a component at position (x, y) and resizes the component to the number of pixels specified by the parameters width and height.

Component methods

• void setEnabled(boolean enable) enables the component if the parameter, enable, is true; disables the component if enable is false. If a button is enabled, clicking the button usually triggers some program action.

• void setVisible(boolean x)hides the component if the parameter is false; displays the component if the parameter is true.

• void setName(String name)sets the name of the component. int getHeight()returns the height in pixels of a component.

• int getWidth()returns the width in pixels of a component.

Component methods

• int getX()returns the x-coordinate of the component, i.e., the x-coordinate of the upper left corner of the component.

• int getY() returns the y-coordinate of the component, i.e., the y-coordinate of the upper left corner of the component.

• String getName() returns the name of the component.

• boolean isEnabled()returns true if the component is enabled, false otherwise.

Component methods

• boolean isVisible()returns true if the component is visible when its container is visible, false otherwise. Note, that a visible component does

not display if its parent container is not also visible.

Container class

The Container class defines additional methods. The most important of these is

Component add( Component c),

which places a component, c, in a container and returns c.

Abstract Windows Toolkit and Swing

Java provides two packages that contain the classes for graphics programming:

• the original Abstract Windows Toolkit (AWT) and • the newer Swing package.

Abstract Windows Toolkit and Swing

• Swing does not replace AWT.• Swing uses many AWT classes. • Swing provides new user interface components (buttons,

textboxes, checkboxes, menus etc.) which are platform independent. The AWT classes are in java.awt

• The Swing classes reside in javax.swing.

AWT and Swing

AWT in java.awt Swing in javax.swing •Each component is mapped to a corresponding platform-dependent interface called a peer. •Platform specific and prone to platform specific bugs.

•Components may look different on different platforms. Components have the look of a particular platform.

•No platform dependent peers.

•Code written in Java.

•All components look the same, regardless of the platform

•Components are all prefixed with “J,” e.g., JButton, JCheckbox, JLabel

• Swing classes are all prefixed with uppercase J. For example JButton, JCheckBox, JWindow and JMenu are Swing classes that encapsulate buttons, checkboxes, windows, and menus.

• All Swing components except JFrame and JDialog extend JComponent

Windows and Frames

• Every GUI utilizes one or more windows.

• The Window class extends Container.

• A Java Window is a “window” without borders and a title bar.

• The Frame class, a member of AWT, extends Window.

• A Frame is-a Window that includes a title bar and border.

• JFrame is a Swing class that extends the AWT class Frame.

• A JFrame object is a container for other objects such as buttons, labels, text boxes, and checkboxes.

Windows and Frames

JFrame encapsulates what you normally think of as a “window,” and it is the primary container used in all our applications.

Constructors

Two JFrame constructors are:• JFrame()

creates a new JFrame that is initially invisible.

• JFrame(String title)creates a new JFrame with title, title, that is initially invisible. When the frame is visible, the title appears on the title bar of the frame.

JFrame Methods

• void setTitle(String title)sets the title of the frame to title.

• void setResizable(boolean x) If x is true, the frame can be resized by the user; if x is false the frame cannot be resized. By default, a frame is resizable.

• void setDefaultCloseOperation(int op)exits the application when the user closes the frame, provided that op is the JFrame constant EXIT_ON_CLOSE. If the close operation is not set with EXIT_ON_CLOSE, then when a user closes the application by clicking on the x in the upper right hand corner of the window, the window disappears but the process still runs in the background.

JFrame Methods

To add components to a frame use

• the add(Component c) method of and

• the setVisible(boolean x) method of Component to make a JFrame visible.

JFrame Methods

Problem Statement

Design a class that extends JFrame. Include two constructors. The default constructor sets the title to “I’ve been framed!” A one argument constructor accepts a String parameter, title. The frame should be positioned at (0,0) on the user screen. The dimensions of the frame should be 300 by 300 pixels.

The Application

The upper left corner of the screen has coordinates (0, 0). A call to setBounds (0, 0, 300, 300) places the upper left corner of the frame at screen position (0,0).

1. import javax.swing.*;2. public class MyFirstFrame extends JFrame3. {4. public MyFirstFrame ()

// creates a frame with title "I've been framed!"5. {6. super("I've been framed!");

// call the one-argument constructor of JFrame7. setBounds(0,0,300,300);

// placed at screen position (0,0); size 300 by 3008. }9. public MyFirstFrame (String title) // creates a frame with title title10. {11. super(title); // call the one-argument constructor of JFrame12. setBounds(0,0,300,300); // placed at (0,0); size 300 by 30013. }14. }

A test class that creates, displays, and closes a MyFirstFrame frame

15. import javax.swing.*;16. public class TestMyFirstFrame17. {18. public static void main(String[] args)19. {20. JFrame frame = new MyFirstFrame ("This is a test");21. frame.setVisible(true);22. frame.setResizable(false);23. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);24. }25. }

A frame in the upper left-hand corner of the

screen

Discussion

Line 21: JFrame frame = new MyFirstFrame ("This is a test");The reference frame is declared as a JFrame. Because

MyFirstFrame extends JFrame, upcasting is acceptable.

Line 22: frame.setVisible(true);By default, a frame is invisible; so the call setVisible(true) is

essential.

Line 23: frame.setResizable(false);The frame cannot be resized by the user. Notice that the

center button in the upper right hand corner of the frame has been disabled. The frame always remains 300 by 300.

How to center a frame

Place a frame of size 200 by 100 pixels in the center of the

screen.

If the screen size (resolution) is 800 by 600 then the upper right hand corner of the frame should be positioned at (x, y) such thatx = (800 – 200)/ 2 = 300 y = (600 – 100)/ 2 = 250

Centering a 200 by 100 frame

If the screen resolution is 1024 by 768 then a centered 200 by 100 frame should be positioned at:

x = (1024 – 200)/2 = 412y = (768 – 100)/ 2 = 334

To center a frame on a screen of any size, use methods of the AWT classes

• Toolkit

• Dimension classes

The Dimension class has two public fields, • int width and • Int height,

that hold the screen dimensions

The Toolkit class contains a method Dimension getScreenSize(),

that returns a Dimension object.

Use the Toolkit and Dimension classes to

obtain the screen size

Toolkit toolkit = Toolkit.getDefaultToolkit(); // a static method of the Toolkit class

Dimension dimensions = toolkit.getScreenSize(); // dimensions.width is the width of the screen

// dimensions.height is the height of the screen

Point class

• The Point class encapsulates a two dimensional point.

• The Point class has two public fields • int x and • int y

that denote the horizontal and vertical coordinates of a two dimensional point.

• The class has a two-argument constructor Point (int x, int y)

that sets the values of x and y.

A CenterFrame class

The class CenterFrame has a single static method

public static Point getPosition(int frameWidth, int frameHeight)

that, given the width and height of a frame, returns a Point that holds the coordinates, x and y, of the position where the frame should be placed so that it is centered on the screen.

A CenterFrame class

1. import java.awt.*;2. public class CenterFrame // a utility class3. {4. public static Point getPosition(int frameWidth, int frameHeight)5. {6. // frame size is width * height7. // returns a Point holding the coordinates of8. // the upper left-hand corner of the (centered) frame9. Toolkit toolkit = Toolkit.getDefaultToolkit();10. Dimension dimensions =toolkit.getScreenSize();11. int x = (dimensions.width - frameWidth)/2;

// x coordinate of upper left corner12. int y = (dimensions.height - frameHeight)/2;

// y coordinate of upper left corner13. return (new Point(x,y));

// return coordinates as a Point object14. }15. }

How to Add Components to a Frame

• To add components to a frame, Java provides layout managers.

• A layout manager is an object that arranges components in a container such as a frame. The layout manager classes implement the LayoutManager interface.

• Different layout managers arrange widgets differently.

• Three common layout managers are :• BorderLayout,• FlowLayout, and• GridLayout.

BorderLayout

• BorderLayout is the default layout manager for JFrame.

• The BorderLayout manager divides a frame into five areas: NORTH WEST SOUTH EAST CENTER

Constructors

• BorderLayout()

• BorderLayout(int horizontalgap, int verticalgap)where horizontalgap and verticalgap specify horizontal and

vertical space, in pixels, between components.

BorderLayout

• The method add(Component c, int region)

places a component into a container.

• The parameter, region, is specified by one of the constants• BorderLayout.NORTH,• BorderLayout.SOUTH,• BorderLayout.EAST, • BorderLayout.WEST, or• BorderLayout.CENTER.

• If no region is specified, a BorderLayout layout manager places a component in the center region. Only one component can be placed in a region and components are resized to fit the region.

BorderLayout

Problem Statement

Create a class, BorderLayoutFrame, that extends JFrame such that an object belonging to BorderLayoutFrame displays five buttons.

A button is a widget that displays some text or image and allows some action to occur when the button is “pressed” – i.e., when the mouse is clicked on the button.

BorderLayout

Arrange the five buttons in the frame using the default BorderLayout layout manager. The center button should display the famous “smiley face” image stored in smiley.jpg. The other four buttons should display the word smile in four languages: English, French (sourire), Italian (sorriso), and Spanish (sonrisa).

The size of the frame should be 300 by 300 and the frame should be positioned at (0,0). Include a main(...) method that instantiates the frame.

A Button

• A button is a member of the JButton class.

• Three constructors of JButton are:

• JButton(),creates a button with no text

• JButton(String text), text is text displayed on the button,

• JButton(new ImageIcon (String filename))displays an image on the button , where filename is the name of an image file, such as myPicture.jpg or yourPicture.gif.

The Application

1. import javax.swing.*;2. import java.awt.*;3. public class BorderLayoutFrame extends JFrame4. {5. public BorderLayoutFrame()6. {7. super("BorderLayout "); // call one-argument constructor of JFrame8. setBounds(0,0, 300,300); // position and size9. // add the center button that displays the image in "smiley.jpg"10. add(new JButton(new ImageIcon("smiley.jpg")),

BorderLayout.CENTER)11. // add four buttons to NORTH, SOUTH, EAST, and WEST12. add(new JButton("Smile"), BorderLayout.NORTH);13. add(new JButton("Sourire"),BorderLayout.SOUTH);14. add(new JButton("Sorriso"), BorderLayout.EAST);15. add(new JButton("Sonrisa"),BorderLayout.WEST);16. }17. public static void main(String[] args) // for display purposes18. {19. JFrame frame = new BorderLayoutFrame ();20. frame.setVisible(true);21. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);22. }23. }

Five JButtons, one displaying an ImageIcon, placed with the default layout manager,

BorderLayout

Discussion

• Each button fills its region.

• If the frame is expanded, so are the buttons.

• The frame can hold only five components, and components can be covered by other components.

.

Discussion

If the additional statement

add(new JButton( ":)" ),BorderLayout.CENTER);

is added to the constructor at line 16, the frame would appear as

FlowLayout

An object belonging to FlowLayout arranges components

horizontally in a container, left to right, row by row, in the

order in which they are added to the container.

Constructors

• FlowLayout()instantiates a FlowLayout layout manager object that center aligns components in a container.

• FlowLayout( int Alignment) instantiates a FlowLayout layout manager with the specified alignment: FlowLayout.LEFT, FlowLayout.CENTER, or FlowLayout.RIGHT, with integer values 0, 1, and 2 respectively.

• FlowLayout(int Alignment, int horizontalSpace, int verticalSpace) instantiates a FlowLayout layout manager with the specified alignment. Parameters horizontalSpace and verticalSpace specify horizontal and vertical space, in pixels, between components

setLayout

The JFrame method

setLayout(LayoutManager m);

sets the layout manager for a frame.

Example:

setLayout(new FlowLayout()) ;or

LayoutManager manager = new FlowLayoutManager();setLayout(manager);

changes the layout manager of a frame from the default BorderLayout to FlowLayouT.

Hangman

Problem StatementIn one version of the game Hangman, a program randomly

chooses a word from a list of 5000 words. A player attempts to determine the mystery word by guessing letters, one letter at a time. The player guesses a letter by clicking a button labeled with some letter. For example, if the mystery word is ELEPHANT and the player clicks the E button the computer displays

E*E* * * * *The player made a correct guess and sees all the Es that occur

in the secret word.

Create a class AlphabetFrame that extends JFrame. A frame belonging to AlphabetFrame is a container that holds 26 buttons labeled with the letters of the alphabet. Such a frame might be used as part of a GUI for a Hangman application.

Solution

1. import java.awt.*;2. import javax.swing.*;3. public class AlphabetButtons extends JFrame4. {5. public AlphabetButtons(int width, int height) 6. {7. super("Alphabet Buttons");8. setLayout(new FlowLayout()); // layout manager9. setBounds(0,0, width,height);10. for (int i = 0; i < 26; i++)11. {12. Character letter = (char)(i + 'A'); // needs an object reference13. JButton button = new JButton(letter.toString()); 14. add(button);15. }16. }

17. public static void main(String[] args)18. {19. JFrame frame = new AlphabetButtons(300,300);20. frame.setVisible(true);21. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);22. }23. }

Twenty-six buttons placed with FlowLayout

Discussion

• The buttons arranged by FlowLayout are not stretched or resized.

• The buttons are placed consecutively one after the other. When there is no more room in the first row, the second row begins, etc.

• Each row is centered in the frame, because the default

constructor FlowLayout() uses center alignment.

GridLayout

The GridLayout layout manager arranges the components of a frame in a grid of specified dimensions, left to right, top to bottom, row by row.

Constructors

• GridLayout(int rows, int columns)where rows and columns specify the number of rows and columns in the grid.

• GridLayout(int rows, int columns, int horizontalSpace, int verticalSpace)where rows and columns specify the number of rows and columns in the grid and horizontalSpace and verticalSpace are the horizontal and vertical gaps between components.

• GridLayout()creates a grid with a single row and a column for each component.

Buttons and GridLayout

Problem Statement

Place 26 “alphabet buttons” in a frame using GridLayout. The

grid should have 6 rows and 5 columns

Buttons and GridLayout

1. import java.awt.*;2. import javax.swing.*;3. import java.util.*;4. public class GridAlphabetButtons extends JFrame5. {6. public GridAlphabetButtons (int width, int height) 7. { // width and height are frame dimensions8. super("Grid Layout Alphabet Buttons");9. setLayout(new GridLayout(6, 5)); // 6 rows; 5 columns10. setBounds(0,0, width,height);11. for (int i = 0; i < 26; i++)12. {13. Character alphabet = (char)(i + 'A');14. JButton button = new JButton(alphabet.toString());15. add(button);16. }17. }18. public static void main(String[] args)19. {20. JFrame frame = new GridAlphabetButtons (300,300);21. frame.setVisible(true);22. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);23. }24. }

A frame created with GridLayout

How to place components in a frame without a layout manager

By default, a frame uses the BorderLayout layout manager. To disable the default layout manager and place components in a frame without any assistance,

• set the layout manager of the frame to null, using setLayout(null) and

• use screen coordinates to place components

No Layout Manager

Problem Statement

Place three buttons, each of size 50 by 50, in a frame of size 300 by 300 such that:

• the first button is placed at position (30,30),• the second button is placed at (220,30), and• the third button is placed at (125,125).

Solution

1. import javax.swing.*;2. import java.awt.*;3. public class NoLayoutManager extends JFrame4. {5. public NoLayoutManager()6. {7. super("No Layout manager");8. setLayout(null); // no layout manager9. setBounds(0,0, 300,300); // for the frame

10. // create the three buttons11. JButton picture = new JButton( new ImageIcon("smiley.jpg"));12. JButton smile = new JButton (":-)");13. JButton frown = new JButton (":-(");

14. // set the position and size of each button15. picture.setBounds(125,125,50,50);16. smile.setBounds(30,30, 50,50);17. frown.setBounds(220,30,50,50);

Solution

18. // add each button to the frame19. add(picture);20. add(smile);21. add(frown);

22. setResizable

23. public static void main(String[] args)24. {25. JFrame frame = new NoLayoutManager();26. frame.setVisible(true);27. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);28. }29. }

A frame created without a layout manager

Panels

• Most Swing applications do not place components directly in a frame. Instead, components are grouped together and placed in panels.

• A panel is an invisible container used for arranging and organizing components.

• A panel can have a layout manager. Components are placed in panels and the panels are subsequently added to a frame.

• Swing’s JPanel class extends JComponent.

• FlowLayout is the default layout manager for JPanel.

Constructors

• JPanel()instantiates a JPanel object with FlowLayout as the default layout manager.

• JPanel (LayoutManager layoutManager)instantiates a JPanel object with the specified layout

manager.

A Game Board Using Panels

The game How Good Is Your Memory? (also known as Concentration or Memory) utilizes a frame with twenty numbered buttons. Each button hides a picture. There are ten different pairs of identical pictures. For example, there may be a smiley face hidden by buttons 6 and 19 and question marks hidden by buttons 2 and 16.

A Game Board Using Panels

The game is played by two people. Players alternately click two buttons and the buttons’ hidden pictures are displayed. If the pictures match, the player gets a point, the pictures remain visible, and that player chooses again. If the pictures do not match, they are hidden again, and the other player chooses. When all matches have been revealed, the player with the greater number of points wins.

A Game Board Using Panels

The board ( frame) shows each player’s score. On the bottom of the frame are four buttons.

• The Open button displays the pictures behind the last unmatched pair.

• The Close button hides the last two unmatched pictures.

• The Reset button initializes a game.

• The Quit button exits the program.

A Concentration game in progress

Concentration game

Problem Statement

Create a frame that can be used as an interface for How Good Is Your Memory. Use a label to display each the player and the player’s score.

JLabel

• A label is a component that displays text and/or an image. In contrast to a button, which can be “clicked” and utilized for input, a label is a component that is used primarily to display a string or an image.

• The Swing class that encapsulates a label is JLabel.

• One JLabel constructor is JLabel(String text), where text is the string displayed on the label

Solution

The program• creates twenty numbered buttons,

• creates four labeled buttons: Close, Open, Reset, and Quit,

• creates two labels, player1 and score1, one to hold the text “Player 1” and the other to hold 0, the initial score for Player 1,

• creates two labels, player2 and score2, one to hold the text “Player 2” and the other to hold 0, the initial score for Player 2,

• creates a panel and places the numerical buttons in that panel,

Solution

• creates a second panel and places the Close, Open, Reset, and Quit buttons in the panel,

• creates a third panel and places the player1 and score1 labels in the panel,

• creates a fourth panel and places the player2 and score2 labels in the panel, and

• places the panels in a frame.

Solution

1. import java.awt.*;2. import javax.swing.*;3. public class HowGoodIsYourMemory extends JFrame4. {5. public HowGoodIsYourMemory()6. {7. super("Let's Play How Good Is Your Memory");8. setBounds(0,0,600,400);

9. // Create an array of 20 buttons10. JButton[] button = new JButton[20];11. for( int i = 0; i <20; i++)12. button[i] = new JButton(i+" ");

13. // Create the four bottom row buttons14. JButton buttonClose = new JButton("Close");15. JButton buttonReset = new JButton("Reset");16. JButton buttonOpen = new JButton("Open");17. JButton buttonQuit = new JButton("Quit");

Solution

18. // Labels for Player 1 and Player 1 score19. JLabel player1 = new JLabel(" Player 1");20. JLabel score1 = new JLabel(" 0 ");

21. // Labels for Player 2 and Player 2 score22. JLabel player2 = new JLabel("Player 2 ");23. JLabel score2 = new JLabel(" 0 ");

24. // Create a panel for the array of numerical buttons25. // using GridLayout, and26. // place the buttons in the panel27. JPanel numberPanel = new JPanel(new GridLayout(4,5,10,10));28. for (int i = 0; i < 20; i++)29. numberPanel.add(button[i]);

Solution

30. // Create a panel of bottom buttons31. // using FlowLayout, and32. // place the buttons in the panel33. JPanel bottomPanel = new JPanel(new FlowLayout());34. bottomPanel.add(buttonClose);35. bottomPanel.add(buttonOpen);36. bottomPanel.add(buttonReset);37. bottomPanel.add(buttonQuit); 38. // Create a panel for the Player 1 labels39. // using FlowLayout40. JPanel player1Panel = new JPanel(new FlowLayout());41. player1Panel.add(player1);42. player1Panel.add(score1);

Solution

43. // Create a panel for the Player 2 label44. // using FlowLayout45. JPanel player2Panel = new JPanel(new FlowLayout());46. player2Panel.add(player2);47. player2Panel.add(score2);48. // Place all panels in the frame

// using the default BorderLayout layout manager49. add(bottomPanel, BorderLayout.SOUTH);50. add(numberPanel, BorderLayout.CENTER);51. add(player1Panel, BorderLayout.WEST);52. add(player2Panel, BorderLayout.EAST);

53. setResizable(false); // cannot resize the game54. setVisible(true);55. }

Solution

56. public static void main(String[] args)57. {58. JFrame game = new HowGoodIsYourMemory();59. game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);60. }61. }

Output

Some Basic Graphics

Each time that a frame is moved or changed, it must be “repainted” or redrawn on the screen. Java provides two methods, paint(...) and paintComponent(...) that not only redraw a component that has been moved, resized, or changed.

The paint() and paintComponent() Methods

• The Component class defines a method, paint(...), that draws or renders a component on the screen.

• When a frame is first displayed, the system calls paint(...), and paint(...) does the drawing.

• JComponent includes a method, paintComponent(...), which draws Swing components such as JButtons, JLabels, or JPanels.

• When a user resizes, moves, covers, or uncovers a component, the paint(...) or paintComponent(...) method redraws the component.

The paint() and paintComponent() Methods

• The two methods are declared as:• void paint(Graphics g);• void paintComponent(Graphics g);

• Each method accepts a single parameter g, a reference to a Graphics object. The Graphics object encapsulates information about a component and includes methods that facilitate drawing on a component. Graphics is an abstract class in java.awt.

• Like the garbage collector, paint(...) and paintComponent(...) work behind the scenes. An application does not explicitly invoke paint(...) or paintComponent(...). That’s done by the system

The Graphics Context

The Graphics parameter, g, supplies paint(...) and paintComponent(...) with information about how to draw a particular component. For example, certain information about the font, drawing color, and location are encapsulated in g.

A component’s Graphics object is also called the component’s graphics context.

Graphics

Every component that can be drawn on the screen has an associated Graphics object that encapsulates information about the component such as color and font. When a component is drawn, the JVM automatically retrieves and passes the component’s Graphic object, g, to paint(...) and paintComponent(...). The Graphics object g is not explicitly instantiated using a constructor.

The Graphics Context

• The paint(...) and paintComponent(...) methods use the information encapsulated in the Graphics parameter g to render a component.

• For example, if a JFrame object, myFrame, is resized then myFrame must be repainted. Consequently, the system automatically invokes myFrame.paint(g), where g is the graphics context associated with myFrame. This parameter g supplies information to paint(...) so that paint(...) knows how to draw myFrame.

Some Graphics methods

• void drawString(String message, int x, int y) draws message on the component, starting at position (x, y).

• void setColor(Color c)sets the color of a component. Color is a class that extends Object.

• void setFont(Font f)sets the font to be used when drawing characters on a component. Font is a class that extends Object.

• void drawImage(Image img, int x, int y, ImageObserver observer)draws an image on the component such that img is an image file (e.g., .jpg or .gif), x and y designate the position of the image, and observer is the object on which the image is drawn - usually this.

Color

The Color class is used to encapsulate a color. One constructor for the class is

Color(int red, int green, int blue)

where parameters red, green and blue range from 0 to 255

inclusive.

Color

The colors red, green and blue form the basis for every possible color. The parameters indicate how much of each color goes into the mix. The higher the parameter value, the greater the amount of the corresponding color in the red-green-blue mix.

For example,Color color = new Color ( 255, 0, 0)

// full red, no green,no blue.

Color color = new Color (0,0,0) // no red, no green, no blue; that’s white.

Color color = new Color( 150, 0, 150) // an equal mix: red and blue; that’s purple.

Color color = new Color(255,255,255) // this is black.

Color

• The Color class also defines a number of class constants:

RED, WHITE, BLUE, GREEN, YELLOW, BLACK, CYAN, MAGENTA, PINK, ORANGE, GRAY, LIGHTGRAY, and DARKGRAY.

• These colors are accessed with the class name, e.g.,

Color.RED.

Color

Every component implements two methods:

• setBackground(Color c)sets the background color of a component. The parameter can be null, in which case the background color is the background color of the parent.

• setForeground(Color c)sets the foreground color of a component. The foreground color is the color used for drawing and displaying text.

The Font Class

• An object belonging to Font encapsulates the properties of the font used to display text.

• The class constructor is

Font(String name, int style, int size)

where • name is the name of a standard font such as Courier or Arial,• style is a combination of Font class constants:

Font.PLAIN, Font.BOLD, Font.ITALIC with values 1, 2, and 3 respectivelysuch as• size is the point size of a character.

The Font Class

To create a 12 point Courier font that is both bold and italic, use

Font font = new Font(“Courier”, Font.BOLD+Font.ITALIC, 12);

Since Font.BOLD + Font.ITALIC = 1 + 2 = 3, the same Fontobject can be also instantiated as

Font font = new Font(“Courier”, 3, 12);

Font Methods

• public String getName()returns the name of the font.

• public boolean isPlain()returns true if the style is Font.PLAIN.

• public boolean isItalic()returns true if the style is Font.ITALIC.

• public boolean isBold()returns true if the style is Font.BOLD.

Font Methods

• public int getStyle()returns 0 if the style is PLAIN.

returns 1 if the style is BOLD.returns 2 if the style is ITALIC.returns 3 if the style is BOLD+ ITALIC.

• public int getSize()

returns the font size

“Painting” on Panels

Custom “painting” is usually done on a panel.

To paint or draw on a panel,

• extend the JPanel class, and

• override the paintComponent(Graphics g) method so that the redefined paintComponent(...) renders the panel with some customized image or text.

“Painting” on Panels

Problem Statement:

Create a panel with a red background that displays the familiar Star Wars quotation “May the Force be with you.” The quote should be drawn in yellow, with point size 16, using the exotic Flat Brush font. Position the quote at (50,50). Include

a main(...) method that places the panel in frame.

“Painting” on Panels

Solution

The application

• defines the class StarPanel, which extends JPanel,

• overrides JPanel’s paintComponent(...) method so that paintComponent(...) paints the message “May the Force be with you” on a StarPanel object.

The Graphics object g, which is passed to paintComponent(...), invokes the setColor(...) and setFont(...) methods.

Solution1. import javax.swing.*;2. import java.awt.*;3. public class StarPanel extends JPanel4. {5. public void paintComponent(Graphics g)6. {7. super.paintComponent(g);

// Call the paintComponent method of the parent8. g.setColor(Color.YELLOW); // Use yellow for drawing9. Font font = new Font("Flat Brush", Font.BOLD, 24);10. g.setFont(font); // Uses the Flat Brush font 11. setBackground(Color.red);12. g.drawString("May the Force be with you", 50,50);13. }14. public static void main(String [] args)15. {16. JFrame frame = new JFrame("Star Wars Quotation");17. frame.setBounds(0,0,400,200);18. StarPanel panel = new StarPanel();19. frame.add(panel);20. frame.setVisible(true);21. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);22. }23. }

Drawing Shapes

The Graphics class also defines a number of methods that facilitate drawing various shapes on a panel. Among the most commonly used methods are:

• void drawLine(int startx, int starty, int endx, int endy)draws a line segment from point (startx, starty) to point (endx, endy).

• void drawRect(int x, int y, int width, int height)draws a rectangle with upper left-hand corner positioned at (x,y). The width and height of the rectangle are width and height respectively.

• void fillRect(int x, int y, int width, int height)draws and fills the specified rectangle.

void drawOval(int x, int y , int width, int height)draws an ellipse that fits within the boundary of the rectangle specified by the parameters x, y, width, and height. If width

and height are equal, the figure is a circle.

• void fillOval(int x, int y, int width, int height)draws and fills the specified oval.

• void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)draws an arc using the oval inscribed in the rectangle specified by parameters x, y ,width and height. The arc begins at startAngle and spans arcAngle. Angles are given in degrees

The arc drawn by the drawArc() method.

Problem StatementDesign an application that draws the “megaphone of

circles” in a frame."

Solution

The application defines two classes:

• CirclesPanel extends JPanel and overrides paintComponent(Graphics g), and

• CircleFrame extends JFrame, instantiates CirclePanel, and adds a CirclesPanel object to the frame.

Solution

1. import javax.swing.*;2. import java.awt.*;3. public class CirclePanel extends JPanel

4. // Displays 39 circles. //The bounding rectangle for each circle is positioned at (10,10).

5. // The circles range in radius 10 to 400 pixels.6. // A frame size of at least 440 by 440 is recommended. 7. {8. public void paintComponent(Graphics g)9. {10. super.paintComponent(g);11. g.setColor(Color.black);12. setBackground(Color.white);13. for (int radius = 400; radius >0; radius-=10)

// draw 39 circles of decreasing radius14. g.drawOval(10,10,radius,radius);15. }16. }

Solution

17. public class CircleFrame extends JFrame18. {19. public CircleFrame(String title)20. {21. super(title);22. setBounds(0,0, 450, 450);23. JPanel circles = new CirclePanel();24. add(circles);25. setVisible(true);26. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);27. }28. public static void main(String[] args)29. {30. JFrame frame = new CircleFrame("Circles");31. 32. }33. }

The getGraphics() Method

Each displayable component has an associated Graphics context. This object is automatically created and passed to paint(Graphics g) or paintComponent(Graphics g). The Graphics context of a component can be obtained , not by a constructor, but via the method

Graphics getGraphics().

The getGraphics() Method

The following small class uses the getGraphics() method to obtain the Graphics context of a JFrame and set the drawing

color to red.

The getGraphics() Method

1. import javax.swing.*;2. import java.awt.*;3. public class GetGraphicsDemo extends JFrame4. {5. public static void main(String[] args)6. {7. GetGraphicsDemo frame = new GetGraphicsDemo();8. Graphics g;

9. g = frame.getGraphics();10. System.out.println(g);

11. frame.setVisible(true);12. g = frame.getGraphics();13. g.setColor(Color.RED);14. System.out.println(g.getColor());15. }16. }

Output

The output of this small program is

nulljava.awt.Color[r=255,g=0,b=0]

Before the frame is made visible, the call

frame.getGraphics() (line 9)returns null.

When the frame is made visible (line 11), the method returns the Graphics object associated with the displayable frame.

On line 13, the Graphics color is set to red, and the statement on line 14 prints the RGB version of red (i.e., r = 255, g = 0, b = 0).

Displaying an Image

An icon is a small picture that can be displayed on a component Java’s Icon interface declares the following methods for working with icons:

• int getIconHeight(),• int getIconWidth(), and• void paintIcon(Component c, Graphics g, int x, int y),

where (x,y) denote a position in component c.•

The ImageIcon class, found in Swing, implements the Icon interface.

The constructor

ImageIcon(String filename)

creates an icon from the specified image file.

Display Image

Problem Statement:

Display the image stored in the file eniac.gif in a frame

Solution

The application implements two classes. • PicturePanel extends JPanel.

The constructor accepts the name of an image file. PicturePanel overrides paintComponent(...) so that paintComponent(...) instantiates ImageIcon, and paints the image on the panel.

• ShowPicture instantiates a JFrame and a PicturePanel. The panel is added to the frame.

Solution

1. import java.awt.*;2. import javax.swing.*;3. public class PicturePanel extends JPanel4. {5. private String image; // a filename6. public PicturePanel(String filename)7. {8. image = filename;9. }10. public void paintComponent(Graphics g)11. {12. super.paintComponent(g);13. ImageIcon picture = new ImageIcon(image);14. picture.paintIcon(this, g, 0,0);

// this means "this panel"15. }16. }

17. import javax.swing.*;18. public class ShowPicture extends JFrame19. {20. public ShowPicture()21. {22. super("Two women programming the Eniac ");23. setBounds(0,0,650,450);24. PicturePanel picPanel = new PicturePanel("eniac.gif");25. add(picPanel);26. setVisible(true);27. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);28. }29. public static void main(String[] args)30. {31. JFrame frame = new ShowPicture();32. }33. }

Programming B.J.– Before Java

The repaint() method

A program does not invoke paint(...) or paintComponent(...) to redisplay a component, but another method of the Component class:

void repaint().

The repaint() method, in turn, calls paint(... ).

Solution

• The Message class extends JPanel and overrides paintComponent(...) so that a new version of paintComponent(…) paints a string on the panel.

• The FrameWithAMessage class, which demonstrates Message, – interactively prompts a user for a message (a string),– interactively, reads the message using the Scanner

method, next(),– instantiates a frame and a Message panel,– adds the panel to the frame,– paints the user’s message on the panel,– prompts for a second message, and– repaints the panel so that the new message is displayed.

Solution

1. import javax.swing.*;2. import java.awt.*;3. public class Message extends JPanel4. {5. String message;6. public Message()7. {8. super(); // call the default constructor of JPanel9. message = "";10. setBackground(Color.WHITE);11. }12. public void paintComponent(Graphics g)

// override paintComponent(…) of JPanel13. {14. super.paintComponent(g);

// first call paintComponent(...) of JPanel15. Font font = new Font("ARIAL",Font.BOLD,14);16. g.setFont(font);17. g.drawString (message, 30, 30); // display the message18. }19. public void setMessage(String msg) // set the value of message20. {21. message = msg;22. }23. }

Solution

24. import java.util.*; // java.util.* is needed for Scanner 25. import javax.swing.*; // java.awt is not necessary for this class26. public class FrameWithAMessage27. {28. public static void main(String[] args)29. {30. Scanner input = new Scanner(System.in);31. System.out.print("Enter Greeting: ");32. String message = input.next();33. JFrame frame = new JFrame(); // create a frame34. frame.setBounds(0,0,200,200);35. Message panel = new Message(); // create a panel36. panel.setMessage(message); 37. frame.add(panel); // add the panel to the frame38. frame.setVisible(true); 39. System.out.print("Enter Greeting: ");40. message = input.next(); // get a new message41. panel.setMessage(message);42. panel.repaint(); // repaint the panel with the new message43. }44. }

Output following lines 38 and 42