我有两节课。 Draw和DrawGUI。在DrawGUI中,我有一个JPanel。对于我的JUnit测试,我需要向Draw类询问getWidth()和getHeight()。所以我的代码如下:

public class Draw {
public static void main(String[] args) throws ColorException {new Draw();}

/** Application constructor:  create an instance of our GUI class */
  public Draw() throws ColorException { window = new DrawGUI(this); }

  protected JFrame window;

  public void getWidth(){
  }


}

class DrawGUI extends JFrame {
  JPanel drawPanel;

  public DrawGUI(Draw application) throws ColorException {
    super("Draw");        // Create the window
    app = application;

    drawPanel = new JPanel();
  }
}


那么如何实现getWidth? getWidth应该从JPanel drawPanel返回宽度

最佳答案

一种选择是更改要在以下位置保存window的弱类型:

public class Draw {
    public static void main(String[] args) throws ColorException {new Draw();}

    /** Application constructor:  create an instance of our GUI class */
    public Draw() throws ColorException { window = new DrawGUI(this); }

    protected DrawGUI window;  // <- is now a DrawGUI

    public int getWidth(){
        return window.getPanelWidth();
    }

}

class DrawGUI extends JFrame {
    JPanel drawPanel;
    ...

    public DrawGUI(Draw application) throws ColorException {
        super("Draw");        // Create the window
        app = application;

        drawPanel = new JPanel();
    }

    public int getPanelWidth() {  // <- added method to get panel width
        return drawPanel.getWidth();
    }
}


还有其他选择。您也可以只为整个面板做吸气剂,但是封装较少。

10-05 23:52