Reputation: 69
import java.awt.*;
import javax.swing.JFrame;
public class GraphicsDemo1 extends Canvas
{
public void paint( Graphics g )
{
g.setColor(Color.green);
g.drawRect(50,20,100,200); // draw a rectangle
g.fillOval(160,20,100,200); // draw a filled-in oval
g.setColor(Color.blue);
g.fillRect(200,400,200,20); // a filled-in rectangle
g.drawOval(200,430,200,100);
g.setColor(Color.black);
g.drawString("Graphics are pretty neat.", 500, 100);
int x = getWidth() / 2;
int y = getHeight() / 2;
g.drawString("The first letter of this string is at (" + x + "," + y + ")", x, y);
}
public static void main( String[] args )
{
// You can change the title or size here if you want.
JFrame win = new JFrame("GraphicsDemo1");
win.setSize(800,600);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphicsDemo1 canvas = new GraphicsDemo1();
win.add( canvas );
win.setVisible(true);
}
}
Thanks. awt and swing are very confusing to me.
Upvotes: 1
Views: 1919
Reputation: 347204
why does it extend canvas?
Because who ever wrote it chose to do so. Only those classes that extend from Component
can actually be painted to the screen and only when they are attached to a valid, visible window
When is paint called in this program?
Painting is the responsibility of the RepaintManager
. It will decide when components need to be repainted and schedule a repaint event on the Event Dispatching Thread. This in turn calls (in your case update
which calls) paint
on your behalf.
You might like to have a read through Painting in AWT and Swing for more details on the subject
Upvotes: 3
Reputation: 81459
paint() is called whenever the control is invalidated and needs to repaint itself. Think of moving the app partially off screen and then back. Paint would get called to redraw...
I suppose a number of different controls could be extended to achieve the same goal which is basically to create a custom-drawn control. An existing control is extended to get the ability to draw on its surface, be placed in a JFrame, get repainted automatically etc.
Upvotes: 1