DrawRect, DrawOval, DrawLine, FillRect и FillOval рисуют только прямую горизонтальную линию в предоставленном коде - PullRequest
0 голосов
/ 07 января 2020

Я сейчас практикую GUI в Java и создал программу, которая процедурно генерирует случайные формы в зависимости от ввода пользователя. Однако, похоже, что он не работает правильно. В настоящее время программа выглядит следующим образом (линии вместо прямоугольников и овалов): Lines instead of Rectangles and Ovals

Однако, как указывалось выше, программа должна иметь несколько заполненных, незаполненных прямоугольников и овалов и линий. Эти горизонтальные линии не представляют, как должен выглядеть результат.

Это код ниже.

DrawPanelTest. java (основной файл)

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.BorderLayout;

public class DrawPanelTest {
    public static void main(String[] args) {
        String amount = JOptionPane.showInputDialog("How many shapes should exist?");
        int intAmount = Integer.parseInt(amount);
        DrawPanel drawPanel = new DrawPanel(intAmount);
        JLabel text = new JLabel("Lines: " + drawPanel.getLineAmount() + ", Ovals: " + drawPanel.getOvalAmount()
                + ", Rectangles: " + drawPanel.getRectangleAmount());
        JFrame jFrame = new JFrame();
        jFrame.setDefaultCloseOperation(3);
        jFrame.add(drawPanel);
        jFrame.add(text, BorderLayout.SOUTH);
        jFrame.setSize(600, 600);
        jFrame.setVisible(true);
    }
}

DrawPanel. java

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JPanel;

public class DrawPanel extends JPanel {
    private Random random = new Random();
    private Shape[] shapes;
    private int lineAmount;
    private int ovalAmount;
    private int rectangleAmount;

    public DrawPanel(int amount) {
        shapes = new Shape[amount];
        for (int i = 0; i < shapes.length; i++) {
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            int choice = random.nextInt(3);
            switch (choice) {
            case 0:
                shapes[i] = new Line(random.nextInt(300), random.nextInt(300), random.nextInt(300), random.nextInt(300),
                        color);
                lineAmount++;
                break;
            case 1:
                shapes[i] = new Oval(random.nextInt(300), random.nextInt(300), random.nextInt(300), random.nextInt(300),
                        color, random.nextBoolean());
                ovalAmount++;
                break;
            case 2:
                shapes[i] = new Rectangle(random.nextInt(300), random.nextInt(300), random.nextInt(300),
                        random.nextInt(300), color, random.nextBoolean());
                rectangleAmount++;
                break;
            }
        }
    }

    public int getLineAmount() {
        return lineAmount;
    }

    public int getOvalAmount() {
        return ovalAmount;
    }

    public int getRectangleAmount() {
        return rectangleAmount;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Shape shape : shapes) {
            shape.draw(g);
        }
    }
}

Форма. java

import java.awt.Color;
import java.awt.Graphics;

public abstract class Shape {
    private int x1;
    private int y1;
    private int x2;
    private int y2;
    private Color color;

    public Shape() {
        setX1(0);
        setY1(0);
        setX2(100);
        setY2(100);
        setColor(0, 0, 0);
    }

    public Shape(int x1, int y1, int x2, int y2, Color color) {
        setX1(x1);
        setY1(y1);
        setX2(x2);
        setY2(y1);
        setColor(color);
    }

    public void setX1(int newX1) {
        if (newX1 >= 0) {
            x1 = newX1;
        } else {
            x1 = 0;
        }
    }

    public int getX1() {
        return x1;
    }

    public void setY1(int newY1) {
        if (newY1 >= 0) {
            y1 = newY1;
        } else {
            y1 = 0;
        }
    }

    public int getY1() {
        return y1;
    }

    public void setX2(int newX2) {
        if (newX2 >= 0) {
            x2 = newX2;
        } else {
            x2 = 0;
        }
    }

    public int getX2() {
        return x2;
    }

    public void setY2(int newY2) {
        if (newY2 >= 0) {
            y2 = newY2;
        } else {
            y2 = 0;
        }
    }

    public int getY2() {
        return y2;
    }

    public void setColor(int r, int g, int b) {
        color = new Color(r, g, b);
    }

    public void setColor(Color newColor) {
        color = newColor;
    }

    public Color getColor() {
        return color;
    }

    public abstract void draw(Graphics g);
}

BoundedShape. java

import java.awt.Color;
import java.math.*;

public abstract class BoundedShape extends Shape {
    private boolean filled;

    public BoundedShape() {
        super();
        setFill(false);
    }

    public BoundedShape(int x1, int y1, int x2, int y2, Color color, boolean fill) {
        super(x1, y1, x2, y2, color);
        setFill(fill);
    }

    public void setFill(boolean fill) {
        if (fill == true || fill == false) {
            filled = fill;
        } else {
            throw new IllegalArgumentException("fill has to be either true or false");
        }
    }

    public boolean getFill() {
        return filled;
    }

    public int getUpperLeftX() {
        return Math.min(super.getX1(), super.getX2());
    }

    public int getUpperLeftY() {
        return Math.min(super.getY1(), super.getY2());
    }

    public int getWidth() {
        return Math.abs(super.getX2() - super.getX1());
    }

    public int getHeight() {
        return Math.abs(super.getY2() - super.getY1());
    }
}

Линия. java

import java.awt.Color;
import java.awt.Graphics;

public class Line extends Shape {

    public Line() {
        super();
    }

    public Line(int x1, int y1, int x2, int y2, Color color) {
        super(x1, y1, x2, y2, color);
    }

    @Override
    public void draw(Graphics g) {
        g.setColor(super.getColor());
        g.drawLine(super.getX1(), super.getY1(), super.getX2(), super.getY2());
    }
}

Прямоугольник. java

import java.awt.Color;
import java.awt.Graphics;

public class Rectangle extends BoundedShape {
    public Rectangle() {
        super();
    }

    public Rectangle(int x1, int y1, int x2, int y2, Color color, boolean filled) {
        super(x1, y1, x2, y2, color, filled);
    }

    public void draw(Graphics g) {
        g.setColor(super.getColor());
        if (super.getFill() == false) {
            g.drawRect(super.getUpperLeftX(), super.getUpperLeftY(), super.getWidth(), super.getHeight());
        } else if (super.getFill() == true) {
            g.fillRect(super.getUpperLeftX(), super.getUpperLeftY(), super.getWidth(), super.getHeight());
        }
    }
}

овал. java

import java.awt.Color;
import java.awt.Graphics;

public class Oval extends BoundedShape {
    public Oval() {
        super();
    }

    public Oval(int x1, int y1, int x2, int y2, Color color, boolean filled) {
        super(x1, y1, x2, y2, color, filled);
    }

    public void draw(Graphics g) {
        g.setColor(super.getColor());
        if (super.getFill() == false) {
            g.drawOval(super.getUpperLeftX(), super.getUpperLeftY(), super.getWidth(), super.getHeight());
        } else if (super.getFill() == true) {
            g.fillOval(super.getUpperLeftX(), super.getUpperLeftY(), super.getWidth(), super.getHeight());
        }
    }
}

Заранее спасибо, mabdi36

1 Ответ

0 голосов
/ 07 января 2020

В вашем draw() методе Oval и Rectangle вы звоните super.getWidth() и super.getHeight(). Но ваш рост всегда равен 0, из-за опечатки в вашем конструкторе в Shape:

Вы вызываете setY2() и передаете y1, поэтому y2 == y1, таким образом abs(y2 - y1) = 0.

 public Shape(int x1, int y1, int x2, int y2, Color color) {
        setX1(x1);
        setY1(y1);
        setX2(x2);
        setY2(y1); // change this to setY2(y2)
        setColor(color);
    }

Теперь высота не будет 0, и вы увидите свою форму в 2D.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...