比較的簡単な質問がありましたが、答える場所がどこにも見つかりません。
アプリケーションでは、セルにテキストのみを表示する単純なSWTテーブルウィジェットを使用しています。インクリメンタルサーチ機能があり、一致する場合はすべてのセルのテキストスニペットを強調表示したいと思います。
したがって、「a」と入力するときは、すべての「a」を強調表示する必要があります。
これを取得するためにSWT.EraseItem
、背景の描画を妨げるリスナーを追加します。現在のセルのテキストに検索文字列が含まれている場合は、位置を検索し、-easyを使用してテキスト内の相対的なx座標を計算しますevent.gc.stringExtent
。
それで、私はオカレンスの「後ろ」に長方形を描くだけです。
さて、これには欠陥があります。テーブルは余白なしでテキストを描画しないので、私のx座標は実際には一致しません-それは数ピクセルだけわずかにずれています!でもいくつ?テーブル自体の図面が使用するセルのテキスト余白はどこで取得できますか?全く分からない。何も見つかりません。
ボーナスの質問:テーブルの描画メソッドもテキストを短縮し、セルに収まらない場合は「...」を追加します。うーん。私のオカレンスファインダーはTableItemのテキストを取得するため、「...」によって消費されているために実際には表示されないオカレンスにもマークを付けようとします。EraseItem描画ハンドラー内の「実際の」テキストではなく、短縮されたテキストを取得するにはどうすればよいですか?
@Override
public void handleEvent( final Event event ) {
final TableItem ti = (TableItem) event.item;
final int index = event.index;
final GC gc = event.gc;
if( ti == null || currentSwyt.isEmpty() ) {
return;
}
final String text = ti.getText( index );
if( !text.contains( currentSwyt ) ) {
return;
}
// search text is contained
final String[] parts = text.split( currentSwyt );
final int swytWidth = gc.stringExtent( currentSwyt ).x;
// calculate positions, must be relative to the text's start
int x = event.x; // THIS IS THE PROBLEM: event.x is not enough!
final int[] pos = new int[parts.length - 1];
for( int i = 0; i < parts.length - 1; i++ ) {
x += gc.stringExtent( parts[i] ).x;
pos[i] = x;
}
final Color red = event.display.getSystemColor( SWT.COLOR_RED );
final Color oldBackground = gc.getBackground();
gc.setBackground( red );
for( int j = 0; j < pos.length; j++ ) {
gc.fillRectangle( pos[j], event.y, swytWidth, event.height );
}
gc.setBackground( oldBackground );
event.detail &= ~SWT.BACKGROUND;
}