// DrawingFrameDemo.java //howto do Graphics drawing in a JFrame by subclassing JPanel: //define a customized subclass of JPanel that can do graphical drawing. //widgets' event handler is 'this'. // import java.awt.*; import java.awt.event.*; import javax.swing.*; public class DrawingFrameDemo implements ActionListener { private JFrame outputFrame; private Container container; private DrawingPanel myDrawingPanel; //***DrawingPanel is user-defined below private JButton drawButton; public static void main( String [] args ) { DrawingFrameDemo myDemo = new DrawingFrameDemo(); } public DrawingFrameDemo() { outputFrame = new JFrame(); outputFrame.setSize(600,500); outputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); container = outputFrame.getContentPane(); container.setLayout( new BorderLayout() ); //for this demo //***create object of the customized subclass of JPanel myDrawingPanel = new DrawingPanel(); drawButton = new JButton( "Draw some random lines (click me)" ); drawButton.addActionListener(this); container.add( myDrawingPanel, BorderLayout.CENTER ); container.add( drawButton, BorderLayout.SOUTH ); outputFrame.setVisible(true); } public void actionPerformed( ActionEvent event ) { //***call of some method of the custom subclass of JPanel that calls repaint() myDrawingPanel.drawRandomLines(); } } //*** define a subclass (of whatever name) of JPanel. class DrawingPanel extends JPanel { //***must be this signature. //***called explicitly by the repaint method and //implicitly whenever the area is resized or uncovered. //analogous to the paint method of an applet. //all the Graphics drawing methods can be used: //drawLine, drawOval, fillOval, drawRect, fillRect, drawString, setColor, setFont... public void paintComponent( Graphics g ) { super.paintComponent( g ); //clears the drawing area. int w=getWidth(); //***width of drawing area. int h=getHeight(); //*** Try resizing the frame window. //draw some random lines for demo purposes: for (int i=1; i<100; i++) { g.setColor(new Color((int)(Math.random()*256), //random color (int)(Math.random()*256), (int)(Math.random()*256))); g.drawLine((int)(Math.random()*w), //random start and end points (int)(Math.random()*h), (int)(Math.random()*w), (int)(Math.random()*h)); } } //***a method that calls repaint() public void drawRandomLines() { repaint(); //repaint() has paintComponent() called } }