【问题标题】:Lwjgl GUI libraryLwjgl GUI 库
【发布时间】: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


    【解决方案1】:

    您需要确保Component每个 子类都有一个paintComponent() 方法。您可以通过在超类中将其声明为抽象来做到这一点:

    abstract class Component {
    
      /* fields of Component class */
    
      public abstract void paintComponent();
    
    }
    

    这将强制Component的每个非抽象子类都实现该方法,否则编译器会报错。

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


    另外:因为Component 已经出现在类的名称中,所以更习惯将方法命名为paint()。这避免了调用中的重复,例如myComponent.paint() 而不是 myComponent.paintComponent()

    【讨论】:

      【解决方案2】:

      如果您需要将按钮存储为组件,您可以使用 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;
      }
      

      或者,您可以将按钮与不是按钮的组件分开存储,然后不需要转换它们。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-30
        • 2015-06-12
        • 2015-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多