我想自己製作一個小的lwjgl GUI庫。我現在重新開始了三次。我的問題是我無法創建一個好的OOP設計。 我看了一下在Swing和AWT庫中構建的Java。 我讀了代碼,並研究了Swing和AWT的類設計。 但我認爲這不是爲lwjgl製作我自己的GUI庫的正確方法,因爲它有很多不同之處。 我在OO中遇到的最大問題之一是我無法達到某種方法。我認爲這是一個普遍的編程問題。例如,我有以下類:Lwjgl GUI庫
class Container {
private ArrayList<Component> components = new ArrayList<Component>();
public void add(Component c) { // Accepts only Component objects, or child objects of Component
this.components.add(c);
}
public volid paintAll() {
for(int i = 0; i < this.components.size(); i++) {
// Not possible, the Component object has no method paintComponent(), the
// class which extends Component does. This can be a button, but it's stored as
// a Component. So the method paintComponent "Does not exist" in this object,
// but is does.
this.components.get(i).paintComponent(); // error
}
}
}
class Component {
private int x;
private int y;
private int width;
private int height;
/* methods of Component class */
}
class Button extends Component {
private String text;
public Button(String text) {
this.text = text;
}
public void paintComponent() {
/* Paint the button */
}
}
// In Swing, the Component class has no method like paintComponent.
// The container can only reach the methods of Component, and can not use methods of
// classes which extends Component.
// That's my problem. How can I solve this?
Container container = new Container();
Button b = new Button("This is a button");
Container.add(b); // b "Is a" Component.