如何清除JPanel中的组件?

How to clear components in JPanel?

我是 Java 编程新手。我开发了一个 java 应用程序,它在 windows 框架上绘制形状(圆形、直线、三角形等)。我定义了一个抽象 class Shapes.java 来包含形状的框架:

public abstract class Shapes {
    public abstract void draw(Graphics g);
}

然后,我定义了一些 class 元素,例如从 Shapes.java class.

延伸的圆形、直线、三角形和矩形
public class Circle extends Shapes{
   private int x;
   private int y;
   private int radius;

   public Circle(int x, int y, int radius) {
       this.x = x;
       this.y = y;
       this.radius = radius;
   }

   @Override
   public void draw(Graphics g) {
       g.drawOval(x-radius,y-radius,radius * 2, radius *2);
   }}

在我的Picture.javaclass中,我设置了一个JFrame并在上面添加形状:

public class Picture extends JFrame {
    private static final long serialVersionUID = 1L;
    private int width;
    private int height;
    private boolean isClear = false;

    private ArrayList<Shapes> listShape = new ArrayList<Shapes>();
    private class ShapesPanel extends JPanel{
    private static final long serialVersionUID = 1L;

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(isClear)
            return;
        else
            for (Shapes s : listShape)
                s.draw(g);         
    }

    public void add(Shapes s){
        listShape.add(s);
    }

    public Picture(int width, int height, String title) throws HeadlessException {
        ShapesPanel mypanel = new ShapesPanel();
        add(mypanel);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.width = width;
        this.height = height;
        this.setTitle(title);
    }  

    public void draw(){
        setLocationRelativeTo(null);
        setSize(width, height);
        setVisible(true);
        repaint();
    }

    void clear(){//clear the componets in the JPanel
        this.setIsClear(true); 
        this.validate();
        this.repaint();
    }

    private void setIsClear(boolean b) {
        // TODO Auto-generated method stub
        this.isClear = b;
    }
}

但是当我在主class中调用clear()方法时,程序无法再次重新绘制新形状。我该如何修复错误?谢谢。

public class MyPic {
    public static void main(String[] args){
        Picture pic = new Picture(420, 300, "shape demo");
        Circle c1 = new Circle(320,80,80);
        Rectangle r1 = new Rectangle(100,100,100,100);
        Triangle t1 = new Triangle(100,100,200,100,150,50);
        Line l1 = new Line(0,205,400,50);

        pic.add(c1);
        pic.add(r1);
        pic.add(t1);
        pic.add(l1);
        pic.clear();
        pic.draw();
        pic.add(l1);//add l1 again
    }
}

好的,所以通过调用 clear(),您将变量 isClear 设置为 true。然后在你的 paintComponent 你说:

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if(isClear)
        return;

这意味着“如果 isClear 为真,则不要绘制任何东西”(就是这样,您只需使用 clear() 将其设置为真)。所以,难怪。

无论如何,我认为在 clear 方法中,您可能想要执行 listShape.clear() 而不是设置该布尔值。