Recall from earlier steps that drawing was done within the overridden method,
paint
. If we do that in the current context, we would be drawing on the applet's inherent panel, not ondrawPanel
. To draw ondrawPanel
, we must override thePanel
class so that within that class we perform our drawing operations.Example Applet
import java.applet.Applet; import java.awt.*; public class step6 extends Applet{ // step 5 provided framework, but no way to draw; step 6 extends // Panel class to provide drawing TextArea ta = new TextArea ("My Text Area", 5, 40); Button button = new Button ("Button"); MyPanel drawPanel = new MyPanel (); Panel topPanel = new Panel ( ); public void init ( ){ setBackground (Color.white); setForeground (Color.red); topPanel.add (ta); topPanel.add (button); setLayout (new BorderLayout ( ) ); add ("North", topPanel); add ("Center", drawPanel); } // end init }// end step6 class MyPanel extends Panel { public void paint (Graphics g ) { g.fillRect (50, 50, 100, 100); g.setColor (Color.blue); g.setFont (new Font ("Helvetica", Font.BOLD, 24) ); g.drawString ("Hello, World!", 200, 200); g.setColor (Color.yellow); g.drawOval (300, 50, 100, 100); g.setColor (Color.green); g.fillArc (50, 300, 200, 200, 180, -90); g.setColor (Color.cyan); g.fill3DRect (300, 300, 100, 100, true ); } // end paint } // end MyPanelRun the applet
Discussion
Instead of declaring
drawPanel
to be of typePanel
, we declare it to be of typeMyPanel
, which is defined in the second half of the program. (It could also be stored separately in a file of its own, of the same name.) We then use itspaint
method to draw ondrawPanel
.