import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; /** * A GUI application that plays within painting on a JPanel * * @author Sharon Tuttle * @version 2015-10-21 */ public class DrawPlay1 { /** * creates a DrawPlay1Frame * * @param args not used here */ public static void main(String args[]) { EventQueue.invokeLater( new Runnable() { public void run() { DrawPlay1Frame mainFrame = new DrawPlay1Frame(); mainFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); mainFrame.setVisible(true); } }); } } /** * A frame with a panel that is painted/drawn upon */ class DrawPlay1Frame extends JFrame { // data fields private final static int DEFAULT_WIDTH = 500; private final static int DEFAULT_HEIGHT = 500; /** * constructs a DrawPlay1Frame instance */ public DrawPlay1Frame() { this.setTitle("DrawPlay1"); this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // add DrawPlay1 panel to frame DrawPlay1Panel panel = new DrawPlay1Panel(); this.add(panel); } } /** * a JPanel subclass to be drawn/painted upon */ class DrawPlay1Panel extends JPanel { private final static Font DISPLAY_FONT = new Font("Dialog", Font.PLAIN, 20); // using the default constructor?! THIS time /** * paint/draw some stuff on this DrawPlay1Panel * * @param g the Graphics object to hold graphics-related * settings */ public void paintComponent(Graphics g) { // call JPanel's version of this first, // to handle usual background painting, etc. super.paintComponent(g); // let's paint 2 strings using the default font // and color g.drawString("I am painted at (10, 20)", 10, 20); g.drawString("I am painted at (10, 60)", 10, 60); g.setFont(new Font("Serif", Font.ITALIC, 30)); g.setColor(Color.BLUE); g.drawString("...and I am painted at (50, 100)", 50, 100); g.setFont(DISPLAY_FONT); g.drawString("...and I am painted at (50, 150)", 50, 150); // course text mentions that class Graphics2D // has better/more-sophisticated figure-drawing // methods -- I am using the "old" Graphics // methods below for simplicity // drawRect(topLeftX, topLeftY, width, height) // ...for a rectangle outline g.drawRect(200, 200, 50, 75); // fillRect for a "filled" rectangle g.setColor(Color.PINK); g.fillRect(200, 200, 30, 60); // drawLine(startX, startY, endX, endY) g.setColor(Color.MAGENTA); g.drawLine(80, 80, 160, 120); } }