现在的位置: 首页 > 综合 > 正文

完善上一篇文章中的JTable中的操作

2013年12月09日 ⁄ 综合 ⁄ 共 1886字 ⁄ 字号 评论关闭
public void actionPerformed(ActionEvent e) {
		Vector colum = new Vector();
		Vector rows = new Vector();

		// 查询
		if (e.getSource() == qurey) {
			String sql = "SELECT * FROM employee";
			rs = dbc.executeQuery(sql);
			try {
				rsmd = rs.getMetaData();
				for (int i = 1; i <= rsmd.getColumnCount(); ++i)
					colum.addElement(rsmd.getColumnName(i));
				while (rs.next()) {
					Vector currow = new Vector();
					for (int i = 1; i <= rsmd.getColumnCount(); ++i) {
						currow.addElement(rs.getString(i));
					}
					rows.addElement(currow);
				}

				tablemodel = new DefaultTableModel(rows, colum);
				table = new JTable(tablemodel);
				add(table, BorderLayout.CENTER);
				table.setVisible(true);
				table.setRowHeight(50);

				add(new JScrollPane(table), BorderLayout.CENTER);
				// table.setFillsViewportHeight(true);
				JOptionPane.showMessageDialog(this, "查询成功!");

			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			show();

		}

		// 删除数据
		if (e.getSource() == buttonDelete || e.getSource() == delete) {

			String deletesql = "delete * from employee where number=" + "'"
					+ table.getValueAt(table.getSelectedRow(), 0) + "'";

			dbc.executeUpdate(deletesql);

			int[] row = table.getSelectedRows();
			for (int i = 0; i < row.length; i++) {
				tablemodel.removeRow(row[i]);
			}
			JOptionPane.showMessageDialog(this, "删除成功!");

		}

		// 修改单元格内容并保存
		if (e.getSource() == buttonSave) {
		

			table.getCellEditor().stopCellEditing();
			String val0 = (String) table.getValueAt(table.getSelectedRow(),
					table.getSelectedColumn());
			System.out.println(val0);// val0为取得编辑的内容

			int val1 = table.getSelectedColumn();// val1为编辑的列

			System.out.println(val1);

			String val2 = (String) table.getValueAt(table.getSelectedRow(), 0);// 主键内容
			System.out.println(val2);

			String sql = null;
			try {
				sql = "update employee set " + "["
						+ rsmd.getColumnName(val1 + 1) + "]" + "=" + "'" + val0
						+ "'" + " where number=" + "'" + val2 + "'";
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			boolean bool = false;
			dbc.executeUpdate(sql);
			bool = true;
			if (bool == true) {
				JOptionPane.showMessageDialog(this, "修改成功!");
			} else {
				JOptionPane.showMessageDialog(this, "修改失败!");
			}

		}

	}
//中间还有很多需要完善的地方,暂时先写这么多吧!有需要改的可以给个建议!!谢谢了!!!

抱歉!评论已关闭.