SWT: 테이블 컬럼 내용 수정하기

사용자가 테이블의 특정 Cell의 내용을 편집하기 위해서 Cell에 텍스트 에디터를 띄우고 편집 저장하는 방법을 제공하는 예제 코드

org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet96.java
  1. // org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet96.java
  2. // Eclipse Public License v1.0
  3.  
  4. // 테이블을 순회하기 위한 TableCursor을 생성한다.
    final TableCursor cursor = new TableCursor(table, SWT.NONE);
  5.  
  6. // 사용자가 Cell의 내용을 편집하고 "ENTER"키를 누르면 저장하기 위한 에디터를 생성한다.
    final ControlEditor editor = new ControlEditor(cursor);
    editor.grabHorizontal = true;
    editor.grabVertical = true;

    cursor.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            table.setSelection(new TableItem[] { cursor.getRow()});
        }
  7.  
  8.     // 테이블 커서에서 "ENTER"를 입력하거나 더블클릭 시 사용자가 값을 편집할 수 있도록 텍스트 에디터를 띄운다.
        public void widgetDefaultSelected(SelectionEvent e) {
            final Text text = new Text(cursor, SWT.NONE);
            TableItem row = cursor.getRow();
            int column = cursor.getColumn();
            text.setText(row.getText(column));
            text.addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent e) {
                    // "ENTER"가 입력되면 테이블의 정보를 사용자가 입력한 값으로 업데이트한다.
                    if (e.character == SWT.CR) {
                        TableItem row = cursor.getRow();
                        int column = cursor.getColumn();
                        row.setText(column, text.getText());
                        text.dispose();
                    }
                    // "ESSC"가 입력되면 텍스트 에디터를 닫는다. 변경내용은 반영되지 않음.
                    if (e.character == SWT.ESC) {
                        text.dispose();
                    }
                }
            });

  9.         // 포커스가 다른 곳으로 이동하면 텍스트 에디터를 닫는다.
            text.addFocusListener(new FocusAdapter() {
                public void focusLost(FocusEvent e) {
                    text.dispose();
                }
            });
            editor.setEditor(text);
            text.setFocus();
        }
    });