How to paint an arrayList of shapes Java

前端 未结 2 1900
盖世英雄少女心
盖世英雄少女心 2020-12-22 12:41

I am tasked with how to paint an arrayList of shapes in java.

I feel i have most of it right, there are two methods i am confused about however

the method in

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-22 13:43

    You could...

    Define an "abstract" concept of a shape, which has the basic properties (location and size) and which can paint itself...

    public abstract class Shape {
    
        private int x, y;
        private int width, height;
        private Color c;
    
        public Shape(int x, int y, int width, int height, Color c) {
            this.x = x;
            this.y = y;
            this.c = c;
            this.width = width;
            this.height = height;
        }
    
        public int getHeight() {
            return height;
        }
    
        public int getWidth() {
            return width;
        }
    
        public int getX() {
            return x;
        }
    
        public int getY() {
            return y;
        }
    
        public Color getColor() {
            return c;
        }
    
        public abstract void paint(Graphics2D g2d);
    }
    

    Then you can implement the individual shapes...

    public class Rectangle extends Shape {
    
        public Rectangle(int x, int y, int width, int height, Color c) {
            super(x, y, width, height, c);
        }
    
        @Override
        public void paint(Graphics2D g2d) {
            g2d.setColor(getColor());
            g2d.drawRect(getX(), getY(), getWidth(), getHeight());
        }
    }
    
    public class Oval extends Shape {
    
        public Oval(int x, int y, int width, int height, Color c) {
            super(x, y, width, height, c);
        }
    
        @Override
        public void paint(Graphics2D g2d) {
            g2d.setColor(getColor());
            g2d.drawOval(getX(), getY(), getWidth(), getHeight());
        }
    }
    

    Then, you can simply call the paint method of each instance of Shape as required...

    public class TestPane extends JPanel {
    
        private List shapes;
    
        public TestPane() {
            shapes = new ArrayList<>(25);
            shapes.add(new Rectangle(10, 10, 20, 20, Color.RED));
            shapes.add(new Oval(15, 15, 40, 20, Color.RED));
        }
    
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (Shape shape : shapes) {
                Graphics2D g2d = (Graphics2D) g.create();
                shape.paint(g2d);
                g2d.dispose();
            }
        }
    
    }
    

提交回复
热议问题