我正在尝试在用户单击 JFrame 的位置绘制类似月亮的形状(或者可能是使用我的代码实现的任何任意形状)。但我得到运行时异常:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at java.awt.geom.AffineTransform.<init>(AffineTransform.java:488)
at sun.java2d.SunGraphics2D.clone(SunGraphics2D.java:267)
at sun.java2d.SunGraphics2D.create(SunGraphics2D.java:300)
at javax.swing.JComponent.paint(JComponent.java:1000)
at Shapes$component.paintComponent(Shapes.java:48)
at javax.swing.JComponent.paint(JComponent.java:1054)
at Shapes$component.paintComponent(Shapes.java:48)
at javax.swing.JComponent.paint(JComponent.java:1054)
at Shapes$component.paintComponent(Shapes.java:48)
at javax.swing.JComponent.paint(JComponent.java:1054)
at Shapes$component.paintComponent(Shapes.java:48)
at javax.swing.JComponent.paint(JComponent.java:1054)
at Shapes$component.paintComponent(Shapes.java:48)
at javax.swing.JComponent.paint(JComponent.java:1054)
at Shapes$component.paintComponent(Shapes.java:48)
at javax.swing.JComponent.paint(JComponent.java:1054)
我哪里错了?如何消除这个错误。
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Shapes extends JFrame{
private ArrayList shapes=new ArrayList();
Shapes()
{
super("Creating moon on mouse clicks");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
addMouseListener(new listener());
add(new component());
setVisible(true);
}
public class listener extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
int x=e.getX();
int y=e.getY();
int rand=(int) Math.floor(Math.random()*x);
int temp;
Area a1=new Area(new Ellipse2D.Double(x,y,rand,rand));
temp=(int)rand/3;
Area a2=new Area(new Ellipse2D.Double(x+temp,y+temp,temp,temp));
a1.subtract(a2);
shapes.add(a1);
repaint();
}
}
public class component extends JComponent
{
public void paintComponent(Graphics g)
{
super.paint(g);
Graphics2D g2=(Graphics2D)g.create();
for(int i=0;i<shapes.size();i++)
{
g2.draw((Shape) shapes.get(i));
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable(){public void run(){new Shapes();}});
}
}