Draw circle and rectangle in java -
i new java , want draw circle , rectangle using java code. did write code purpose , tried @ own. on panel appearing , shapes not appearing.
code of "mypanel" given below
import javax.swing.*; import java.awt.*; public class mypanel extends jpanel{ public void paincomponent(graphics g){ super.paintcomponent(g); graphics2d g2 = (graphics2d)g; g2.drawrect(20,20,20,20); g2.setcolor(color.blue); g2.filloval(50,20,20,20); g2.drawstring("hello world", 120, 50); }//end paincomponent }//end test class
cdoe of driver class "test" given below.
import javax.swing.*; import java.awt.*; public class test{ jframe f; mypanel p; public test(){ f = new jframe(); container c = f.getcontentpane(); c.setlayout(new borderlayout()); p = new mypanel(); c.add(p, borderlayout.center); f.setsize(400,400); f.setvisible(true); f.setdefaultcloseoperation(jframe.exit_on_close); }//end of constructor public static void main(string args[]){ test t = new test(); } }
and per knowledge when frame becomes visible through paintchildren()
method panel should become visible become visible panel call paintcomponent()
method custom drawing, seems panel not calling paintcomponent()
.
you doing spelling mistake. method inside “mypanel” paincomponent() rather paintcomponent()
“t” missing prototype why program not able override paintcomponent() in mypanel class.
so have update code , replace “paintcomponent();”
complete class code given below,
import javax.swing.*; import java.awt.*; public class mypanel extends jpanel{ public void paintcomponent(graphics g){ super.paintcomponent(g); graphics2d g2 = (graphics2d)g; g2.drawrect(20,20,20,20); g2.setcolor(color.blue); g2.filloval(50,20,20,20); g2.drawstring("hello world", 120, 50); }//end paincomponent }//end test class
i have tested code works fine.
Comments
Post a Comment