Java: Example - Drawing a Face - v3
Two separate source files
This is the same as the previous application, except that the two classes have been put into separate files. Programs are generally easier to manage if separate classes are in separate files. For small programs there is little difference, but for large programs it becomes more important to separate them.
The main program
The code is identical to the first example. We've only taken the Face class definition out of here, and put it into a separate file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// File: face/file2/PacLadyApplication.java // Author: Fred Swartz, Date: July 1998 ... Oct 2004 import java.awt.*; import javax.swing.*; ///////////////////////////////////////////////// class PacLadyApplication public class PacLadyApplication { public static void main(String[] args) { JFrame window = new JFrame("Face"); // Create a new window. window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setContentPane(new Face()); // Put drawing in window. window.pack(); // Adjust to fit panel. window.setVisible(true); // Show the window. } } |
The Face class
The class is unchanged from the previous example. However, it was necessary to add the import statements that are needed by Face.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// File: face/file2/Face.java // Author: Fred Swartz, Date: July 1998 ... Oct 2004 import java.awt.*; import javax.swing.*; //////////////////////////////////////////////////////////////// class Face class Face extends JPanel { /** Constructor sets background color and initial size. */ public Face() { this.setPreferredSize(new Dimension(300, 300)); this.setBackground(Color.GRAY); } /** Override paintComponent to draw a face */ public void paintComponent(Graphics g) { super.paintComponent(g); // Required as first line. //... Get panel width and height, Compute center. int centerX = this.getWidth() / 2; int centerY = this.getHeight() / 2; //... Draw everything except the mouth in pink g.setColor(Color.PINK); g.fillArc(centerX-100, centerY-100, 200, 200, 30, 300); //... Draw an eye g.setColor(Color.MAGENTA); g.fillOval(170, 90, 15, 20); } } |