我试图在用户点击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)
Run Code Online (Sandbox Code Playgroud)
我哪里错了?如何删除此错误.
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();}});
}
}
Run Code Online (Sandbox Code Playgroud)
当你覆盖时,paintComponent()你正在调用super.paint()而不是super.paintComponent().
默认实现的JComponent.paint()执行paintComponent(),paintBorder()和 paintChildren().因此,执行super.paint()从paintComponent()创建无限的执行循环.这就是原因StackOverflowError.
这是错的......
public void paintComponent(Graphics g)
{
super.paint(g);
// ...
}
Run Code Online (Sandbox Code Playgroud)
万一你错过了它;) - 它应该读
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
340 次 |
| 最近记录: |