2014-02-09 65 views
2

我想自己製作一個小的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. 

回答

2

你需要確保每ComponentpaintComponent()方法。你可以通過在超聲明爲抽象:

abstract class Component { 

    /* fields of Component class */ 

    public abstract void paintComponent(); 

} 

這將迫使Component每個非抽象子類來實現方法,否則編譯器會產生一個錯誤。

Swing做同樣的事情:JComponenta method paint(Graphics)


旁白:因爲Component是在類的名稱已經存在,它會更習慣命名方法paint()代替。這避免了通話中的重複,例如myComponent.paint()而不是myComponent.paintComponent()

1

如果您需要將您的按鈕保存爲組件,您可以使用instanceof運算符來檢查它們是否確實按鈕,然後由澆鑄他們這樣叫,只有按鍵有任何方法:

for(int i = 0; i < this.components.size(); i++) { 
    if(components.get(i) instanceof Button){ 
     Button b = (Button)components.get(i); 
     b.paintComponent(); //or any other methods that buttons have. 
    } 
    //treat it as a normal component; 
} 

或者你可以將你的按鈕單獨存放在不是按鈕的組件中,然後不需要施放它們。