我有两个 类 并且想从一个到另一个获取一个变量

I have two classes and want to get a variable from one to the other

我有两个 class。绘图和 DrawGUI。在 DrawGUI 中我有一个 JPanel。对于我的 JUnit 测试,我需要向 class 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 应该 return 来自 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();
    }
}

还有其他选择。您也可以只为整个面板制作一个 getter,但这样您的封装就更少了。