Posted on 2007-06-12 00:57
停留的风 阅读(1572)
评论(0) 编辑 收藏 所属分类:
快速前进的Java
数据库的操作:
public ArrayList SelIdMed(String Id){
Database DB=new Database();//Database中封装了数据库连接,打开、执行的方法
String sql="select * from medInfo where medId="+Integer.parseInt(Id);
ArrayList<Medicine> list=null; //Medicine是一个有几种属性的实体类
Medicine med=null;
try{
DB.OpenCon();
rs=DB.executeQuery(sql);
list=new ArrayList<Medicine>();
while(rs.next()){
med=new Medicine();
med.setMedicineId(rs.getString("medId"));
med.setMedicineName(rs.getString("medName"));
med.setUnit(rs.getString("unit"));
med.setQuantity(rs.getDouble("quantity"));
med.setSideEffect(rs.getString("sideEffect"));
list.add(med);
}
}catch(Exception e){
e.getStackTrace();
}finally{
try{
DB.closeStmt();
DB.closeCon();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
return list;
}
为查询button添加事件,读取数据
public void actionPerformed(ActionEvent e) {
TableModel tm=getJTable1().getModel();
DefaultTableModel dtm=(DefaultTableModel)tm;
Object obj=e.getSource();
if(obj==jButton)
{
pId = (String)jComboBox1.getSelectedItem();//一个下拉列表框
MedBean md=new MedBean(); //MedBean类中定义了上述的方法
ArrayList<Medicine>list=md.SelIdMed(pId);
}
int rowcount=dtm.getRowCount();
for(int i=rowcount-1;i>=0;i--){
dtm.removeRow(i);
}
for(Medicine med:list){
Object[] object={med.getMedicineId(),med.getMedicineName(),med.getQuantity(),med.getSideEffect(),med.getUnit()};
dtm.addRow(object);
}
}
else
{
this.dispose();
}
}
第二种读取数据的方法:
public void actionPerformed(ActionEvent e) {
TableModel tm=getJTable1().getModel();
DefaultTableModel dtm=(DefaultTableModel)tm;
Object obj=e.getSource();
if(obj==jButton)
{
pId = (String)jComboBox1.getSelectedItem();
MedBean md=new MedBean();
Iterator iterator=md.SelIdMed(pId).iterator();
while(iterator.hasNext()){
Medicine med=(Medicine) iterator.next();
Object[] object={med.getMedicineId(),med.getMedicineName(),med.getQuantity(),med.getSideEffect(),med.getUnit()};
dtm.addRow(object);
}
int rowcount=dtm.getRowCount();
for(int i=rowcount-1;i>=0;i--){
dtm.removeRow(i);
}
}
}
else
{
this.dispose();
}
}
对于表的属性要做修改
Object[][] tabledata={};
private String[] colName={"编号","医生姓名","医生电话","开始时间","终止时间","用过次数","可用次数"};
if (jTable == null) {
DefaultTableModel model=new DefaultTableModel(tabledata,column){
public boolean isCellEditable(int row, int column)
{
return false;
};
};
jTable = new JTable(model);
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);