为什么我的方法没有清除ArrayList?

时间:2012-12-11 23:54:01

标签: java user-interface arraylist actionlistener

注意:我的代码的问题只是我创建了清除rects的方法,但是我唯一做错的就是在go()方法中实例化DrawPanel类的myDraw对象。所以我不得不再次使用Stop实例化DrawPanel并创建了一个全新的对象。所以我最终在一个不同的DrawPanel对象上调用clearRects方法,而不是添加一个rects。无论如何,我决定使用MadProgrammer的代码建议,因为他的代码正是Java:A Beginner's Guide教授它并且更加清晰。

好吧,我从今天早上起就一直在运行StackOverflow,并且已经能够解决我的代码中的很多问题,但我仍然坚持使用ArrayLists这个问题。

我有以下代码似乎没有做我打算做的事情。现在我知道我是那个在某个地方弄错了但却不确定如何纠正它的人。

它的设置方式是当我点击停止按钮时,ArrayList应该清除,所以我有一个空白的JPanel可以这么说,这是代码片段。如果你想要我,我可以发布整个程序,但我只是在这里粘贴片段,因为我假设我在制作一个非常简单和愚蠢的错误:

class DrawPanel extends JPanel {
    ArrayList<MyRectangle> rects = new ArrayList<>();
    Random rand = new Random();

    @Override
    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        addRect();

        for(MyRectangle r : rects) {
        g.setColor(r.getColor());
        g.fillRect(r.x, r.y, r.width, r.height);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(500,500);
    }

    public ArrayList<MyRectangle> addRect() {
        int ht = rand.nextInt(getHeight());
    int wd = rand.nextInt(getWidth());

    int x = rand.nextInt(getWidth() - wd);
    int y = rand.nextInt(getHeight() - ht);

    int r = rand.nextInt(256);
    int g = rand.nextInt(256);
    int b = rand.nextInt(256);

    rects.add(new MyRectangle(x, y, wd, ht, new Color(r, b, g)));
    System.out.println(rects.size());
    return rects;
}

    public void clearEvent(ActionEvent e) {
        System.out.println(rects.size());
        rects.clear();
        frame.repaint();
        System.out.println("I was called");
    }
}

这是按钮在actionPerformed方法中调用它的部分:

class StopListener implements ActionListener {
    DrawPanel draw = new DrawPanel();
    public void actionPerformed(ActionEvent e) {
        timer.stop();
        draw.clearEvent(e);
    }
    }
编辑:据我所知,我的clearEvent方法引用的arraylist对象与addRect()添加内容的方法不同。我想,我想问的是如何使它“连接”,这样我就可以使用JButton擦拭干净了。

编辑:这是完整的程序:

import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import java.awt.*;

public class TwoButtonsRandomRec {

    JFrame frame;
    Timer timer;

    public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            TwoButtonsRandomRec test = new TwoButtonsRandomRec();
            test.go();
        }
        });
    }

    public void go() {
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton startButton = new JButton("Start");
    startButton.addActionListener(new StartListener());
    JButton stopButton = new JButton("Stop");
    stopButton.addActionListener(new StopListener());

    final DrawPanel myDraw = new DrawPanel();

    timer = new Timer(50, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            myDraw.repaint();
        }
        });

    frame.add(startButton, BorderLayout.NORTH);
    frame.add(stopButton, BorderLayout.SOUTH);
    frame.add(myDraw, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    }

    class StartListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        timer.start();
    }
    }

    class StopListener implements ActionListener {
    DrawPanel draw = new DrawPanel();
    public void actionPerformed(ActionEvent e) {
        timer.stop();
        draw.clearEvent(e);
    }
    }

    class DrawPanel extends JPanel {
    ArrayList<MyRectangle> rects = new ArrayList<>();
    Random rand = new Random();

    @Override
    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        addRect();

        for(MyRectangle r : rects) {
        g.setColor(r.getColor());
        g.fillRect(r.x, r.y, r.width, r.height);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(500,500);
    }

    public ArrayList<MyRectangle> addRect() {
        int ht = rand.nextInt(getHeight());
        int wd = rand.nextInt(getWidth());

        int x = rand.nextInt(getWidth() - wd);
        int y = rand.nextInt(getHeight() - ht);

        int r = rand.nextInt(256);
        int g = rand.nextInt(256);
        int b = rand.nextInt(256);

        rects.add(new MyRectangle(x, y, wd, ht, new Color(r, b, g)));
        System.out.println(rects.size());
        return rects;
    }

    public void clearEvent(ActionEvent e) {
        System.out.println(rects.size());
        rects.clear();
        repaint();
        System.out.println("I was called");
    }
    }
}

class MyRectangle extends Rectangle {
    Color color;
    public MyRectangle(int x, int y, int w, int h, Color c) {
    super(x, y, w, h);
    this.color = c;
    }

    public Color getColor() {
    return color;
    }
}

以下是我在此问过的相关问题,以防有人感兴趣。

Strange JFrame Behavior

1 个答案:

答案 0 :(得分:3)

我看到两个直接的问题。

首先,您在addRect方法中调用了paintComponent,这意味着即使在您清除List之后,在下一次重绘时,也会添加一个新的矩形它。

其次,我会在repaint中拨打DrawPanel而不是使用frame.repaint(),因为您真的只想更新绘图面板,而不是整个框架

public class BadPaint05 {

    public static void main(String[] args) {
        new BadPaint05();
    }

    public BadPaint05() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new MasterPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MasterPane extends JPanel {

        private DrawPanel drawPane;
        private Timer timer;

        public MasterPane() {
            setLayout(new BorderLayout());
            drawPane = new DrawPanel();

            add(drawPane);

            JButton stop = new JButton("Stop");
            stop.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    drawPane.clearEvent(e);
                    timer.stop();
                }
            });

            timer = new Timer(500, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    drawPane.addRect();
                }
            });
            timer.setRepeats(true);
            timer.setCoalesce(true);
            timer.start();

            add(stop, BorderLayout.SOUTH);

        }

    }

    class DrawPanel extends JPanel {

        ArrayList<MyRectangle> rects = new ArrayList<>();
        Random rand = new Random();

        @Override
        public void paintComponent(Graphics g) {

            super.paintComponent(g);

//            addRect();

            for (MyRectangle r : rects) {
                g.setColor(r.getColor());
                g.fillRect(r.x, r.y, r.width, r.height);
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(500, 500);
        }

        public ArrayList<MyRectangle> addRect() {
            int ht = rand.nextInt(getHeight());
            int wd = rand.nextInt(getWidth());

            int x = rand.nextInt(getWidth() - wd);
            int y = rand.nextInt(getHeight() - ht);

            int r = rand.nextInt(256);
            int g = rand.nextInt(256);
            int b = rand.nextInt(256);

            rects.add(new MyRectangle(x, y, wd, ht, new Color(r, b, g)));
            System.out.println(rects.size());
            repaint();
            return rects;
        }

        public void clearEvent(ActionEvent e) {
            System.out.println(rects.size());
            rects.clear();
//            frame.repaint();
            repaint();
            System.out.println("I was called");
        }
    }

    public class MyRectangle {

        private int x, y, width, height;
        private Color color;

        private MyRectangle(int x, int y, int wd, int ht, Color color) {
            this.x = x;
            this.y = y;
            this.width = wd;
            this.height = ht;
            this.color = color;
        }

        public Color getColor() {
            return color;
        }

    }
}