import java.awt.*; import java.awt.event.*; import javax.swing.*; /** a GUI application drawing on a JPanel subclass @author Sharon Tuttle @version 2021-10-25 */ public class DrawApp1 { /** creates a simple frame with a panel that is painted upom @param args not used here */ public static void main(String[] args) { EventQueue.invokeLater( () -> { DrawApp1Frame mainFrame = new DrawApp1Frame(); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setVisible(true); } ); } } /** A frame with a panel that is drawn upon! */ class DrawApp1Frame extends JFrame { // data fields private static final int DEFAULT_WIDTH = 450; private static final int DEFAULT_HEIGHT = 200; /** construct a DrawApp1Frame instance */ public DrawApp1Frame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setTitle("Drawing on a panel"); DrawApp1Panel mainPanel = new DrawApp1Panel(); add(mainPanel); } } /** A panel to be drawn/painted upon */ class DrawApp1Panel extends JPanel { // using default constructor /** draw/paint several strings on this panel @param g the Graphics object to hold the pertinent settings */ public void paintComponent(Graphics g) { // I want to call the inherited version first... 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, 30)", 10, 30); // let's muck with the font and color of this Graphics // object g.setFont(new Font("Serif", Font.ITALIC, 40)); g.setColor(new Color(128, 255, 145)); g.drawString("...and I am painted at (50, 50)", 50, 50); g.setFont(new Font("Dialog", Font.PLAIN, 20)); g.setColor(Color.MAGENTA); g.drawString("...and I am painted at (50, 100)", 50, 100); } }