Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can you give sample code to draw rectangle etc., etc.,?

 
sabapathy
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any one give a sample and simple code to draw rectangle on the screen using Frames(Applets are not covered by SCJP exam.so please give example in FRAMES).
Thanks.
 
deekasha gunwant
Ranch Hand
Posts: 396
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi sabapathy,
similar to applet u'll have to write all your drawing code in paint method of frame.. here is a small example.


 
sabapathy
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You Deekasha....
 
sabapathy
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Deekasha,
Can you tell me why the following code is giving compilation error.
Thanks for your time.
Sakthivel.
----------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
class Drawing extends Frame
{
public static void main(String h[])
{
Drawing dr = new Drawing();
dr.setSize(300,300);
dr.setVisible(true);
addWindowListener(new WindowHandler());
}
public void paint(Graphics g)
{
g.drawRect(0,0,200,100);
g.setColor(Color.cyan);
g.fillRect(50,50,150,50);
g.setColor(Color.black);
g.drawString("Hello Sabapathy",60,60);
g.drawOval(100,100,25,25);
g.setColor(Color.red);
g.fillOval(100,100,15,15);
}
class WindowHandler extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
}
 
Sunitha Kumar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Sabapathy,
In the above code you are instantiating non static inner class Window Handler inside the static main.
Non static inner class can be instantiated inside static method like new Outer().new Inner(). This is the reason for the compilation error.
Put the WindowHandler class outside the Drawing class and try compiling it.
Sunitha
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic