问题:正如您所看到的,当我们执行此代码并单击圆形按钮时,它会正确计数,但是当单击方形按钮时,它会再次正确计数,但是再次单击圆形按钮,则先前的圆形计数会消失并且它再次从 1 开始。
问题出在哪里:经过一番搜索后,我知道在 ContentPane 对象上调用的方法getGraphics()导致了问题,我尝试更改它,但程序甚至没有运行,如果它运行则所有 GUI 组件会有问题。
编辑:做了 mKorbel 所说的
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<count;i++)
{
if(shape.equals("CIRCLE"))
{
g.drawOval(x,y,w,h);
}
else
{
g.drawRect(x,y,w,h);
}
x+=40;
if(x>=getWidth()-30)
{
x=10;
y+=40;
}
} //for -loop finished
} // if-finished
} // paint() finished
} // class finished
/*
<applet code="CountShapes1" width=500 height=500>
</applet>
*/