问题:正如您所看到的,当我们执行此代码并单击圆形按钮时,它会正确计数,但是当单击方形按钮时,它会再次正确计数,但再次单击圆形按钮然后先前的圆计数消失并再次从 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>
*/
最佳答案
我认为以前的开发人员在 cont
上调用 paint
是一个错误。这将作为部分自动完成,如果部分进程无论如何,我会将其替换为 super.paint
我怀疑原作者无法弄清楚如何一次绘制多个形状。
paint
方法一次只能绘制一个形状。除非您将形状添加到某种列表中,然后循环遍历,否则每次调用 Paint 方法时,每次调用 Paint 时,它都会删除先前的内容并仅绘制指定的形状。
您确实应该创建一个自定义组件,扩展类似 JPanel
的形式,并重写其 paintComponent
方法。在此,您应该绘制形状。
当前实现的问题是形状可能会绘制在控件上,这很可能是不可取的
关于java - 尝试理解已经制作的 JApplet 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15596138/