Note that there are some explanatory texts on larger screens.

plurals
  1. POTrying to understand an already made JApplet code
    primarykey
    data
    text
    <p><b> Question :</b>As you can see when we execute this code and click on Circle button it counts it properly, but when square button is clicked it again counts it properly but then once again circle button is click then the previous counts of circle gets disappeared and it again starts from 1.</p> <p><b> Where's the problem :</b> After doing a bit of search i came to know that the method <b>getGraphics()</b> invoked on ContentPane object is causing the problem, i tried changing it but then the program doesn't even run and if it runs then all GUI components will have problem.</p> <p>Edit : Did what mKorbel said</p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CountShapes1 extends JApplet implements ActionListener { Container cont; JPanel p; JLabel lblCount; JButton btCircle,btSquare; boolean blnCircle,blnSquare; int count=0; String shape=""; public void init() { cont=getContentPane(); lblCount=new JLabel("Shape Count : 0",JLabel.CENTER); lblCount.setFont(new Font("Arial",Font.BOLD,18)); cont.add(lblCount,BorderLayout.NORTH); btCircle=new JButton("Circle"); btSquare=new JButton("Square"); btCircle.addActionListener(this); btSquare.addActionListener(this); p=new JPanel(); p.add(btCircle); p.add(btSquare); cont.add(p,BorderLayout.SOUTH); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==btCircle) { if(blnSquare==true) { blnSquare=false; count=0; } blnCircle=true; shape="CIRCLE"; count++; lblCount.setText(shape+" Count : "+count); repaint(); } if(ae.getSource()==btSquare) { if(blnCircle==true) { blnCircle=false; count=0; } blnSquare=true; shape="SQUARE"; count++; lblCount.setText(shape+" Count : "+count); repaint(); } } public void paint(Graphics g) { cont.paint(cont.getGraphics()); int x=10,y=30,w=30,h=30; if(shape.equals("CIRCLE") || shape.equals("SQUARE")) { for(int i=0;i&lt;count;i++) { if(shape.equals("CIRCLE")) { g.drawOval(x,y,w,h); } else { g.drawRect(x,y,w,h); } x+=40; if(x&gt;=getWidth()-30) { x=10; y+=40; } } //for -loop finished } // if-finished } // paint() finished } // class finished /* &lt;applet code="CountShapes1" width=500 height=500&gt; &lt;/applet&gt; */ </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload