【发布时间】:2014-11-05 22:10:48
【问题描述】:
我在文本字段上添加了一个修改侦听器,当我尝试打开对话框时,它会触发修改侦听器事件并在打开对话框之前给出空指针异常
这是我的代码
UserNameDialog dialog = new UserNameDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), true);
dialog.init("", userSession.hasAdminRights(), false, true, false, "");
dialog.open();
if (dialog.getReturnCode() == Window.CANCEL) {
return;
}
对话框类
public class UserNameDialog extends TitleAreaDialog {
private Text txtUsername;
@Override
protected Control createDialogArea(Composite parent) {
setMessage("Enter user information and press OK");
setTitle("User Information");
Composite area = (Composite) super.createDialogArea(parent);
Composite container = new Composite(area, SWT.NONE);
container.setLayout(new GridLayout(2, false));
container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
Label lblUserName = new Label(container, SWT.NONE);
lblUserName.setText("User name");
txtUsername = new Text(container, SWT.BORDER);
txtUsername.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtUsername.addListener(SWT.Modify, new Listener()
{
@Override
public void handleEvent(Event event)
{
getButton(IDialogConstants.OK_ID).setEnabled(isValidUsername());
// As I try to open the dialog the handler comes here and throws exception on
// getButton(IDialogConstants.OK_ID)
}
});
if(newUser || currentUserisAdmin)
txtUsername.setEditable(true);
else
txtUsername.setEditable(false);
txtUsername.setText(name);
new Label(container, SWT.NONE);
new Label(container, SWT.NONE);
return area;
}
/**
* Create contents of the button bar.
* @param parent
*/
@Override
protected void createButtonsForButtonBar(Composite parent) {
okButton = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
okButton.setEnabled(false);
}
private boolean isValidUsername()
{
String username = txtUsername.getText();
return username != null && username.trim().length() > 0;
}
}
它在一个对话框中,但我认为它在创建对话框之前被调用,因为 okButton 为空
【问题讨论】:
-
您的代码看起来还不错。您确定没有调用侦听器,或者只是因为您的
if检查而没有调用enableOkButton? -
它很好,但我无法在文本字段上添加 ModifyListener 它给了我空指针异常
-
您必须发布执行此操作的代码。
-
代码添加到问题中
-
好的,最后:请发布堆栈跟踪并指出引发异常的行。
标签: java radio-button swt selection