我有两个类。绘制和绘制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/