TreeEditorはTableウィジェットに対するTableEditorと同様に、Treeで表示しているデータを編集するためのクラスです。各アイテムに対して任意のウィジェットをエディタとして適用することができます。Treeでアイテムを選択した場合にTextウィジェットで編集する例を示します(一度アイテムを選択状態にし、再度クリックすると編集可能状態になります)。
TableEditorのサンプルと同様にENTERキーで決定、ESCキーでキャンセルする処理も実装してみます。
import org.eclipse.swt.*; import org.eclipse.swt.custom.*; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; public class TreeEditorSample1 { // 最後に選択されたTreeItem private static TreeItem lastItem = null; public static void main (String [] args) { Display display = new Display (); Shell shell = new Shell(display); shell.setText("TreeEditor Sample 1"); shell.setLayout(new FillLayout()); // Treeウィジェットを生成 final Tree tree = new Tree(shell, SWT.BORDER); // TreeItemを追加 TreeItem item1 = new TreeItem(tree,SWT.NULL); item1.setText("データベース"); TreeItem item2 = new TreeItem(item1,SWT.NULL); item2.setText("MySQL"); TreeItem item3 = new TreeItem(item1,SWT.NULL); item3.setText("PostgreSQL"); // TreeEditorを生成 final TreeEditor treeEditor = new TreeEditor(tree); treeEditor.grabHorizontal = true; // TreeでTreeItemが選択されたときの処理 tree.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e){ TreeItem item = (TreeItem)e.item; if(item==null){ return; } // すでに選択状態のTreeItemが再選択された場合のみ編集可能とする if(item!=lastItem){ lastItem = item; return; } // セルエディタを設定 final Text text = new Text(tree, SWT.BORDER); text.setText(item.getText()); // フォーカスが外れたときの処理 text.addFocusListener(new FocusAdapter(){ public void focusLost(FocusEvent e){ TreeItem item = treeEditor.getItem(); item.setText(text.getText()); text.dispose(); } }); // ENTERとESC押下時の処理 text.addKeyListener(new KeyAdapter(){ public void keyReleased(KeyEvent e){ if(e.character==SWT.CR){ TreeItem item = treeEditor.getItem(); item.setText(text.getText()); text.dispose(); } else if(e.keyCode==SWT.ESC){ text.dispose(); } } }); treeEditor.setEditor (text,item); text.setFocus(); text.selectAll(); } }); // ウィンドウのサイズを指定 shell.setSize(200,100); shell.open(); while (!shell.isDisposed ()){ if (!display.readAndDispatch ()){ display.sleep (); } } display.dispose (); } }
上記のコードを実行すると以下のようになります。
最終更新時間:2004年08月27日 03時27分52秒