import java.awt.Frame; import java.awt.Canvas; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.Image; import java.awt.Toolkit; import java.awt.Graphics2D; // Used for anti-aliasing import java.awt.RenderingHints; // Used for anti-aliasing public class GraphicsObjectPlacementWithFrame { public static void main(String[] args) { // Create a frame Frame frame = new Frame(); // Set the size of the frame frame.setSize(500, 500); // Have the frame appear in the center of the screen frame.setLocationRelativeTo(null); // Make the frame not resizable frame.setResizable(false); // Give the frame a title frame.setTitle("Object Placement with Frame"); // Create (instantiate) an instance of the 'GraphicsCanvas' class GraphicsCanvas canvas = new GraphicsCanvas(); // Set the canvas background color to yellow canvas.setBackground(Color.yellow); // Add the canvas to the frame frame.add(canvas); // Make the frame visible frame.setVisible(true); // Close and destroy the window (frame) when a closing event is // detected; without this section of code, it can be difficult // for a user to end the program and make the frame go away; // note that with a JFrame (as opposed to a Frame), closing a // window can be handled with a single line of code frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().dispose(); System.exit(0); } }); } } // The 'GraphicsCanvas' class becomes a type of canvas since it extends // the 'Canvas' class class GraphicsCanvas extends Canvas { // Display the graphics, text, and image in the frame public void paint(Graphics g) { // This line causes graphics and text to be rendered with anti-aliasing // turned on, making the overall display look smoother and cleaner ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Draw a line, an oval (circle), and an arc g.setColor(Color.blue); g.drawLine(280, 50, 400, 150); g.fillOval(34, 336, 100, 100); g.drawArc(30, 75, 100, 250, 45, 90); // Draw a rectangle and fill it in g.drawRect(20, 150, 100, 100); g.setColor(Color.cyan); g.fillRect(21, 151, 99, 99); // Draw a rounded rectangle g.setColor(Color.red); g.drawRoundRect(150, 75, 100, 250, 45, 90); // Draw a four-sided polygon g.setColor(Color.green); int[] xCoords = {350, 440, 400, 390}; int[] yCoords = {30, 10, 40, 90}; g.drawPolygon(xCoords, yCoords, 4); // Draw some text g.setColor(Color.black); g.setFont(new Font("Arial", Font.BOLD, 24)); g.drawString("Hello, World!", 15, 40); // Display a diskfile image Image image = Toolkit.getDefaultToolkit().getImage("data_files/davebaby.jpg"); g.drawImage(image, 280, 200, this); } }