2016-05-01 4 views
1

Ich habe zwei Klassen. Draw und DrawGUI. In DrawGUI habe ich ein JPanel. Für meinen JUnit Test muss ich die Klasse Draw nach getWidth() und getHeight() fragen. So ist mein Code wie folgt aus:Ich habe zwei Klassen und möchte eine Variable von einem zum anderen

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

So wie ich getWidth implementieren? getWidth sollte die Breite der JPanel DrawPanel

+0

'' 'return window.getWidth();' ''? –

+0

@JornVernee Ich möchte getWidth aus dem JPanel DrawPanel und nicht das komplette Fenster. – Sonius

Antwort

1

Eine Option zurückzukehren ist die schwache Typ ändern Sie das Speichern Ihrer window unter:

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

Es gibt andere Optionen. Sie könnten auch nur ein Getter für das gesamte Panel erstellen, aber dann haben Sie weniger Verkapselung.