4

注意:我的代码的问题只是我创建了清除矩形和所有内容的方法,但我做错的唯一一件事是在 go() 方法中实例化 DrawPanel 类的 myDraw 对象。所以我不得不用 Stop 再次实例化 DrawPanel 并创建了一个全新的对象。所以我最终在一个不同的 DrawPanel 对象上调用了 clearRects 方法,而不是添加了一个矩形。无论如何,我决定采用 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;
    }
}

这是我在这里问的上一个相关问题,以防有人感兴趣。

奇怪的 JFrame 行为

4

1 回答 1

3

我看到两个直接的问题。

第一个是,您在方法addRect内调用paintComponent,这意味着,即使您清除List, 在下一次重绘时,也会向其中添加一个新矩形。

其次,我会调用repaintDrawPanel不是 using 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;
        }

    }
}
于 2012-12-12T00:10:16.590 回答