我创建了一个名为SimpleCanvas
的类,该类将extends
变为JPanel
类,并且我想将一些图形对象呈现到SimpleCanvas
对象上。我还创建了另一个名为Rectangle
的类,我想将一个简单的Rectangle
对象呈现到名为SimpleCanvas
的mainCanvas
对象上。但是,我的问题是我无法弄清楚如何访问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>
即可。