主题:jtable 键盘事件
我想双击表格的某个单元格,修改其中的数据,修改完后按enter键激发键盘事件,但我的代码不能执行键盘事件,不知是什么原因?代码如下:
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import java.awt.event.*;
public class Test {
JTable table;
int rownum,colnum;
public Test() throws Exception{
int i,j,RowNum,ColNum;
String sqlstr;
ResultSet res;
JFrame f=new JFrame();
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
Connection con=DriverManager.getConnection(url,"guest","");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
sqlstr="select count(*) from txl";
res=stmt.executeQuery(sqlstr);
res.next();
RowNum=res.getInt(1);
sqlstr="select * from txl";
res=stmt.executeQuery(sqlstr);
ResultSetMetaData rsmd=res.getMetaData();
ColNum=rsmd.getColumnCount();
String[] names=new String[ColNum];
for(i=1;i<=ColNum;i++)
names[i-1]=rsmd.getColumnName(i);
Object[][] info=new Object[RowNum][ColNum];
i=0;
while(res.next()){
for(j=1;j<=ColNum;j++)
info[i][j-1]=res.getObject(j);
i++;
}
res.close();
stmt.close();
con.close();
table=new JTable(info,names);
JScrollPane scrollpane=new JScrollPane(table);
Container cont=f.getContentPane();
cont.add(scrollpane);
table.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER)
System.out.println("hello");
}
});
f.pack();
f.setVisible(true);
}
public static void main( String []args)throws Exception {
new Test();
}
}
请各位指教。
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import java.awt.event.*;
public class Test {
JTable table;
int rownum,colnum;
public Test() throws Exception{
int i,j,RowNum,ColNum;
String sqlstr;
ResultSet res;
JFrame f=new JFrame();
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
Connection con=DriverManager.getConnection(url,"guest","");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
sqlstr="select count(*) from txl";
res=stmt.executeQuery(sqlstr);
res.next();
RowNum=res.getInt(1);
sqlstr="select * from txl";
res=stmt.executeQuery(sqlstr);
ResultSetMetaData rsmd=res.getMetaData();
ColNum=rsmd.getColumnCount();
String[] names=new String[ColNum];
for(i=1;i<=ColNum;i++)
names[i-1]=rsmd.getColumnName(i);
Object[][] info=new Object[RowNum][ColNum];
i=0;
while(res.next()){
for(j=1;j<=ColNum;j++)
info[i][j-1]=res.getObject(j);
i++;
}
res.close();
stmt.close();
con.close();
table=new JTable(info,names);
JScrollPane scrollpane=new JScrollPane(table);
Container cont=f.getContentPane();
cont.add(scrollpane);
table.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER)
System.out.println("hello");
}
});
f.pack();
f.setVisible(true);
}
public static void main( String []args)throws Exception {
new Test();
}
}
请各位指教。