0

私はこのビットのコードを持っています:

import org.eclipse.swt.widgets.Table;

....

Table table = code_that_returns_table_object;

table.addSelectionListener(new SelectionAdapter() {
  public void widgetSelected(SelectionEvent e) {
    Table table = e.getSource();
  }
});

イベントのソースが Table オブジェクトであることは明らかですが、コンパイルしようとすると次のエラーが発生します。

incompatible types
found   : java.lang.Object
required: org.eclipse.swt.widgets.Table
          Table table = e.getSource();

私がこれを行う場合:

table.addSelectionListener(new SelectionAdapter() {
  public void widgetSelected(SelectionEvent e) {
    System.out.println(e.getSource().getClass());
  }
});

出力は「org.eclipse.swt.widgets.Table」を出力します

互換性のない型のエラーが発生する理由と、その修正方法を誰か教えてもらえますか?

4

1 に答える 1

0

メソッドは、getSource()タイプ のオブジェクトを返すものとして宣言されていますObject。使用する必要があります

public void widgetSelected(SelectionEvent e) {
    Table table = (Table) e.getSource();
}

確実であれば、それはTableオブジェクトになります。は他のものになる可能性があるためObject、コンパイラは互換性のない参照を割り当てることを防ぎます。

于 2013-10-10T01:04:41.510 に答える