将静态方法传递给按钮工厂 (Java)
Passing static Method to a button factory (Java)
我正在为 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;
}
我的问题是:如何将要执行的动作的方法作为参数传递给工厂class?
您可以将其作为方法的 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
我正在为 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;
}
我的问题是:如何将要执行的动作的方法作为参数传递给工厂class?
您可以将其作为方法的 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