【发布时间】:2014-02-09 15:04:18
【问题描述】:
我正在尝试自己制作一个小的 lwjgl GUI 库。我现在又开始了3次。我的问题是我无法创建一个好的 OOP 设计。 我查看了 Java 内置库 Swing 和 AWT。 我读了代码,研究了 Swing 和 AWT 的类设计。 但我认为这不是为 lwjgl 创建自己的 GUI 库的正确方法,因为它有很大的不同。 我在 OO 中一直遇到的最大问题之一是我无法找到方法。我认为这是一个普遍的编程问题。例如,我有以下课程:
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.
【问题讨论】:
标签: java oop design-patterns user-interface lwjgl