jface in action 中的一个例子:
package org.zhyi.rcp.views.composite;
/**
* @author zhouyi
*
*/
import org.eclipse.jface.action.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.*;
//import org.zhyi.rcp.model.UserRole;
import org.zhyi.rcp.dao.BaseDao;
import org.zhyi.rcp.dbmodel.DBUserRole;
public class TableEditorComposite extends Composite {
private Object[] content; //存储传递过来的数据数组
private static final String[] VALUE_SET = new String[] { "xxx", "yyy",
"zzz" };
private static final String NAME_PROPERTY = "角色名";
private static final String VALUE_PROPERTY = "角色编号";
private TableViewer viewer;
public TableEditorComposite(Composite parent,BaseDao baseDao) {
super(parent, SWT.NULL);
//获得显示的对象
content = baseDao.getAll().toArray();
buildControls();
}
private class NewRowAction extends Action {
public NewRowAction() {
super("添加新记录");
}
public void run() {
// EditableTableItem newItem = new EditableTableItem("new row",
// new Integer(2));
// viewer.add(newItem);
}
}
private class DeleteRowAction extends Action {
public DeleteRowAction() {
super("删除当前记录");
}
public void run() {
try {
viewer.refresh();
System.out.println("删除成功!");
} catch (Exception e) {
System.out.println("删除不成功!");
}
}
}
protected void buildControls() {
FillLayout compositeLayout = new FillLayout();
setLayout(compositeLayout);
final Table table = new Table(this, SWT.MULTI);
viewer = buildAndLayoutTable(table);
attachContentProvider(viewer);
attachLabelProvider(viewer);
attachCellEditors(viewer, table);
MenuManager popupMenu = new MenuManager();
IAction newRowAction = new NewRowAction();
IAction deleteRowAction = new DeleteRowAction();
popupMenu.add(newRowAction);
popupMenu.add(deleteRowAction);
Menu menu = popupMenu.createContextMenu(table);
table.setMenu(menu);
viewer.getTable().setLinesVisible(true);
viewer.setInput(content);
}
private void attachLabelProvider(TableViewer viewer) {
viewer.setLabelProvider(new ITableLabelProvider() {
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
switch (columnIndex) {
case 0:
return ((DBUserRole) element).getUserRoleName();
case 1:
return (new Integer(((DBUserRole) element).getUserRoleId())).toString();
default:
return "Invalid column: " + columnIndex;
}
}
public void addListener(ILabelProviderListener listener) {
}
public void dispose() {
}
public boolean isLabelProperty(Object element, String property) {
return false;
}
public void removeListener(ILabelProviderListener lpl) {
}
});
}
private void attachContentProvider(TableViewer viewer) {
viewer.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput,
Object newInput) {
}
});
}
private TableViewer buildAndLayoutTable(final Table table) {
TableViewer tableViewer = new TableViewer(table);
TableLayout layout = new TableLayout();
layout.addColumnData(new ColumnWeightData(20, 25, false));
layout.addColumnData(new ColumnWeightData(20, 25, false));
table.setLayout(layout);
TableColumn nameColumn = new TableColumn(table, SWT.CENTER);
nameColumn.setText("角色名");
TableColumn valColumn = new TableColumn(table, SWT.CENTER);
valColumn.setText("角色编号");
table.setHeaderVisible(true);
return tableViewer;
}
private void attachCellEditors(final TableViewer viewer, Composite parent) {
viewer.setCellModifier(new ICellModifier() {
public boolean canModify(Object element, String property) {
return true;
}
public Object getValue(Object element, String property) {
if (NAME_PROPERTY.equals(property))
return ((DBUserRole) element).getUserRoleName();
else
return new Integer(((DBUserRole) element).getUserRoleId());
}
public void modify(Object element, String property, Object value) {
TableItem tableItem = (TableItem) element;
DBUserRole data = (DBUserRole) tableItem
.getData();
if (NAME_PROPERTY.equals(property))
data.setUserRoleName(value.toString()) ;
else
data.setUserRoleId(((Integer) value).intValue());
viewer.refresh(data);
}
});
viewer.setCellEditors(new CellEditor[] { new TextCellEditor(parent),
new ComboBoxCellEditor(parent, VALUE_SET) });
viewer
.setColumnProperties(new String[] { NAME_PROPERTY,
VALUE_PROPERTY });
}
}
zhyi_12 | 2006年06月25日 03:12 |
/******************************************************************** *DBObject .java */ package org.zhyi.rcp.dbmodel; /** * @author zhouyi * */ import java.util.Hashtable; public abstract class DBObject { protected Hashtable hashtable; public abstract Hashtable getAttributes(); public abstract String description(); public abstract DBObject change(Hashtable hashtable); } /** * DBUserRole.java */ package org.zhyi.rcp.dbmodel; import java.util.Hashtable; /** * @author zhouyi * */ public class DBUserRole extends DBObject { /** * */ private int userRoleId; private String userRoleName; public DBUserRole() { super(); // TODO Auto-generated constructor stub } public DBUserRole(int userRoleId,String userRoleName) { this.userRoleId = userRoleId; this.userRoleName = userRoleName; } /* * (non-Javadoc) * * @see org.zhyi.rcp.util.DBObject#getAttributes() */ @SuppressWarnings("unchecked") public Hashtable getAttributes() { // TODO Auto-generated method stub Hashtable hashtable = new Hashtable(); hashtable.put("userRoleId", "userRoleId"); hashtable.put("userRoleName", "userRoleName"); this.hashtable = hashtable; return hashtable; } public DBObject change(Hashtable ahashtable){ DBUserRole obj = new DBUserRole(); String userRoleId = (String)ahashtable.get("userRoleId"); Integer id =new Integer(userRoleId); String userRoleName = (String)ahashtable.get("userRoleName"); obj.setUserRoleId(id.intValue()); obj.setUserRoleName(userRoleName); return obj; } /* * (non-Javadoc) * * @see org.zhyi.rcp.util.DBObject#description() */ public String description() { // TODO Auto-generated method stub return null; } /** * @return Returns the userRoleId. */ public int getUserRoleId() { return userRoleId; } /** * @param userRoleId * The userRoleId to set. */ public void setUserRoleId(int userRoleId) { this.userRoleId = userRoleId; } /** * @return Returns the userRoleName. */ public String getUserRoleName() { return userRoleName; } /** * @param userRoleName * The userRoleName to set. */ public void setUserRoleName(String userRoleName) { this.userRoleName = userRoleName; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof DBUserRole)) return false; DBUserRole pn = (DBUserRole) o; return pn.getUserRoleId()==getUserRoleId()&&pn.getUserRoleName().equals(getUserRoleName()); } public int hashCode(){ int hash = 37; hash = hash+37*getUserRoleId(); hash = hash + 37*getUserRoleName().hashCode(); return hash; } public String toString(){ return this.getUserRoleName(); } public static void main(String args[]) { DBUserRole dbu = new DBUserRole(); System.out.print(dbu.getAttributes().size()); } } |
zhyi_12 | 2006年06月25日 03:21 |
/** * Config.java * 解析配制文件 * 一个简单的实现:XMLParseConfig.java */ package org.zhyi.rcp.util; /** * @author zhouyi * */ import org.zhyi.rcp.model.Config; public interface ParseConfig { public Config getConfig(); public String description(); } /** * XMLParseConfig.java * 请自行增加获得路径的方法 */ package org.zhyi.rcp.util; /** * @author zhouyi * 使用dom4j解析xml配置文件 * 获得数据库配置的属性值 */ import org.zhyi.rcp.model.Config; import java.io.File; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import org.dom4j.Node; import java.util.Iterator; import java.util.Hashtable; public class XMLParseConfig implements ParseConfig { private Config xmlConfig; private String fileName; Hashtable hashtable = new Hashtable(); public XMLParseConfig() { } public XMLParseConfig(String fileName,Config config) { this.fileName = fileName; this.xmlConfig = config; parse(); fillXmlConfig(); } protected File getXMLFile() { File file = new File(fileName); return file; } protected void parse() { SAXReader reader = new SAXReader(); Document document = null; try { document = reader.read(getXMLFile()); } catch (DocumentException e) { // 下次加 System.out.print("读取失败"); System.out.print(e.getMessage()); } if (document != null) { Element root = document.getRootElement(); for ( Iterator i = root.elementIterator("DataSource"); i.hasNext(); ) { Element foo = (Element) i.next(); treeWalk(foo); // do something } //treeWalk(document); } } // 遍历所有节点 public void treeWalk(Document document) { treeWalk(document.getRootElement()); } // 根据元素遍历 @SuppressWarnings("unchecked") public void treeWalk(Element element) { for (int i = 0, size = element.nodeCount(); i < size; i++) { Node node = element.node(i); // 如果不是叶子节点,继续遍历(树的遍历方法) if (node instanceof Element) { treeWalk((Element) node); } else { if (element.getText()!= null) { //System.out.print(element.getName()); //System.out.print("="); //System.out.println(element.getText()); hashtable.put(element.getName(),element.getText()); } } } } /** * @return Returns the xmlConfig. */ public Config getConfig() { return xmlConfig; } public void fillXmlConfig() { xmlConfig.setDatabaseName((String)hashtable.get("Database")); xmlConfig.setDriver((String)hashtable.get("Driver")); xmlConfig.setName((String)hashtable.get("Username")); xmlConfig.setPassword((String)hashtable.get("Password")); xmlConfig.setUrl((String)hashtable.get("URL")); } /* * (non-Javadoc) * * @see org.zhyi.rcp.util.ParseConfig#description() */ public String description() { // TODO Auto-generated method stub return "使用XML获得数据源"; } } /** * DBHelp.java */ package org.zhyi.rcp.util; /** * @author zhouyi *辅助类 */ import java.util.Hashtable; import org.zhyi.rcp.dbmodel.DBObject; public class DBHelp { /** * */ public DBHelp() { super(); // TODO Auto-generated constructor stub } //把获得的hashtable对象转换为对应的DBObject对象 public static DBObject change(DBObject dbo,Hashtable hashtable){ dbo = dbo.change(hashtable); return dbo; } public static DBObject make(DBObject dbo){ //dbo = dbo.change(); return dbo; } } /** * DBConnection.java * 一个简单的数据库连接 */ package org.zhyi.rcp.util; /** * @author zhouyi * */ import org.zhyi.rcp.model.Config; import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Hashtable; import java.util.Enumeration; import java.util.List; import java.util.ArrayList; import org.zhyi.rcp.dbmodel.DBObject; public class DBConnection { Config config = new Config(); ParseConfig xm; Class c = this.getClass(); Connection con; public DBConnection() { xm = new XMLParseConfig("D://System.xml", config); createConnection(); } public void createConnection() { try { Class.forName(xm.getConfig().getDriver()); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } try { con = DriverManager.getConnection(xm.getConfig().getUrl(), xm .getConfig().getName(), xm.getConfig().getPassword()); } catch (SQLException sqle) { sqle.printStackTrace(); } } public void closeConnection() { try { con.close(); } catch (SQLException e) { } } //获得数据集,将结果集以对象方式存入List中 @SuppressWarnings("unchecked") public List<DBObject> getResult(String sql, DBObject dbo) { List<DBObject> lists = new ArrayList<DBObject>(); try { PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(); //根据sql语句获得数据集,从DBObject对象中获得属性名称 //数据库中的属性名和DBObject中的要一致 //在取出值时要注意值的类型转换 while (rs.next()) { int i=0; Hashtable list = new Hashtable(); for (Enumeration e = dbo.getAttributes().elements(); e.hasMoreElements();i++) { try{ String str = (String)e.nextElement(); str = new String(str.getBytes("utf-8"),"gb2312"); list.put(str,rs.getString(str).trim()); }catch(Exception e2){ System.out.println("数据获取出错:"+e2.getMessage()); } } //获得DBObject对象 DBObject cdbo = DBHelp.change(dbo,list); //将DBObject对象存入List lists.add(cdbo); cdbo = null; } rs.close(); ps.close(); //closeConnection(); } catch (SQLException sqle) { sqle.printStackTrace(); } //返回lists return lists; } } |
/**
* config.java
*/
package org.zhyi.rcp.model;
/**
* @author zhouyi
*数据库属性
*/
public class Config {
private String databaseName;
private String url;
private String driver;
private String name;
private String password;
/**
* @return Returns the databaseName.
*/
public String getDatabaseName() {
return databaseName;
}
/**
* @param databaseName The databaseName to set.
*/
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
/**
* @return Returns the driver.
*/
public String getDriver() {
return driver;
}
/**
* @param driver The driver to set.
*/
public void setDriver(String driver) {
this.driver = driver;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* @return Returns the password.
*/
public String getPassword() {
return password;
}
/**
* @param password The password to set.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return Returns the url.
*/
public String getUrl() {
return url;
}
/**
* @param url The url to set.
*/
public void setUrl(String url) {
this.url = url;
}
}
/**
* BaseDao.java
*/
package org.zhyi.rcp.dao;
import org.zhyi.rcp.util.DBConnection;
import java.util.List;
/**
* @author zhouyi
*
*/
public abstract class BaseDao {
protected DBConnection dbc;
public BaseDao(){
getConnection();
}
//建立数据库连接
public void getConnection() {
dbc= new DBConnection();
}
//关闭连接
public void dispose(){
dbc.closeConnection();
}
//用list获得数据集
public abstract List getAll();
}
/**
* UserRoleDao.java
*/
package org.zhyi.rcp.dao;
/**
* @author 周毅
*
*/
import org.zhyi.rcp.dbmodel.DBUserRole;
import java.util.List;
public class UserRoleDao extends BaseDao{
/**
*
*/
private DBUserRole dbUserRole;
public UserRoleDao() {
super();
dbUserRole = new DBUserRole();
// TODO Auto-generated constructor stub
}
private List getAllUserRole(){
String sql = "select * from userRole order by userRoleId";
return dbc.getResult(sql,dbUserRole);
}
/* (non-Javadoc)
* @see org.zhyi.rcp.dao.BaseDao#getAll()
*/
public List getAll() {
// TODO Auto-generated method stub
return getAllUserRole();
}
}
/**
* DistinctView.java
* 这个是我测试时用的,名字没什么意义
* 反正是用来显示TreeComposite的
* 由于就做了两天,也刚学会用JFace,就将就了
*/
package org.zhyi.rcp.views;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import org.zhyi.rcp.views.composite.TreeComposite;
// import org.zhyi.rcp.views.composite.TableEditorComposite;
// import org.zhyi.rcp.dao.DistinctDao;
/**
* @author zhyi
*
*/
public class DistinctView extends ViewPart {
/**
*
*/
public static final String ID = "org.zhyi.rcp.views.distinctView";
public DistinctView() {
super();
// TODO Auto-generated constructor stub
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
@Override
public void createPartControl(Composite parent) {
// TODO Auto-generated method stub
Composite top = new Composite(parent, SWT.NONE);
FillLayout layout = new FillLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
top.setLayout(layout);
TreeComposite tree = new TreeComposite(top, this);
tree.setBounds(2, 2, 2, 2);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
@Override
public void setFocus() {
// TODO Auto-generated method stub
}
}
System.xml <?xml version = "1.0"?> <System> <DataSource> <Database>Mysql</Database> <URL>jdbc:mysql://127.0.0.1:3306/RCP</URL> <Driver>org.gjt.mm.mysql.Driver</Driver> <Username>root</Username> <Password>你的密码</Password> </DataSource> </System> userrole.sql -- MySQL dump 10.10 -- -- Host: localhost Database: rcp -- ------------------------------------------------------ -- Server version 5.0.18-nt /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `userrole` -- DROP TABLE IF EXISTS `userrole`; CREATE TABLE `userrole` ( `userRoleId` int(11) NOT NULL auto_increment, `userRoleName` varchar(100) default '', PRIMARY KEY (`userRoleId`) ) ENGINE=MyISAM DEFAULT CHARSET=gb2312; -- -- Dumping data for table `userrole` -- /*!40000 ALTER TABLE `userrole` DISABLE KEYS */; LOCK TABLES `userrole` WRITE; INSERT INTO `userrole` VALUES (1,'超级管理员'),(2,'部门管理员'),(3,'专业管理员'); UNLOCK TABLES; /*!40000 ALTER TABLE `userrole` ENABLE KEYS */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; |