SWT Tips and Samples 基礎編 > LineBackgroundListener |
|
LineBackgroundListenerStyledTextには、キーワードが含まれる行の背景色を自動で変更できる機能があります。この機能を使うには、LineBackgroundListenerを実装します。使い方は簡単です。LineBackgroundListenerの唯一のメソッドlineGetBackgroundをオーバーライドするだけです。このメソッドは、テキストウィジェットのテキストが変更されると呼び出されます。そして、event.lineTextに変更された行の文字列が格納されているので、これを使ってキーワードが含まれているか調べます。該当行の背景色を変更するには、event.lineBackgroundにColorオブジェクトを代入します。 Color red = ...; StyledText text = new SourceViewer(...); ... text.addLineBackgroundListener(new LineBackgroundListener(){ public lineGetBackground(LineBackgroundEvent event){ //event.lineTextに変更された行の文字列が格納される。 if (event.lineText.indexOf("キーワード") > -1){ //event.lineBackgroundにColorオブジェクトを代入すると背景所が変わる。 event.lineBackground = red; } } }); スクリーンショットSWTというキーワードを含む行が赤色の背景色、また#で始まる行があると青色の背景色になるサンプルプログラムです。 ソースコード (LineBackgroundListenerTest.java)import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.swt.widgets.*; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.LineBackgroundEvent; import org.eclipse.swt.custom.LineBackgroundListener; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.layout.*; public class LineBackgroundListenerTest{ Color blue; Color red; public static void main(String[] args) { new LineBackgroundListenerTest(); } public LineBackgroundListenerTest() { Display display = new Display(); Shell shell = new Shell(display); shell.setText("LineBackgroundListenerTest"); shell.setLayout(new FillLayout()); blue = display.getSystemColor(SWT.COLOR_BLUE); red = display.getSystemColor(SWT.COLOR_RED); Font font = new Font(display, "MS ゴシック", 10, SWT.NORMAL); StyledText text = new StyledText(shell, SWT.BORDER | SWT.MULTI); text.setFont(font); text.addLineBackgroundListener( new MyLineBackgroundListener()); shell.setSize(300,200); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } font.dispose(); display.dispose(); } class MyLineBackgroundListener implements LineBackgroundListener{ Pattern commentPattern; public MyLineBackgroundListener(){ commentPattern = Pattern.compile("^[\t ]*#.*"); } public void lineGetBackground(LineBackgroundEvent event) { String line = event.lineText; if (line.indexOf("SWT") > -1){ event.lineBackground = red; } Matcher commentMatcher = commentPattern.matcher(line); if (commentMatcher.matches()){ event.lineBackground = blue; } } } } 最新更新日: 2004年8月8日 |
- PR -
【Sony】大手他社よりも安い!ビジネス向け光・100Mしかも固定IP付!今なら更に初期費用最大15,000円OFF!
オフィス用品・オフィス家具 価 格 交 渉 可!
|
||||
|
|||||
Copyright(C) 2003,2004 Jasmin Project. All Right Reserved. |
SEO | [PR] 爆速!無料ブログ 無料ホームページ開設 無料ライブ放送 | ||