LISTING 4.7. //****************************************

Added on - 16 Sep 2019

  • 5

    pages

  • 1704

    words

  • 66

    views

  • 0

    downloads

Showing pages 2 of 5
LISTING 4.7//********************************************************************// Splat.java Author: Lewis/Loftus//// Demonstrates the use of graphical objects.//********************************************************************import javax.swing.*;import java.awt.*;public class Splat{//-----------------------------------------------------------------// Presents a collection of circles.//-----------------------------------------------------------------public static void main(String[] args){JFrame frame = new JFrame("Splat");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.getContentPane().add(new SplatPanel());frame.pack();frame.setVisible(true);}}
Let’s look at another example. The Splat class shown in Listing 4.7 contains a main method thatcreates and displays the frame for the program. Visually, this program simply draws a few filledcircles. The interesting thing about this program is not what it does, but how it does it—eachcircle drawn in this program is represented by its own object.The main method instantiates a SplatPanel object and adds it to the frame. The SplatPanel classis shown in Listing 4.8. Like the SmilingFacePanel class in the previous example, the SplatPanelclass is derived from JPanel. It holds as instance data five Circle objects, which are instantiatedin the constructor.LISTING 4.8//********************************************************************// SplatPanel.java Author: Lewis/Loftus//// Demonstrates the use of graphical objects.//********************************************************************import javax.swing.*;import java.awt.*;public class SplatPanel extends JPanel{private Circle circle1, circle2, circle3, circle4, circle5;//-----------------------------------------------------------------// Constructor: Creates five Circle objects.//-----------------------------------------------------------------public SplatPanel(){circle1 = new Circle(30, Color.red, 70, 35);circle2 = new Circle(50, Color.green, 30, 20);circle3 = new Circle(100, Color.cyan, 60, 85);circle4 = new Circle(45, Color.yellow, 170, 30);circle5 = new Circle(60, Color.blue, 200, 60);setPreferredSize(new Dimension(300, 200));setBackground(Color.black);}//-----------------------------------------------------------------// Draws this panel by requesting that each circle draw itself.//-----------------------------------------------------------------public void paintComponent(Graphics page){super.paintComponent(page);circle1.draw(page);circle2.draw(page);circle3.draw(page);