我有两节课。 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
的宽度答案 0 :(得分:1)
一种选择是更改您在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,但是你的封装更少。