要建議的Window.this,但如果你只是在組件感興趣,那麼爲什麼不:
public class Engine {
Component[] components;
public Engine(Component[] components){
this.components = components;
}
}
public class Window() {
JButton btnDownload;
JButton btnUpload;
public Window() {
btnDownload = new JButton("Download");
btnDownload.setName("Download");
btnUpload = new JButton("Upload");
btnUpload.setName("Upload");
btnDownload.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// create engine passing reference to only the components...
Engine en = new Engine(Window.this.getComponents());
// rest of your code
}
}
public Component[] getComponents() {
return new Component[] { btnDownload, btnUpload };
}
}
其中component是java.awt.Component中,或者你可以從擺動使用的JComponent。
如果你做了這樣的事情,然後我猜每個組件將只通過名字意義。所以你可以在每個組件上使用setName方法(在Window構造函數中顯示),並在引擎中執行某些操作以便在需要時通過名稱訪問它們 - 這可能很糟糕。無論哪種方式,您都需要引用引擎中的不同組件。如果上述示例不適合,您可以使用其他類或接口來公開組件。
Engine e = new Engine(new MyParams(Window.this.btnDownload, Window.this.btnUpload));
引擎構造:
public Engine(MyParams myParams) {
this.myParams = myParams;
}
訪問這些引擎:
this.myParams.getUpload().setText("Engine class has changed me");
完全符合CUGA同意關於通過在窗口
public class MyParams {
private Component download;
private Component upload;
public MyParams(Component download, Component upload) {
this.upload = upload;
this.download = download;
}
public Component getUpload() {
return this.upload;
}
public Component getDownload() {
return this.download;
}
}
創建引擎時
然後參考。這種違背良好的類設計封裝技術。
只是想到的食物
你需要回到OOP的基礎知識。投票結束。 – mre