java - 我有两个类,想要从一个类到另一个类获取一个变量

标签 java swing awt

我有两个类。绘制和绘制GUI。在 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 的宽度

最佳答案

一种选择是更改您保存窗口的弱类型:

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();
    }
}

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

<小时/>

关于java - 我有两个类,想要从一个类到另一个类获取一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36967528/

相关文章:

java - 如何对 JOptionPane.showMessageDialog 的 OK 执行操作

java - 运行没有main方法的Java程序?

java - 将 Java Gui 连接到不同类中的不同实现

java - Swing 定时器与 Util 定时器

java - 如何使用java Socket编程在同一个文件中实现对等代码,即服务器和客户端代码

java - 递归二叉搜索树插入

java - 在 Swing 中移动背景图像

java - StackOverflowError 由 TableModelListener 引起

java - 在 Java 中处理未初始化的参数?

java - JSpeex 解码不工作