Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming: From the Ground Up

Similar presentations


Presentation on theme: "Java Programming: From the Ground Up"— Presentation transcript:

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

2 Components and Containers
Java provides a hierarchy of classes that facilitates GUI programming, Java’s Component hierarchy

3 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.

4 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).

5 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.

6 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.

7 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.

8 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.

9 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.

10 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.

11 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.

12 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

13 Swing classes are all prefixed with uppercase J
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

14 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.

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

16 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.

17 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.

18 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.

19 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.

20 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). import javax.swing.*; public class MyFirstFrame extends JFrame { public MyFirstFrame () // creates a frame with title "I've been framed!" super("I've been framed!"); // call the one-argument constructor of JFrame setBounds(0,0,300,300); // placed at screen position (0,0); size 300 by 300 } public MyFirstFrame (String title) // creates a frame with title title super(title); // call the one-argument constructor of JFrame setBounds(0,0,300,300); // placed at (0,0); size 300 by 300

21 A test class that creates, displays, and closes a MyFirstFrame frame
import javax.swing.*; public class TestMyFirstFrame { public static void main(String[] args) JFrame frame = new MyFirstFrame ("This is a test"); frame.setVisible(true); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

22 A frame in the upper left-hand corner of the screen

23 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.

24 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 that x = (800 – 200)/ 2 = 300 y = (600 – 100)/ 2 = 250

25 Centering a 200 by 100 frame

26 If the screen resolution is 1024 by 768 then a centered 200 by 100 frame should be positioned at:
x = (1024 – 200)/2 = 412 y = (768 – 100)/ 2 = 334

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

28 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.

29 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

30 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.

31 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.

32 A CenterFrame class import java.awt.*;
public class CenterFrame // a utility class { public static Point getPosition(int frameWidth, int frameHeight) // frame size is width * height // returns a Point holding the coordinates of // the upper left-hand corner of the (centered) frame Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension dimensions =toolkit.getScreenSize(); int x = (dimensions.width - frameWidth)/2; // x coordinate of upper left corner int y = (dimensions.height - frameHeight)/2; // y coordinate of upper left corner return (new Point(x,y)); // return coordinates as a Point object }

33 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.

34 BorderLayout BorderLayout is the default layout manager for JFrame.
The BorderLayout manager divides a frame into five areas: NORTH WEST SOUTH EAST CENTER

35 Constructors BorderLayout()
BorderLayout(int horizontalgap, int verticalgap) where horizontalgap and verticalgap specify horizontal and vertical space, in pixels, between components.

36 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.

37 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.

38 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.

39 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.

40 The Application import javax.swing.*; import java.awt.*;
public class BorderLayoutFrame extends JFrame { public BorderLayoutFrame() super("BorderLayout "); // call one-argument constructor of JFrame setBounds(0,0, 300,300); // position and size // add the center button that displays the image in "smiley.jpg" add(new JButton(new ImageIcon("smiley.jpg")), BorderLayout.CENTER) // add four buttons to NORTH, SOUTH, EAST, and WEST add(new JButton("Smile"), BorderLayout.NORTH); add(new JButton("Sourire"),BorderLayout.SOUTH); add(new JButton("Sorriso"), BorderLayout.EAST); add(new JButton("Sonrisa"),BorderLayout.WEST); } public static void main(String[] args) // for display purposes JFrame frame = new BorderLayoutFrame (); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

42 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. .

43 Discussion If the additional statement
add(new JButton( ":)" ),BorderLayout.CENTER); is added to the constructor at line 16, the frame would appear as

44 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.

45 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

46 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.

47 Hangman Problem Statement
In 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.

48 Solution import java.awt.*; import javax.swing.*;
public class AlphabetButtons extends JFrame { public AlphabetButtons(int width, int height) super("Alphabet Buttons"); setLayout(new FlowLayout()); // layout manager setBounds(0,0, width,height); for (int i = 0; i < 26; i++) Character letter = (char)(i + 'A'); // needs an object reference JButton button = new JButton(letter.toString()); add(button); } public static void main(String[] args) JFrame frame = new AlphabetButtons(300,300); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

49 Twenty-six buttons placed with FlowLayout

50 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.

51 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.

52 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.

53 Buttons and GridLayout
Problem Statement Place 26 “alphabet buttons” in a frame using GridLayout. The grid should have 6 rows and 5 columns

54 Buttons and GridLayout
import java.awt.*; import javax.swing.*; import java.util.*; public class GridAlphabetButtons extends JFrame { public GridAlphabetButtons (int width, int height) { // width and height are frame dimensions super("Grid Layout Alphabet Buttons"); setLayout(new GridLayout(6, 5)); // 6 rows; 5 columns setBounds(0,0, width,height); for (int i = 0; i < 26; i++) Character alphabet = (char)(i + 'A'); JButton button = new JButton(alphabet.toString()); add(button); } public static void main(String[] args) JFrame frame = new GridAlphabetButtons (300,300); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

55 A frame created with GridLayout

56 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

57 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).

58 Solution import javax.swing.*; import java.awt.*;
public class NoLayoutManager extends JFrame { public NoLayoutManager() super("No Layout manager"); setLayout(null); // no layout manager setBounds(0,0, 300,300); // for the frame // create the three buttons JButton picture = new JButton( new ImageIcon("smiley.jpg")); JButton smile = new JButton (":-)"); JButton frown = new JButton (":-("); // set the position and size of each button picture.setBounds(125,125,50,50); smile.setBounds(30,30, 50,50); frown.setBounds(220,30,50,50);

59 Solution // add each button to the frame add(picture); add(smile);
add(frown); setResizable public static void main(String[] args) { JFrame frame = new NoLayoutManager(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

60 A frame created without a layout manager

61 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.

62 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.

63 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.

64 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.

65 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.

66 A Concentration game in progress

67 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.

68 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

69 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,

70 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.

71 Solution import java.awt.*; import javax.swing.*;
public class HowGoodIsYourMemory extends JFrame { public HowGoodIsYourMemory() super("Let's Play How Good Is Your Memory"); setBounds(0,0,600,400); // Create an array of 20 buttons JButton[] button = new JButton[20]; for( int i = 0; i <20; i++) button[i] = new JButton(i+" "); // Create the four bottom row buttons JButton buttonClose = new JButton("Close"); JButton buttonReset = new JButton("Reset"); JButton buttonOpen = new JButton("Open"); JButton buttonQuit = new JButton("Quit");

72 Solution // Labels for Player 1 and Player 1 score
JLabel player1 = new JLabel(" Player 1"); JLabel score1 = new JLabel(" "); // Labels for Player 2 and Player 2 score JLabel player2 = new JLabel("Player 2 "); JLabel score2 = new JLabel(" "); // Create a panel for the array of numerical buttons // using GridLayout, and // place the buttons in the panel JPanel numberPanel = new JPanel(new GridLayout(4,5,10,10)); for (int i = 0; i < 20; i++) numberPanel.add(button[i]);

73 Solution // Create a panel of bottom buttons // using FlowLayout, and
// place the buttons in the panel JPanel bottomPanel = new JPanel(new FlowLayout()); bottomPanel.add(buttonClose); bottomPanel.add(buttonOpen); bottomPanel.add(buttonReset); bottomPanel.add(buttonQuit); // Create a panel for the Player 1 labels // using FlowLayout JPanel player1Panel = new JPanel(new FlowLayout()); player1Panel.add(player1); player1Panel.add(score1);

74 Solution // Create a panel for the Player 2 label // using FlowLayout
JPanel player2Panel = new JPanel(new FlowLayout()); player2Panel.add(player2); player2Panel.add(score2); // Place all panels in the frame // using the default BorderLayout layout manager add(bottomPanel, BorderLayout.SOUTH); add(numberPanel, BorderLayout.CENTER); add(player1Panel, BorderLayout.WEST); add(player2Panel, BorderLayout.EAST); setResizable(false); // cannot resize the game setVisible(true); }

75 Solution public static void main(String[] args) {
JFrame game = new HowGoodIsYourMemory(); game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

76 Output

77 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.

78 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.

79 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

80 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.

81 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.

82 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.

83 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.

84 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.

85 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.

86 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.

87 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.

88 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.

89 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 = = 3, the same Font object can be also instantiated as Font font = new Font(“Courier”, 3, 12);

90 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.

91 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

92 “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.

93 “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.

94 “Painting” on Panels

95 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.

96 Solution import javax.swing.*; import java.awt.*;
public class StarPanel extends JPanel { public void paintComponent(Graphics g) super.paintComponent(g); // Call the paintComponent method of the parent g.setColor(Color.YELLOW); // Use yellow for drawing Font font = new Font("Flat Brush", Font.BOLD, 24); g.setFont(font); // Uses the Flat Brush font setBackground(Color.red); g.drawString("May the Force be with you", 50,50); } public static void main(String [] args) JFrame frame = new JFrame("Star Wars Quotation"); frame.setBounds(0,0,400,200); StarPanel panel = new StarPanel(); frame.add(panel); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

97 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.

98 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.

99 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

100 The arc drawn by the drawArc() method.

101 Problem Statement Design an application that draws the “megaphone of circles” in a frame."

102 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.

103 Solution import javax.swing.*; import java.awt.*;
public class CirclePanel extends JPanel // Displays 39 circles //The bounding rectangle for each circle is positioned at (10,10). // The circles range in radius 10 to 400 pixels. // A frame size of at least 440 by 440 is recommended. { public void paintComponent(Graphics g) super.paintComponent(g); g.setColor(Color.black); setBackground(Color.white); for (int radius = 400; radius >0; radius-=10) // draw 39 circles of decreasing radius g.drawOval(10,10,radius,radius); }

104 Solution public class CircleFrame extends JFrame {
public CircleFrame(String title) super(title); setBounds(0,0, 450, 450); JPanel circles = new CirclePanel(); add(circles); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) JFrame frame = new CircleFrame("Circles");

105 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().

106 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.

107 The getGraphics() Method
import javax.swing.*; import java.awt.*; public class GetGraphicsDemo extends JFrame { public static void main(String[] args) GetGraphicsDemo frame = new GetGraphicsDemo(); Graphics g; g = frame.getGraphics(); System.out.println(g); frame.setVisible(true); g.setColor(Color.RED); System.out.println(g.getColor()); }

108 Output The output of this small program is null
java.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).

109 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.

110 Display Image Problem Statement:
Display the image stored in the file eniac.gif in a frame

111 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.

112 Solution import java.awt.*; import javax.swing.*;
public class PicturePanel extends JPanel { private String image; // a filename public PicturePanel(String filename) image = filename; } public void paintComponent(Graphics g) super.paintComponent(g); ImageIcon picture = new ImageIcon(image); picture.paintIcon(this, g, 0,0); // this means "this panel"

113 import javax.swing.*; public class ShowPicture extends JFrame { public ShowPicture() super("Two women programming the Eniac "); setBounds(0,0,650,450); PicturePanel picPanel = new PicturePanel("eniac.gif"); add(picPanel); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) JFrame frame = new ShowPicture();

114 Programming B.J.– Before Java

115 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(... ).

116 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.

117 Solution import javax.swing.*; import java.awt.*;
public class Message extends JPanel { String message; public Message() super(); // call the default constructor of JPanel message = ""; setBackground(Color.WHITE); } public void paintComponent(Graphics g) // override paintComponent(…) of JPanel super.paintComponent(g); // first call paintComponent(...) of JPanel Font font = new Font("ARIAL",Font.BOLD,14); g.setFont(font); g.drawString (message, 30, 30); // display the message public void setMessage(String msg) // set the value of message message = msg;

118 Solution import java.util.*; // java.util.* is needed for Scanner
import javax.swing.*; // java.awt is not necessary for this class public class FrameWithAMessage { public static void main(String[] args) Scanner input = new Scanner(System.in); System.out.print("Enter Greeting: "); String message = input.next(); JFrame frame = new JFrame(); // create a frame frame.setBounds(0,0,200,200); Message panel = new Message(); // create a panel panel.setMessage(message); frame.add(panel); // add the panel to the frame frame.setVisible(true); message = input.next(); // get a new message panel.repaint(); // repaint the panel with the new message }

119 Output following lines 38 and 42


Download ppt "Java Programming: From the Ground Up"

Similar presentations


Ads by Google