我正在为Eclipse编写一个小插件(使用SWT),该插件创建带有几个按钮的视图。为了不产生冗余代码,我想创建某种工厂方法来为我创建按钮。呼叫将类似于:
Button button0 = createButton(new Button(parent, SWT.PUSH), "Test DB zurücksetzen", btnHight, btnWidth, new FormAttachment(0, 2), new FormAttachment(0,2));
到目前为止,我的工厂是这样的:
private Button createButton(Button buttonToCreate, String buttonText, int height, int width, FormAttachment left, FormAttachment top) {
buttonToCreate.setText(buttonText);
FormData formData = new FormData();
formData.height = height;
formData.width = width;
formData.left = left;
formData.top = top;
buttonToCreate.setLayoutData(formData);
buttonToCreate.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Actions.editPropertys();
}
});
return buttonToCreate;
}
我的问题是:如何将要执行的Actions类的Method作为参数传递给工厂?
答案 0 :(得分:1)
您可以将其作为方法的Runnable
参数进行传递。
例如:
private Button createButton(Button buttonToCreate, String buttonText, int height, int width, FormAttachment left, FormAttachment top, Runnable actionOnSelection) {
// ...
buttonToCreate.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
actionOnSelection.run(); // change here
}
});
}
并调用它:
Button button0 = createButton(new Button(parent, SWT.PUSH), "Test DB zurücksetzen", btnHight, btnWidth, new FormAttachment(0, 2), new FormAttachment(0,2),
Actions::editPropertys); // other change here