JAVA.SWT/JFace: SWT高級控件之表格 – JAVA編程語言程序開發技術文章

package com.wjc.tree; 
 
import java.util.Hashtable; 
 
import org.eclipse.swt.SWT; 
import org.eclipse.swt.custom.CCombo; 
import org.eclipse.swt.custom.ControlEditor; 
import org.eclipse.swt.custom.TableCursor; 
import org.eclipse.swt.custom.TableEditor; 
import org.eclipse.swt.custom.ViewForm; 
import org.eclipse.swt.events.FocusAdapter; 
import org.eclipse.swt.events.FocusEvent; 
import org.eclipse.swt.events.KeyAdapter; 
import org.eclipse.swt.events.KeyEvent; 
import org.eclipse.swt.events.ModifyEvent; 
import org.eclipse.swt.events.ModifyListener; 
import org.eclipse.swt.events.MouseEvent; 
import org.eclipse.swt.events.MouseListener; 
import org.eclipse.swt.events.SelectionAdapter; 
import org.eclipse.swt.events.SelectionEvent; 
import org.eclipse.swt.layout.FillLayout; 
import org.eclipse.swt.layout.GridData; 
import org.eclipse.swt.layout.GridLayout; 
import org.eclipse.swt.widgets.Composite; 
import org.eclipse.swt.widgets.Display; 
import org.eclipse.swt.widgets.Event; 
import org.eclipse.swt.widgets.Listener; 
import org.eclipse.swt.widgets.Menu; 
import org.eclipse.swt.widgets.MenuItem; 
import org.eclipse.swt.widgets.Shell; 
import org.eclipse.swt.widgets.Table; 
import org.eclipse.swt.widgets.TableColumn; 
import org.eclipse.swt.widgets.TableItem; 
import org.eclipse.swt.widgets.Text; 
import org.eclipse.swt.widgets.ToolBar; 
import org.eclipse.swt.widgets.ToolItem; 
 
public class TableSample { 
    public class TableItemControls{ 
 
     Text text; 
       CCombo combo; 
       TableEditor tableeditor; 
       TableEditor tableeditor1; 
       
       public TableItemControls(Text text, CCombo combo, TableEditor tableeditor, TableEditor tableeditor1) { 
//      super(); 
        this.text = text; 
        this.combo = combo; 
        this.tableeditor = tableeditor; 
        this.tableeditor1 = tableeditor1; 
       } 
       public void dispose() 
       { 
        text.dispose(); 
        combo.dispose(); 
        tableeditor.dispose(); 
        tableeditor1.dispose(); 
       } 
    }; 
    private Shell sShell = null; // @jve:decl-index=0:visual-constraint="10,10" 
    private ViewForm viewForm = null; 
    private ToolBar toolBar = null; 
    private Composite composite = null; 
    private Table table = null; 
    private Menu menu = null; 
    private Hashtable<TableItem, TableItemControls> tablecontrols = new Hashtable<TableItem, TableItemControls>(); 
 
    //創建ViewForm面板放置工具欄和表格 
    private void createViewForm() { 
       viewForm = new ViewForm(sShell, SWT.NONE); 
       viewForm.setTopCenterSeparate(true); 
       createToolBar(); 
       viewForm.setTopLeft(toolBar); 
       createComposite(); 
       viewForm.setContent(composite); 
    } 
 
    //創建工具欄 
    private void createToolBar() { 
       toolBar = new ToolBar(viewForm, SWT.FLAT); 
       final ToolItem add = new ToolItem(toolBar, SWT.PUSH); 
       add.setText("添加"); 
//     add.setImage( ImageFactory.loadImage( toolBar.getDisplay() , ImageFactory.ADD_OBJ)); 
       final ToolItem del = new ToolItem(toolBar, SWT.PUSH); 
       del.setText("刪除"); 
//     del.setImage( ImageFactory.loadImage( toolBar.getDisplay() , ImageFactory.DELETE_OBJ)); 
       final ToolItem back = new ToolItem(toolBar, SWT.PUSH); 
       back.setText("上移"); 
//     back.setImage( ImageFactory.loadImage( toolBar.getDisplay() , ImageFactory.BACKWARD_NAV)); 
       final ToolItem forward = new ToolItem(toolBar, SWT.PUSH); 
       forward.setText("下移"); 
//     forward.setImage( ImageFactory.loadImage( toolBar.getDisplay() , ImageFactory.FORWARD_NAV)); 
       final ToolItem save = new ToolItem(toolBar, SWT.PUSH); 
       save.setText("保存"); 
//     save.setImage( ImageFactory.loadImage( toolBar.getDisplay() , ImageFactory.SAVE_EDIT)); 
       //工具欄按鈕事件處理 
       Listener listener = new Listener(){ 
        public void handleEvent(Event event) { 
         //如果單擊添加按鈕,添加一行,在實際的項目實現中通常是接收輸入的參數,案後添加 
         //這裡為瞭簡單起見,添加固定的一條記錄 
         if ( event.widget == add ) 
         { 
          TableItem item = new TableItem(table, SWT.NONE); 
          item.setText(new String[] {"鄭六", "女","568","zhengliu@sina.com"}); 
         } 
         //如果單擊刪除按鈕 
         else if ( event.widget == del) 
         { 
          //首先獲得表格中所有的行 
          TableItem[] items = table.getItems(); 
          //循環所有行 
          for ( int i=items.length-1;i>=0;i– ){ 
           //如果該行沒有被選中,繼續循環 
           if ( !items[i].getChecked()) 
            continue; 
           //否則選中,查找該表格中是否有該行 
           int index = table.indexOf( items[i]); 
           //如果沒有該行,繼續循環 
           if (index<0) 
            continue; 
           //刪除綁定的控件 
           TableItemControls cons = tablecontrols.get(items[index]); 
           if (cons != null) { 
            cons.dispose(); 
            tablecontrols.remove(items[index]); 
            System.out.println("dispose " + index); 
           } 
           //如果有該行,刪除該行 
//         items[index].dispose(); 
           table.remove( index ); 
           System.out.println("i="+i+", index="+index); 
           System.out.println("行數:" + table.getItemCount()); 
//         table.pack(); 
          } 
         } 
         //如果單擊上移按鈕 
         else if ( event.widget == back) 
         { 
          int selectedRow = table.getSelectionIndex(); 
          if ( selectedRow > 0 ) 
           table.setSelection( selectedRow-1 );//設置選中的行數 
         } 
         //如果單擊下移按鈕 
         else if ( event.widget == forward) 
         { 
          int selectedRow = table.getSelectionIndex(); 
          if ( selectedRow > -1&& selectedRow<table.getItemCount()-1) 
           table.setSelection( selectedRow+1 );//設置選中的行數 
         } 
         //如果單擊保存按鈕 
         else if ( event.widget == save) 
         { 
          TableItem [] items = table.getItems(); 
          //保存到文件或數據庫中,數據持久化,這裡省略 
          for ( int i=0;i<items.length;i++) 
           for (int j=0;j<table.getColumnCount();j++) 
            System.out.println(items[i].getText(j)); 
         } 
        } 
        
       }; 
       //為工具欄的按鈕註冊事件 
       add.addListener( SWT.Selection , listener ); 
       del.addListener( SWT.Selection, listener ); 
       back.addListener( SWT.Selection , listener ); 
       forward.addListener( SWT.Selection, listener ); 
       save.addListener( SWT.Selection, listener ); 
    } 
    //創建放置表格的面板 
    private void createComposite() { 
       GridLayout gridLayout = new GridLayout(); 
       gridLayout.numColumns = 1; 
       composite = new Composite(viewForm, SWT.NONE); 
       composite.setLayout(gridLayout); 
       createTable(); 
    } 
    //創建表格 
    private void createTable() { 
       //表格佈局 
       GridData gridData = new org.eclipse.swt.layout.GridData(); 
       gridData.horizontalAlignment = SWT.FILL; 
       gridData.grabExcessHorizontalSpace = true; 
       gridData.grabExcessVerticalSpace = true; 
       gridData.verticalAlignment = SWT.FILL; 
       
       //創建表格,使用SWT.FULL_SELECTION樣式,可同時選中一行 
       table = new Table(composite, SWT.MULTI|SWT.FULL_SELECTION|SWT.CHECK); 
       table.setHeaderVisible(true);//設置顯示表頭 
       table.setLayoutData(gridData);//設置表格佈局 
       table.setLinesVisible(true);//設置顯示表格線/* 
       //創建表頭的字符串數組 
       String[] tableHeader = {"姓名","性別","電話","電子郵件"}; 
       for (int i=0;i<tableHeader.length;i++){ 
        TableColumn tableColumn = new TableColumn(table, SWT.NONE); 
        tableColumn.setText( tableHeader[i]); 
        //設置表頭可移動,默認為false 
        tableColumn.setMoveable(true); 
       } 
       //添加三行數據 
       TableItem item = new TableItem(table, SWT.NONE); 
       item.setText(new String[] {"張三", "男","123","zhangsan@sina.com"}); 
       //設置圖標 
       //item.setImage( ImageFactory.loadImage( table.getDisplay(),ImageFactory.ICON_BOY)); 
       
       for (int i = 0; i < 5; i++) { 
        item = new TableItem(table, SWT.NONE); 
        item.setText(new String[] {"李四", "男","4582","lisi@sina.com"}); 
       } 
       //設置圖標 
       //item.setImage( ImageFactory.loadImage( table.getDisplay(),ImageFactory.ICON_BOY)); 
       
       item = new TableItem(table, SWT.NONE); 
       item.setText(new String[] {"周五", "女","567","zhouwu@sina.com"}); 
       //設置圖標 
       //item.setImage( ImageFactory.loadImage( table.getDisplay(),ImageFactory.ICON_GIRL)); 
 
       //添加可編輯的單元格 
       // /****************************************************** 
       TableItem [] items = table.getItems (); 
       for (int i=0; i<items.length; i++) { 
        //第一列設置,創建TableEditor對象 
        final TableEditor editor = new TableEditor (table); 
        //創建一個文本框,用於輸入文字 
        final Text text = new Text (table, SWT.NONE); 
        //將文本框當前值,設置為表格中的值 
        text.setText(items[i].getText(0)); 
        //設置編輯單元格水平填充 
        editor.grabHorizontal = true; 
        //關鍵方法,將編輯單元格與文本框綁定到表格的第一列 
        editor.setEditor(text, items[i], 0); 
        //當文本框改變值時,註冊文本框改變事件,該事件改變表格中的數據。 
        //否則即使改變的文本框的值,對表格中的數據也不會影響 
        text.addModifyListener( new ModifyListener(){ 
         public void modifyText(ModifyEvent e) { 
          editor.getItem().setText(1,text.getText()); 
         } 
         
        }); 
        //同理,為第二列綁定下來框CCombo 
        final TableEditor editor1 = new TableEditor (table); 
        final CCombo combo = new CCombo (table, SWT.NONE); 
        combo.add("男"); 
        combo.add("女"); 
        combo.setText(items[i].getText(1)); 
        editor1.grabHorizontal = true; 
        editor1.setEditor(combo, items[i], 1); 
        combo.addModifyListener( new ModifyListener(){ 
         public void modifyText(ModifyEvent e) { 
          editor1.getItem().setText(1,combo.getText()); 
         } 
         
        }); 
        
        // 保存TableItem與綁定Control的對應關系,刪除TableItem時使用 
        TableItemControls cons = new TableItemControls(text, combo, editor, editor1); 
        tablecontrols.put(items[i], cons); 
        
       }   
       // *****************************************************/ 
            // /*************************************************** 
       //創建TableCursor對象,使用上下左右鍵可以控制表格 
       final TableCursor cursor = new TableCursor(table, SWT.NONE); 
       //創建可編輯的控件 
       final ControlEditor editor = new ControlEditor(cursor); 
       editor.grabHorizontal = true; 
       editor.grabVertical = true; 
       //為TableCursor對象註冊事件 
       cursor.addSelectionListener( new SelectionAdapter() { 
        //但移動光標,在單元格上單擊回車所觸發的事件 
        public void widgetDefaultSelected(SelectionEvent e) { 
         //創建一個文本框控件 
         final Text text = new Text(cursor, SWT.NONE); 
         //獲得當前光標所在的行TableItem對象 
         TableItem row = cursor.getRow(); 
         //獲得當前光標所在的列數 
         int column = cursor.getColumn(); 
         //當前光標所在單元格的值賦給文本框 
         text.setText(row.getText(column)); 
         //為文本框註冊鍵盤事件 
         text.addKeyListener(new KeyAdapter() { 
          public void keyPressed(KeyEvent e) { 
           //此時在文本框上單擊回車後,這是表格中的數據為修改後文本框中的數據 
           //然後釋放文本框資源 
           if (e.character == SWT.CR) { 
            TableItem row = cursor.getRow(); 
            int column = cursor.getColumn(); 
            row.setText(column, text.getText()); 
            text.dispose(); 
           } 
           //如果在文本框中單擊瞭ESC鍵,則並不對表格中的數據進行修改 
           if (e.character == SWT.ESC) { 
            text.dispose(); 
           } 
          } 
         }); 
         //註冊焦點事件 
         text.addFocusListener(new FocusAdapter() { 
          //當該文本框失去焦點時,釋放文本框資源 
          public void focusLost(FocusEvent e) { 
           text.dispose(); 
          } 
         }); 
         //將該文本框綁定到可編輯的控件上 
         editor.setEditor(text); 
         //設置文本框的焦點 
         text.setFocus(); 
        } 
        //移動光標到一個單元格上所觸發的事件 
        public void widgetSelected(SelectionEvent e) { 
         table.setSelection(new TableItem[] { cursor.getRow()}); 
        } 
       }); 
       cursor.addMouseListener(new MouseListener() { 
 
        @Override
        public void mouseDoubleClick(MouseEvent e) { 
         // TODO Auto-generated method stub 
         
        } 
 
        @Override
        public void mouseDown(MouseEvent e) { 
         if (e.button==3) { // 右鍵按下,顯示右鍵菜單 
          menu.setVisible(true); 
         } 
        } 
 
        @Override
        public void mouseUp(MouseEvent e) { 
         // TODO Auto-generated method stub 
         
        } 
        
       }); 
       // ******************************************************/ 
       //重新佈局表格 
       for (int i=0; i<tableHeader.length; i++) { 
        table.getColumn (i).pack (); 
       } 
       // /**************************************************** 
       //為單元格註冊選中事件 
       table.addSelectionListener( new SelectionAdapter(){ 
        public void widgetSelected(SelectionEvent e) { 
         //獲得所有的行數 
         int total = table.getItemCount(); 
         //循環所有行 
         for ( int i=0;i<total;i++){ 
          TableItem item = table.getItem(i); 
          //如果該行為選中狀態,改變背景色和前景色,否則顏色設置 
          if (table.isSelected( i )){  
           item.setBackground( sShell.getDisplay().getSystemColor( SWT.COLOR_RED)); 
           item.setForeground( sShell.getDisplay().getSystemColor( SWT.COLOR_WHITE)); 
          }else { 
           item.setBackground( null ); 
           item.setForeground( null ); 
          } 
         } 
        } 
        
       }); 
       // ******************************************************/ 
    } 
 
    public static void main(String[] args) { 
       //調用主窗口 
       Display display = Display.getDefault(); 
       TableSample thisClass = new TableSample(); 
       thisClass.createSShell(); 
       thisClass.sShell.open(); 
       while (!thisClass.sShell.isDisposed()) { 
        if (!display.readAndDispatch()) 
         display.sleep(); 
       } 
//     ImageFactory.dispose(); 
       display.dispose(); 
    } 
 
    //創建主窗口 
    private void createSShell() { 
       sShell = new Shell(); 
       sShell.setText("表格窗口"); 
       sShell.setLayout(new FillLayout()); 
       createViewForm(); 
       createMenu(); 
//     sShell.setImage( ImageFactory.loadImage( sShell.getDisplay(), ImageFactory.SAMPLES)); 
       sShell.setSize(new org.eclipse.swt.graphics.Point(307,218)); 
       sShell.pack(); 
    } 
    //創建上下文菜單 
    private void createMenu() { 
       //創建彈出式菜單 
       menu = new Menu (sShell, SWT.POP_UP); 
       //設置該菜單為表格菜單 
       table.setMenu (menu); 
       //創建刪除菜單項 
       MenuItem del = new MenuItem (menu, SWT.PUSH); 
       del.setText ("刪除"); 
//     del.setImage( ImageFactory.loadImage( sShell.getDisplay(), ImageFactory.DELETE_EDIT)); 
       //為刪除菜單註冊事件,當單擊時,刪除所選擇的行 
       del.addListener (SWT.Selection, new Listener () { 
        public void handleEvent (Event event) { 
         // 此處需添加刪除綁定Control的代碼 
         table.remove (table.getSelectionIndices ()); 
        } 
       }); 
       //創建查看菜單項 
       MenuItem view = new MenuItem (menu, SWT.PUSH); 
       view.setText ("查看"); 
//     view.setImage( ImageFactory.loadImage( sShell.getDisplay(), ImageFactory.SCOPY_EDIT)); 
       //為查看菜單項註冊事件,當單擊時打印出所選的姓名 
       view.addListener (SWT.Selection, new Listener () { 
        public void handleEvent (Event event) { 
         TableItem[] items = table.getSelection(); 
         for (int i=0;i<items.length;i++) 
          System.out.print(items[i].getText()); 
        } 
       }); 
       
       table.setMenu(menu); 
    } 
 
    } 

作者“TinyKing”

發佈留言