从班级模型:
public TableModel getTableData() {
TableModel model=null;
try {
String sql = "SELECT eventID as 'Event ID', date as 'Date',eventName as 'Name', time as 'Start Time' FROM Event";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
model = (DbUtils.resultSetToTableModel(rs));
}
catch(SQLException e){
e.printStackTrace();
}
finally {
try {rs.close(); pst.close(); }
catch(SQLException e){} }
return model;
}
public void getEvent(String tableClick) {
Events e = new Events();
try {
pst = conn.prepareStatement("SELECT * FROM Event WHERE eventID='"+tableClick+"' ");
rs = pst.executeQuery();
while(rs.next()){
e.setEventName(rs.getString(2));
e.setEventDate(rs.getDate(3));
e.setEventTime(rs.getString(4));
e.setEventVenue(rs.getString(5));
e.setEventDetail(rs.getString(6));
e.setEventOpportunity(rs.getString(7));
e.setEventMoreDetails(rs.getString(8));
e.setEndTime(rs.getString(9));
}
}
catch(SQLException ex){
ex.printStackTrace();
} finally {
try {
rs.close();pst.close();conn.close();}
catch (Exception ex){}
}
} //end getEvent
从类控制器:
@Override
public void valueChanged(ListSelectionEvent event) {
int rowSelected = view.tableEvent.getSelectedRow();
String tableClick = view.tableEvent.getModel().getValueAt(view.tableEvent.convertRowIndexToModel(rowSelected), 0).toString();
model.getEvent(tableClick); //tell model to change its state based on user input on views - model is instance of class model
}
当我运行程序时,我在Model类的
pst = conn.prepareStatement("SELECT * FROM Event WHERE eventID='"+tableClick+"' ");
行和Controller类的model.getEvent(tableClick);
行显示了堆栈跟踪错误。在NetbeanIDE中以调试模式运行带有断点的程序后,我只能看到e.setEventName(...)
被数据库中的值填充,而Event
bean类的所有其他值均为空。 e.setEventDate(...)
将日期设置为#2222。如果您需要更多信息,我将编辑我的帖子。但这真的困扰我。是ListSelectionListener引起问题,也许
mouseListener
更合适吗?进一步添加,如果我将
getEvent()
更改为public void getEvent(String tableClick) {
Events e = new Events();
try {
pst = conn.prepareStatement("SELECT * FROM Event WHERE eventID='"+tableClick+"' ");
rs = pst.executeQuery();
while(rs.next()){
JOptionPane.showMessageDialog(null, "Yess");
}
}
它仅在第一次单击行时执行,显示为
Yes
。没有第二次单击另一行。 最佳答案
使用MouseListener来检测单击的表行。
@Override
public void mouseClicked(java.awt.event.MouseEvent event) {
int rowSelected = view.tableEvent.rowAtPoint(event.getPoint());
String tableClick = view.tableEvent.getModel().getValueAt(view.tableEvent.convertRowIndexToModel(rowSelected), 0).toString();
model.getEvent(tableClick); //tell model to change its state based on user input on views*/
同样,
rs.close();pst.close();
将在getEvent()方法的try
块的末尾。