我创建了一个名为SimpleCanvas的类,该类将extends变为JPanel类,并且我想将一些图形对象呈现到SimpleCanvas对象上。我还创建了另一个名为Rectangle的类,我想将一个简单的Rectangle对象呈现到名为SimpleCanvasmainCanvas对象上。但是,我的问题是我无法弄清楚如何访问render类的Rectangle方法,并不允许在为SimpleCanvas对象调用redraw事件时从我的mainCanvas类中调用它。

这是我的代码:

SimpleCanvas类:

import javax.swing.*;
import java.awt.*;
import java.util.Vector;

public class SimpleCanvas extends JPanel {
    private int x, y, width, height;
    private Vector objects = new Vector();

    public SimpleCanvas(int x, int y, int width, int height) {
        setPosition(x, y);
        setWidth(width);
        setHeight(height);
    }

    public void setPosition(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public void addObject(Object object) {
        this.objects.add(object);
    }

    public void paintComponent(Graphics g) {
        for (int i = 0; i < this.objects.size(); i++) {
            this.objects.get(i).render(g);
        }
    }
}

SimpleWindow类:
import javax.swing.*;
import java.awt.*;

public class SimpleWindow extends JFrame {
    private int x = 0;
    private int y = 0;
    private int width = 0;
    private int height = 0;
    private Color color = Color.WHITE;
    private String name = "DEFAULT_NAME";

    public SimpleWindow(int x, int y, int width, int height, Color color, String name) {
        this.name = name;
        setSize(width, height);
        setLocation(x, y);
        setBackground(color);
        setVisible(true);
    }
}

矩形类:
import java.awt.*;

public class Rectangle {
    private int x = 0;
    private int y = 0;
    private int width = 0;
    private int height = 0;
    private Color color = Color.WHITE;
    public Rectangle(int x, int y, int width, int height, Color color) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.color = color;
    }
    public void render(Graphics g) {
        g.setColor(this.color);
        g.fillRect(this.x, this.y, this.width, this.height);
    }
}

主分类:
import java.awt.*;

public class Main {
    public static void main(String[] args) {
        SimpleWindow mainWindow = new SimpleWindow(0, 0, 640, 360, Color.WHITE, "Simple Windowing System");
        SimpleCanvas mainCanvas = new SimpleCanvas(0, 0, 640, 360);
        Rectangle mainRectangle = new Rectangle(0, 0, 50, 50, Color.BLUE);
        mainCanvas.addObject(mainRectangle);
        mainWindow.setContentPane(mainCanvas);
    }
}

我觉得好像我也可能正在以错误的方式处理将图形渲染到mainCanvas对象的问题。

预先感谢您的任何帮助!

最佳答案

定义一个模型,该模型代表您的画布视图可以渲染的对象,然后让该视图调用每个对象的render方法。该模型只需要在此example中看到的List<Node>List<Edge>即可。

08-03 19:54