【问题标题】:Java add rectangles to ArrayList and then draw themJava将矩形添加到ArrayList,然后绘制它们
【发布时间】:2014-12-25 15:29:30
【问题描述】:

我真的需要你们的帮助。 我尝试将矩形添加到 ArrayList,然后循环遍历列表以将它们全部绘制出来。我不确定我是否使用了正确的方法,但这是我目前的代码。

编辑:代码不会绘制我添加到 ArrayList 的矩形。我什至不知道它们是否以正确的方式添加,或者以正确的方式通过 for 循环访问。

在测试程序中

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JFrame;


public class TestProgram extends JFrame {
    private ShapeRectangle rectangle;
    public ArrayList<Shapes> list = new ArrayList<Shapes>();


    public TestProgram(String title) {
        super(title);
        setLayout(new BorderLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        initComponents();
        setSize(500, 700);
        setVisible(true);
  }

    private void initComponents() {
        rectangle = new ShapeRectangle();    
        add(rectangle, BorderLayout.CENTER);

        list.add(rectangle);        
        Graphics g = getGraphics();
        for (int i = 0; i < list.size(); i++) {
            rectangle.draw(g);
        }
  }

    public static void main(String args[]) {
        new TestProgram("Drawing program");
    }
}

在 ShapeRectangles 类中:

import java.awt.Graphics;

public class ShapeRectangle extends Shapes {

    public ShapeRectangle() {}    

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponents(g);
        draw(g);        
    }

    @Override
    public void draw(Graphics g) {
       g.drawLine(20,20,60,60);
       g.drawLine(130,30,80,11);
       g.drawRect(200,30,20,140);        
   }
}

在形状类中:

import java.awt.Graphics;
import javax.swing.JPanel;

public abstract class Shapes extends JPanel {

    abstract public void draw(Graphics g); 

}

【问题讨论】:

  • 您的问题到底是什么?代码看起来不错。
  • 我闻到了 NullPointerException 酿造的味道:Graphics g = null;
  • Shapes 设为abstract class 并在其子项中覆盖您的draw(g) 方法。
  • @Mr.Polywhirl 我刚刚将 null 更改为 getGraphics();还是不行。。
  • 我也将 Shapes 抽象化了。请参阅上面的更新代码。还是不行。。

标签: java swing arraylist


【解决方案1】:

首先查看2D Graphics,尤其是Working with Geometry

2D 图形 API 定义了一个 Shape API,其中包括一个 Rectangle

例如...

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestRectangles {

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

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

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private List<Rectangle> rectangles;

        public TestPane() {
            rectangles = new ArrayList<>(25);
            Random ran = new Random();

            for (int index = 0; index < 10; index++) {
                int x = ran.nextInt(200 - 10);
                int y = ran.nextInt(200 - 10);
                int width = ran.nextInt(200 - x);
                int height = ran.nextInt(200 - y);
                rectangles.add(new Rectangle(
                        x, 
                        y, 
                        width, 
                        height));
            }
        }

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            for (Rectangle rect : rectangles) {
                g2d.draw(rect);
            }
            g2d.dispose();
        }

    }

}

【讨论】:

    【解决方案2】:

    不要把Shapes 变成JPanel。也取出它的paintComponent 方法。

    取而代之的是一个JPanel 类,它是主要的绘图表面。在课堂上保留List&lt;Shapes&gt;。遍历该类的paintComponent方法中的列表,调用每个Shapes的draw方法

    class DrawingPanel extends JPanel {
        List<Shapes> shapes;
        // add shapes
    
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (Shapes shape: shapes) {
                shape.draw(g);
            }
        }
    }
    

    然后将该面板添加到框架中。

    请记住,所有绘制都应使用传递给paintComponent 方法的 Graphics 上下文来完成。我们不使用getGraphics 进行自定义绘画。

    此外,您可能希望在 Shapes 类中存储一些状态,以便您可以更改 x/y/width/height 状态。现在,您正在为所有形状使用相同的硬编码值。

    abstract class Shapes {
        int x, y;
        public Shapes(int x, int y) {
            this.x = x; this.y = y;
        }
        protected abstract void draw(Graphics g);
    }
    class RectangleShape extends Shape {
        int width, height;
        public RectangleShape(int x, int y, int width, int height) {
            super(x, y);
            this.width = width; this.height = height;
        }
        @Override   
        public void draw(Graphics g) {
            g.fillRect(x, y, width, height);
        }
    }
    

    查看complete example with more complex objects with animation

    【讨论】:

    • 你能解释一下吗?我是新手,不明白你的意思。如何“将面板添加到框架中”?绘制方法中有什么? “取出它的paintcomponent方法”是什么意思?感谢您的时间和精力
    • DrawingPanel 添加到JFrameadd(new DrawingPanel())
    【解决方案3】:

    这个不好,你要么想把它添加为一个绝对定位的组件,要么你想画它,选择一个。

    this.add(rectangle, BorderLayout.CENTER); // Add as component of the panel.
    list.add(rectangle);                      // Add as method of drawing on the panel.
    

    后者会更好,因为您正在绘图。如果需要拖放,请将其添加为子项,但将绘图添加到子项。

    你可以在JFrame上调用repaint()来更新矩形的坐标和大小后的图形。

    绘制形状

    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.util.ArrayList;
    
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    
    public class DrawShapes extends JFrame {
        public ArrayList<Shape> shapeList = new ArrayList<Shape>();
    
        public DrawShapes(String title) {
            super(title);
    
            this.setLayout(new BorderLayout());
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            this.setSize(500, 700);
            this.setLocationRelativeTo(null);
    
            this.initComponents();
        }
    
        private void initComponents() {
            shapeList.add(new RectangleShape(20, 20, 60, 60));
            shapeList.add(new RectangleShape(130, 30, 80, 11));
            shapeList.add(new RectangleShape(200, 30, 20, 140));
        }
    
        @Override
        public void paint(Graphics g) {
            for (Shape s : shapeList) {
                s.draw(g);
            }
        }
    
        public static void main(String args[]) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    DrawShapes d = new DrawShapes("Drawing program");
                    d.setVisible(true);
                }
            });
        }
    }
    

    矩形形状

    import java.awt.Graphics;
    
    public class RectangleShape extends Shape {
        public RectangleShape(int x, int y, int width, int height) {
            super(x, y, width, height);
        }
    
        public RectangleShape() {
            super();
        }
    
        @Override
        public void draw(Graphics g) {
            g.drawRect(getX(), getY(), getWidth(), getHeight());
        }
    }
    

    形状

    import java.awt.Graphics;
    
    public abstract class Shape {
        private int x;
        private int y;
        private int width;
        private int height;
    
        public Shape() {
            this(0, 0, 1, 1);
        }
    
        public Shape(int x, int y, int width, int height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }
    
        public abstract void draw(Graphics g);
    
        public int getX() {
            return x;
        }
    
        public void setX(int x) {
            this.x = x;
        }
    
        public int getY() {
            return y;
        }
    
        public void setY(int y) {
            this.y = y;
        }
    
        public int getWidth() {
            return width;
        }
    
        public void setWidth(int width) {
            this.width = width;
        }
    
        public int getHeight() {
            return height;
        }
    
        public void setHeight(int height) {
            this.height = height;
        }
    }
    

    【讨论】:

    • 这行得通,非常感谢。我实际上应该有另外两个类 ShapesCircles 和 ShapesFreeHand。我还应该通过在屏幕上拖动鼠标来绘制矩形、圆形和 FreeHands。我的下一个挑战...您写道“如果您需要拖放,请将其添加为子项,但将绘图添加到子项。”你是什​​么意思?关于如何修复它的任何建议?再次感谢您!
    • 好吧,对于矩形,如果你最终再次将其设为JComponent,则绘制方法将不得不忽略全局xy。您将从“(0, 0)”开始。将g.drawRect(getX(), getY(), getWidth(), getHeight()); 更改为g.drawRect(0, 0, getWidth(), getHeight()); getWidth()getHeight() 将由JComponent/JPanel 提供。
    • 我不确定我是否明白你的意思。如何从 JPanel 提供 getHeight() 和 getHeight()?如果我听起来很愚蠢,我很抱歉,但这对我来说真的很难。
    • 你能解释一下我应该把 addMouseListener() 放在哪里吗?不是以对象作为参数,但我没有创建任何对象。
    • Java 中的所有非原语都是对象
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2014-04-19
    • 2018-02-26
    相关资源
    最近更新 更多